post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2470889/python3-using-remove-and-sum
class Solution: def average(self, salary: List[int]) -> float: salary.remove(min(salary)) salary.remove(max(salary)) return sum(salary)/len(salary)
average-salary-excluding-the-minimum-and-maximum-salary
[python3] using remove and sum
hhlinwork
0
28
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,200
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2462497/Python3-solutions-Easy-with-POP
class Solution: def average(self, salary: List[int]) -> float: salary.sort(reverse=False) salary.pop() salary.pop(0) sal = 0 for i in salary: sal = sal+i average = sal/len(salary) return average
average-salary-excluding-the-minimum-and-maximum-salary
Python3 solutions -Easy with POP
prakashpandit
0
38
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,201
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2436764/Average-Salary-Excluding-the-Minimum-and-Maximum-Salary
class Solution: def merge(self,arr,L,R,m): i= j= k = 0 while i < len(L) and j<len(R): if L[i]>R[j]: arr[k]= R[j] j+=1 else: arr[k] =L[i] i+=1 k+=1 while i<len(L): arr[k]= L[i] i+=1 k+=1 while j<len(R): arr[k]= R[j] j+=1 k+=1 def mergeSort(self,arr): if len(arr)>1: m = len(arr)//2 L = arr[:m] R = arr[m:] self.mergeSort(L) self.mergeSort(R) self.merge(arr,L,R,m) def average(self, salary: List[int]) -> float: self.mergeSort(salary) print(salary) neededArray =salary[1:-1] x = sum(neededArray) avg = x/len(neededArray) return avg
average-salary-excluding-the-minimum-and-maximum-salary
Average Salary Excluding the Minimum and Maximum Salary
dhananjayaduttmishra
0
23
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,202
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2436764/Average-Salary-Excluding-the-Minimum-and-Maximum-Salary
class Solution: def average(self, salary: List[int]) -> float: salary.sort() neededArray =salary[1:-1] x = sum(neededArray) avg = x/len(neededArray) return avg
average-salary-excluding-the-minimum-and-maximum-salary
Average Salary Excluding the Minimum and Maximum Salary
dhananjayaduttmishra
0
23
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,203
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2436764/Average-Salary-Excluding-the-Minimum-and-Maximum-Salary
class Solution: def average(self, salary: List[int]) -> float: maximum = 999 minimun = 10**6 +1 for i in salary: if i > maximum : maximum = i if i < minimun : minimun = i x = 0 count = 0 for i in salary : if i != maximum and i != minimun : x+=i count+=1 avg = x/count return avg
average-salary-excluding-the-minimum-and-maximum-salary
Average Salary Excluding the Minimum and Maximum Salary
dhananjayaduttmishra
0
23
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,204
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2329188/One-line-python
class Solution: def average(self, salary: List[int]) -> float: return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)
average-salary-excluding-the-minimum-and-maximum-salary
One line python
sunakshi132
0
79
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,205
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2316058/Just-another-one-liner
class Solution: def average(self, salary: List[int]) -> float: return sum(sorted(salary)[1:-1]) / (len(salary) - 2)
average-salary-excluding-the-minimum-and-maximum-salary
Just another one liner
pcdean2000
0
20
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,206
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2307123/Python-oror-One-Line
class Solution: def average(self, salary: List[int]): return (sum(salary) - max(salary) - min(salary)) / (len(salary) - 2)
average-salary-excluding-the-minimum-and-maximum-salary
Python || One Line
Aman-Mahore
0
47
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,207
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2296893/ONE-LINER-oror-Beats-63-oror-Easiest-Solution
'''class Solution: def average(self, salary: List[int]) -> float: return (sum(salary)-(min(salary)+max(salary)))/(len(salary)-2)'''
average-salary-excluding-the-minimum-and-maximum-salary
ONE LINER || Beats 63% || Easiest Solution
keertika27
0
47
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,208
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2296308/python3-or-Solution
class Solution: def average(self, salary: List[int]) -> float: salary.remove(min(salary)) salary.remove(max(salary)) avg = 0 for i in range(0,len(salary)): avg += salary[i] return float(avg / len(salary))
average-salary-excluding-the-minimum-and-maximum-salary
python3 | Solution
arvindchoudhary33
0
42
average salary excluding the minimum and maximum salary
1,491
0.627
Easy
22,209
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1352274/Python3-simple-solution-using-list
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]
the-kth-factor-of-n
Python3 simple solution using list
EklavyaJoshi
1
139
the kth factor of n
1,492
0.624
Medium
22,210
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1257792/Python-oror-clean-and-concise-oror
class Solution: def kthFactor(self, n: int, k: int) -> int: u=[] for i in range(1,int(n**(0.5))+1): if n%i==0: u.append(i) if n//i != i: u.append(n//i) u.sort() if k<=len(u): return u[k-1] return -1
the-kth-factor-of-n
Python || clean and concise ||
chikushen99
1
261
the kth factor of n
1,492
0.624
Medium
22,211
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2823278/Easy-Python3-SolutionororO(N)-oror-7-Line-Code
class Solution: def kthFactor(self, n: int, k: int) -> int: count = 0 for i in range(1, n + 1): if n % i == 0: count += 1 if count == k: return i return -1
the-kth-factor-of-n
Easy Python3 Solution||O(N) || 7 Line Code
ghanshyamvns7
0
2
the kth factor of n
1,492
0.624
Medium
22,212
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2822865/Python3-solution
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) try: return factors[k-1] except: return -1
the-kth-factor-of-n
Python3 solution
SupriyaArali
0
2
the kth factor of n
1,492
0.624
Medium
22,213
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2759752/python-Simple-code
class Solution: def kthFactor(self, n: int, k: int) -> int: l = [] for i in range(1,n+1): if(n%i == 0): l.append(i) if k <= len(l): return l[k-1] return -1
the-kth-factor-of-n
python Simple code
manishx112
0
11
the kth factor of n
1,492
0.624
Medium
22,214
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2562310/Python-or-T-O(n-log(n))-or-93.39-faster
class Solution: def kthFactor(self, n: int, k: int) -> int: fs =list(self.factors(n)) # to make it subscriptable fs.sort() return fs[k-1] if len(fs) >= k else -1 def factors(self, n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) ```
the-kth-factor-of-n
Python | T-O(n log(n)) | 93.39% faster
Yusuf0
0
61
the kth factor of n
1,492
0.624
Medium
22,215
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2532245/easy-python-solution
class Solution: def kthFactor(self, n: int, k: int) -> int: counter = 1 for i in range(1, n+1) : if n%i == 0 : if counter == k : return i else : counter += 1 return -1
the-kth-factor-of-n
easy python solution
sghorai
0
26
the kth factor of n
1,492
0.624
Medium
22,216
https://leetcode.com/problems/the-kth-factor-of-n/discuss/2015395/Python-solution-faster-than-99
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 factors[k-1] return -1
the-kth-factor-of-n
Python solution faster than 99%
alishak1999
0
143
the kth factor of n
1,492
0.624
Medium
22,217
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1982600/Python-3-Solution
class Solution: def kthFactor(self, n: int, k: int) -> int: f = [] for i in range(1,n+1): if n % i == 0: f.append(i) try: return f[k-1] except IndexError: return -1
the-kth-factor-of-n
Python 3 Solution
DietCoke777
0
68
the kth factor of n
1,492
0.624
Medium
22,218
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1952456/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def kthFactor(self, n: int, k: int) -> int: arr = [] for i in range(1, n+1): if n%i == 0: arr.append(i) print(arr) return arr[k-1] if (k <= len(arr)) else -1
the-kth-factor-of-n
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
60
the kth factor of n
1,492
0.624
Medium
22,219
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1856811/time-o(sqrt(n))-space-o(1)-one-pass-self-explain-easy-to-understand
class Solution: def kthFactor(self, n: int, k: int) -> int: if not n or not k: return 0 cnt = 0 for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: cnt += 1 if k == cnt: return i k -= cnt for i in range(int(math.sqrt(n - 1)), 0, -1): if n % i == 0: k -= 1 if k == 0: return n // i return -1
the-kth-factor-of-n
time o(sqrt(n)) space o(1) one pass self-explain easy to understand
BichengWang
0
118
the kth factor of n
1,492
0.624
Medium
22,220
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1856781/o(sqrt(n))-one-pass
class Solution: def kthFactor(self, n: int, k: int) -> int: if not n or not k: return 0 small_factors = [] large_factors = [] for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: small_factors.append(i) large_factors.append(n // i) if len(small_factors) == k: return small_factors[-1] if small_factors[-1] == large_factors[-1]: del large_factors[-1] if k - len(small_factors) > len(large_factors): return -1 return large_factors[-(k - len(small_factors))]
the-kth-factor-of-n
o(sqrt(n)) one pass
BichengWang
0
57
the kth factor of n
1,492
0.624
Medium
22,221
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1800250/Python3-accepted-solution
class Solution: def kthFactor(self, n: int, k: int) -> int: count=0 for i in range(1,n+1): if(n%i == 0): count+=1 if(count==k): return i return -1
the-kth-factor-of-n
Python3 accepted solution
sreeleetcode19
0
44
the kth factor of n
1,492
0.624
Medium
22,222
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1781477/python3-32ms-dictionary-implementation-or-faster-than-88-uses-lesser-memory-than-90
class Solution: def kthFactor(self, n: int, k: int) -> int: factors = dict() #taking a dictionary here so that the factors do not get repeated. count = 0 for i in range(1, int(n**0.5)+1): if n%i == 0: if not factors.get(i): #enter in the dictionary only if the factor hasn't already been added to the dict, you can put any value corresponding to the factor(key) in the dictionary. factors[i] = 1 for i in range(int(n**0.5), 0, -1): if n%i == 0: if not factors.get(n//i): count += 1 factors[n//i] = count factors = list(factors.keys()) if len(factors) < k: return -1 return factors[k-1] ```
the-kth-factor-of-n
python3 - 32ms dictionary implementation | faster than 88% uses lesser memory than 90%
kgrv
0
48
the kth factor of n
1,492
0.624
Medium
22,223
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1669060/Python3-Simple-solution-faster-than-97.08-of-submissions.-Time-and-space-complexity
class Solution: def kthFactor(self, n: int, k: int) -> int: """Return the kth factor of an array n""" narr = ([]) for i in range(n, 0, -1): if n % i == 0: narr.append(i) # Then I only change n if n % i-1 == 0 or better still, n % i==0 if n % i-1 == 0: n = n//i-1 narr.sort() print(narr) for i in range(len(narr)): if i + 1 == k: return narr[i] return -1
the-kth-factor-of-n
Python3 Simple solution faster than 97.08% of submissions. Time and space complexity?
Osereme
0
60
the kth factor of n
1,492
0.624
Medium
22,224
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1650551/Simple-Python-O(n)-Time-O(n)-Space
class Solution: def kthFactor(self, n: int, k: int) -> int: resulting_array = [] for i in range(1, n+1): if n % i == 0: resulting_array.append(i) if len(resulting_array) < k: return -1 else: return resulting_array[k-1]
the-kth-factor-of-n
Simple Python O(n) Time O(n) Space
KoalaKeys
0
65
the kth factor of n
1,492
0.624
Medium
22,225
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1649868/Python-3-No-lists-or-dictionaries-solution
class Solution: def kthFactor(self, n: int, k: int) -> int: curi = 0 for i in range(1, n+1): if n%i == 0: curi += 1 if curi == k: return i return -1
the-kth-factor-of-n
[Python 3] No lists or dictionaries solution
lpswheatley
0
84
the kth factor of n
1,492
0.624
Medium
22,226
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1594342/Python-Two-Approaches-or-No-Extra-Space
class Solution: def kthFactor(self, n: int, k: int) -> int: # 1st Approach # Time: O(sqrt(n)) # Space: O(n) res = [] ans = [] for i in range(1, int(n**0.5)+1): if n % i == 0: if n // i == i: res.append(i) else: res.append(i) ans.insert(0, n//i) res.extend(ans) if len(res) >= k: return res[k-1] return -1 # 2nd Approach: # Time: O(n) # Space: O(1) for i in range(1, n+1): if n % i == 0: k -= 1 if k == 0: return i return -1
the-kth-factor-of-n
Python Two Approaches | No Extra Space ✔
leet_satyam
0
155
the kth factor of n
1,492
0.624
Medium
22,227
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1543541/Python-solution-oror-traversing-till-N2
class Solution: def kthFactor(self, n: int, k: int) -> int: res = [1] for i in range(2,int(ceil(n/2))+1): if n % i == 0: res.append(i) res.append(n) if k > len(res): return -1 return res[k-1]
the-kth-factor-of-n
Python solution || traversing till N/2
s_m_d_29
0
97
the kth factor of n
1,492
0.624
Medium
22,228
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1442805/Python3Python-Simple-solution-using-is_integer-method-w-comments
class Solution: def kthFactor(self, n: int, k: int) -> int: # A function to check if a number is integer or not def is_integer(n): if isinstance(n, int): return True if isinstance(n, float): return n.is_integer() return False # Get all the factors of the number factors = [] for i in range(1,n+1): if is_integer(n/i): factors.append(i) # k is less or equal to no. of factors, return if k <= len(factors): return factors[k-1] return -1
the-kth-factor-of-n
[Python3/Python] Simple solution using is_integer method w/ comments
ssshukla26
0
268
the kth factor of n
1,492
0.624
Medium
22,229
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1110058/Python-or-Beats-99-Memory-92-or-Simple
class Solution: def kthFactor(self, n: int, k: int) -> int: i=1 while k: if n%i==0: k-=1 if i>n: return -1 i+=1 return i-1
the-kth-factor-of-n
Python | Beats 99% Memory 92% | Simple
rajatrai1206
0
123
the kth factor of n
1,492
0.624
Medium
22,230
https://leetcode.com/problems/the-kth-factor-of-n/discuss/1070258/Python-Easy-O(n)
class Solution: def kthFactor(self, n: int, k: int) -> int: count = 0 for i in range(1,n+1): if n % i == 0: count+= 1 if count == k: return i return -1
the-kth-factor-of-n
Python Easy O(n)
Akarsh_B
0
56
the kth factor of n
1,492
0.624
Medium
22,231
https://leetcode.com/problems/the-kth-factor-of-n/discuss/960417/Python-7-liner-easy-solution
class Solution(object): def kthFactor(self, n, k): res= [] for i in range(1,n+1): if n%i==0: res.append(i) if len(res)==k: break return res[-1] if len(res)==k else -1
the-kth-factor-of-n
Python 7 liner easy solution
rachitsxn292
0
182
the kth factor of n
1,492
0.624
Medium
22,232
https://leetcode.com/problems/the-kth-factor-of-n/discuss/959780/Python3-O(N)-and-O(logN)-solns
class Solution: def kthFactor(self, n: int, k: int) -> int: for i in range(1, n+1): if not n%i: k -= 1 if not k: return i return -1
the-kth-factor-of-n
[Python3] O(N) & O(logN) solns
ye15
0
61
the kth factor of n
1,492
0.624
Medium
22,233
https://leetcode.com/problems/the-kth-factor-of-n/discuss/959780/Python3-O(N)-and-O(logN)-solns
class Solution: def kthFactor(self, n: int, k: int) -> int: for i in range(1, int(sqrt(n))+1): # forward pass if not n%i: k -= 1 if not k: return i while i > 0: # backward pass if i * i < n: if not n%i: k -= 1 if not k: return n//i i -= 1 return -1
the-kth-factor-of-n
[Python3] O(N) & O(logN) solns
ye15
0
61
the kth factor of n
1,492
0.624
Medium
22,234
https://leetcode.com/problems/the-kth-factor-of-n/discuss/959662/Simple-7-Line-Python-Iterative
class Solution: def kthFactor(self, n: int, k: int) -> int: count = 0 for i in range(1,n+1): if n % i == 0: count += 1 if count == k: return i return -1
the-kth-factor-of-n
Simple 7 Line Python Iterative
Xianggg
0
24
the kth factor of n
1,492
0.624
Medium
22,235
https://leetcode.com/problems/the-kth-factor-of-n/discuss/713713/Intuitive-approach-by-iteration
class Solution: def kthFactor(self, n: int, k: int) -> int: factors = [1] if n > 3: factors = factors + [i for i in range(2, n//2+1) if n % i == 0] factors.append(n) return -1 if k > len(factors) else factors[k-1]
the-kth-factor-of-n
Intuitive approach by iteration
puremonkey2001
0
22
the kth factor of n
1,492
0.624
Medium
22,236
https://leetcode.com/problems/the-kth-factor-of-n/discuss/708468/Python3-fast-yet-space-efficient-solution-The-kth-Factor-or-n
class Solution: def kthFactor(self, n: int, k: int) -> int: front = [] for i in range(1, int(n**0.5) + 1): if n % i == 0: if len(front) == k - 1: return i front.append(i) if k > len(front) * 2 - int(front[-1]**2 == n): return -1 return n // front[-k+len(front)]
the-kth-factor-of-n
Python3 fast yet space efficient solution - The kth Factor or n
r0bertz
0
80
the kth factor of n
1,492
0.624
Medium
22,237
https://leetcode.com/problems/the-kth-factor-of-n/discuss/708262/PythonPython3-The-kth-Factor-of-n
class Solution: def kthFactor(self, n: int, k: int) -> int: try: return list(filter(lambda x:n%x==0,range(1,n+1)))[k-1] except: return -1
the-kth-factor-of-n
[Python/Python3] The kth Factor of n
newborncoder
0
76
the kth factor of n
1,492
0.624
Medium
22,238
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708121/Easy-Solution-without-DP-Simple-Pictorial-Explanation-or-Python-Solution.
class Solution: def longestSubarray(self, nums: List[int]) -> int: m=0 l=len(nums) one=True for i in range(0,l): if nums[i]==0: one=False left=i-1 right=i+1 ones=0 while left>=0: if nums[left]==1: ones=ones+1 left=left-1 else: break while right<l: if nums[right]==1: ones=ones+1 right=right+1 else: break if ones>m: m=ones if one: return l-1 return m
longest-subarray-of-1s-after-deleting-one-element
[Easy Solution without DP] Simple Pictorial Explanation | Python Solution.
lazerx
12
1,100
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,239
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708513/Python3-groupby-Longest-Subarray-of-1's-After-Deleting-One-Element
class Solution: def longestSubarray(self, nums: List[int]) -> int: groups = [[k, len(list(g))] for k, g in itertools.groupby(nums)] if len(groups) == 1: return groups[0][1] - 1 if groups[0][0] else 0 ans = 0 for i in range(len(groups)): k, klen = groups[i] if k: ans = max(ans, klen) elif i not in [0, len(groups)-1] and klen == 1: ans = max(ans, groups[i-1][1] + groups[i+1][1]) return ans
longest-subarray-of-1s-after-deleting-one-element
Python3 groupby - Longest Subarray of 1's After Deleting One Element
r0bertz
2
162
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,240
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1694401/Python-3-Sliding-window-one-loop
class Solution: def longestSubarray(self, nums: List[int]) -> int: start, max_window, ones_count = 0,0,0 for end in range(len(nums)): ones_count += nums[end] if (end - start + 1 - ones_count) > 1: ones_count -= nums[start] start += 1 max_window = max(max_window, end - start + 1) return max_window - 1
longest-subarray-of-1s-after-deleting-one-element
Python 3 Sliding window one loop
aver18
1
115
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,241
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1583932/Python-Sliding-window-Solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: windowStart = 0 hashmap = {x: 0 for x in nums} max_length = 0 if 0 not in hashmap.keys(): return len(nums) - 1 for windowEnd in range(len(nums)): hashmap[nums[windowEnd]] += 1 if hashmap[0] > 1: hashmap[nums[windowStart]] -= 1 windowStart += 1 max_length = max(max_length, windowEnd - windowStart) return (max_length)
longest-subarray-of-1s-after-deleting-one-element
[Python] - Sliding window Solution
TheBatmanNinja
1
111
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,242
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1561514/Easy-understand-and-less-logical-solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: zeroPos = [] n = len( nums) ct = 0 dp = [] for i in range ( n): if nums[i] == 1: ct += 1 dp.append(ct) else: ct = 0 dp.append(ct) zeroPos.append(i) zn = len( zeroPos) if zn == 0: return n-1 if zn == n: return 0 realMax = 0 for i in range ( zn): val1 = dp[zeroPos[i]] val2 = dp[zeroPos[i]] if zeroPos[i] > 0: val1 = dp[zeroPos[i]-1] val2 = 0 if zeroPos[i]+1 < n: val2 = dp[zeroPos[i]+1] if i < zn-1: val2 = dp[zeroPos[i+1]-1] if i == zn-1: val2 = dp[n-1] realMax = max( realMax, val1+val2) return realMax ```
longest-subarray-of-1s-after-deleting-one-element
Easy understand and less logical solution
krunalk013
1
78
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,243
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1111101/Python3-sliding-window
class Solution: def longestSubarray(self, nums: List[int]) -> int: ans = 0 queue = deque([-1]) for i, x in enumerate(nums): if not x: queue.append(i) if len(queue) > 2: queue.popleft() ans = max(ans, i - queue[0] - 1) return ans
longest-subarray-of-1s-after-deleting-one-element
[Python3] sliding window
ye15
1
93
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,244
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708198/PythonPython3-Longest-Subarray-of-1's-After-Deleting-One-Element
class Solution: def longestSubarray(self, nums: List[int]) -> int: if all(map(lambda x:x==1,nums)): return sum(nums)-1 i = 0 j = 0 zero = [] sum_z = 0 while j<len(nums): if nums[j] == 0 and not zero: zero.append(j) elif nums[j] == 0: k = sum(nums[i:j]) sum_z = k if k>sum_z else sum_z i, zero[0] = zero[0]+1, j j += 1 k = sum(nums[i:j]) sum_z = k if k>sum_z else sum_z return sum_z
longest-subarray-of-1s-after-deleting-one-element
[Python/Python3] Longest Subarray of 1's After Deleting One Element
newborncoder
1
119
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,245
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2814605/python-super-easy-sliding-window
class Solution: def longestSubarray(self, nums: List[int]) -> int: l = 0 r = 0 ans = 0 current_s = nums[l] while l < len(nums) and r < len(nums): if current_s + 1 >= (r-l+1): ans = max(ans, r-l) r += 1 if r < len(nums): current_s += nums[r] else: current_s -= nums[l] l +=1 return ans
longest-subarray-of-1s-after-deleting-one-element
python super easy sliding window
harrychen1995
0
1
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,246
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2812144/Python-Simple-sliding-window-solution-O(n)-time-and-O(1)-space
class Solution: def longestSubarray(self, nums: List[int]) -> int: left, right = 0 , 0 count = 0 maxi = 0 while right < len(nums): if nums[right] == 0: count += 1 while count > 1: if nums[left] == 0: count -= 1 left += 1 maxi = max(maxi, right - left + 1) right += 1 return maxi - 1
longest-subarray-of-1s-after-deleting-one-element
Python Simple sliding window solution O(n) time and O(1) space
vijay_2022
0
1
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,247
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2810180/EASIEST-SELF-EXPLAINER-PYTHON-CODE-SINGLE-ITERATION
class Solution: def longestSubarray(self, nums: List[int]) -> int: k = 1 i,j = 0,0 ans = 0 while(i <= j and j < len(nums)): if(nums[j] == 0): k -= 1 if(k < 0): while(i <= j and k != 0): if(nums[i] == 0): k += 1 i += 1 ans = max(ans,j-i+1) j += 1 return ans-1
longest-subarray-of-1s-after-deleting-one-element
EASIEST SELF EXPLAINER PYTHON CODE SINGLE ITERATION
MAYANK-M31
0
4
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,248
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2740404/Simple-Python-or-O(n)-time-O(1)-space-dynamic-programming
class Solution: def longestSubarray(self, xs: List[int]) -> int: ones1 = 0 ones2 = 0 ans = 0 for x in xs: if x == 1: ones2 += 1 else: ans = max(ans, ones1 + ones2) ones1, ones2 = ones2, 0 ans = max(ans, ones1 + ones2) if ans == len(xs): return ans - 1 return ans
longest-subarray-of-1s-after-deleting-one-element
Simple Python | O(n) time, O(1) space, dynamic programming
on_danse_encore_on_rit_encore
0
7
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,249
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2652849/Python%3A-Beats-95-Time-90-Space-O(n)-Solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: res, lp, k = 0, 0, 1 for rp in range(len(nums)): if nums[rp] == 0: k -= 1 if k < 0: if nums[lp] == 0: k += 1 lp += 1 res = max(res, rp-lp) return res
longest-subarray-of-1s-after-deleting-one-element
Python: Beats 95% Time 90% Space O(n) Solution
shnartho
0
55
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,250
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2645816/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
class Solution: def longestSubarray(self, nums: List[int]) -> int: count_0=0 n=len(nums) maxSize=0 currSize=0 left=0 for i in range(n): currSize+=1 if nums[i]==0: count_0+=1 if count_0>1: while count_0>1 and left<=i: if nums[left]==0: count_0-=1 currSize-=1 left+=1 if currSize>maxSize and count_0<=1: maxSize=currSize return maxSize-1
longest-subarray-of-1s-after-deleting-one-element
Python3 Solution || O(N) Time & O(1) Space Complexity
akshatkhanna37
0
3
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,251
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2410858/Python-Solution-or-Classic-Two-Pointer-Sliding-Window-or-Count-0s
class Solution: def longestSubarray(self, arr: List[int]) -> int: ans = 0 start, end = 0, 0 currZs = 0 while end < len(arr): if arr[end] == 0: currZs += 1 while currZs > 1: if arr[start] == 0: currZs -= 1 start += 1 ans = max(ans,end-start+1) end += 1 return ans-1
longest-subarray-of-1s-after-deleting-one-element
Python Solution | Classic Two Pointer - Sliding Window | Count 0s
Gautam_ProMax
0
23
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,252
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2346793/Python-easy-to-read-and-understand-or-prefix-suffix
class Solution: def longestSubarray(self, nums: List[int]) -> int: n = len(nums) pre, suf = [1]*n, [1]*n if nums[0] == 0:pre[0] = 0 if nums[-1] == 0:suf[-1] = 0 for i in range(1, n): if nums[i] == 1 and nums[i-1] == 1: pre[i] = pre[i-1] + 1 elif nums[i] == 0: pre[i] = 0 for i in range(n-2, -1, -1): if nums[i] == 1 and nums[i+1] == 1: suf[i] = suf[i+1] + 1 elif nums[i] == 0: suf[i] = 0 ans = 0 for i in range(n): if i == 0: ans = max(ans, suf[i+1]) elif i == n-1: ans = max(ans, pre[i-1]) else: ans = max(ans, pre[i-1] + suf[i+1]) return ans
longest-subarray-of-1s-after-deleting-one-element
Python easy to read and understand | prefix-suffix
sanial2001
0
39
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,253
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2301377/Python-Solution-or-Using-Sliding-Window-Approach
class Solution: def longestSubarray(self, nums: List[int]) -> int: L = 0 R = 0 ans = 0 count_of_zeros = 0 #start the sliding window process! while R < len(nums): if(nums[R] == 0): count_of_zeros += 1 #stopping condition! while count_of_zeros == 2: ans = max(ans, R - L - 1) #potentially before contracting window, check if left is pointing to a zero! if(nums[L] == 0): count_of_zeros -= 1 L += 1 #continue expanding sliding window! R += 1 #edge case: if count_of_zeros of input array is ever less than or equal to 1, then #recompute it! if(count_of_zeros <= 1): ans = max(ans, R - L - 1) return ans
longest-subarray-of-1s-after-deleting-one-element
Python Solution | Using Sliding Window Approach
JOON1234
0
42
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,254
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2288009/Simple-python-solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: currentOnes = 0 prevOnes = 0 maxCount = 0 for i in range(len(nums)): if nums[i] == 1: currentOnes += 1 else: maxCount = max(maxCount, currentOnes + prevOnes) prevOnes = currentOnes currentOnes = 0 maxCount = max(maxCount, currentOnes + prevOnes) return maxCount-1 if maxCount == len(nums) else maxCount
longest-subarray-of-1s-after-deleting-one-element
Simple python solution
Gilbert770
0
41
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,255
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/2204765/Pyrhon-3-oror-Simple-Solution-oror-Sliding-Window-oror-O(n)-and-O(1)
class Solution: def longestSubarray(self, nums) -> int: left = 0 right = 0 zero = 0 while right < len(nums): if nums[right] == 0: zero += 1 if zero > 1: if nums[left] == 0: zero -= 1 left += 1 right += 1 return right - left - 1
longest-subarray-of-1s-after-deleting-one-element
Pyrhon 3 || Simple Solution || Sliding Window || O(n) & O(1)
igalart2000
0
47
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,256
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1637687/Python3-Clean-and-Fast-Solution-with-Sliding-Window
class Solution: def longestSubarray(self, nums: List[int]) -> int: idx_zeros = [-1, -1] ans = 0 for i, num in enumerate(nums): if num == 0: ans = max(ans, i - idx_zeros[0] - 2) idx_zeros[0], idx_zeros[1] = idx_zeros[1], i if nums[-1]: ans = max(ans, len(nums) - idx_zeros[0] - 2) return ans
longest-subarray-of-1s-after-deleting-one-element
Python3 Clean and Fast Solution with Sliding Window
ynnekuw
0
36
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,257
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1628075/python3-time%3A-O(n)-using-prefix-and-suffix
class Solution: def longestSubarray(self, nums: List[int]) -> int: n = len(nums) right = [num for num in nums] for i in range(n - 1, -1, -1): if nums[i] == 1: right[i] += right[i + 1] if i + 1 < n else 0 ans = 0 prev = 0 for i in range(n): valR = right[i + 1] if i + 1 < n else 0 ans = max(ans, prev + valR) prev = prev + 1 if nums[i] == 1 else 0 return ans
longest-subarray-of-1s-after-deleting-one-element
python3 time: O(n) using prefix and suffix
reynaldocv
0
29
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,258
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1617995/Most-intuitive-python3-solution
class Solution: def longestSubarray(self, nums: List[int]) -> int: left=0 countZeros=0 res=0 n=len(nums) for right in range(n): if nums[right]==0: countZeros+=1 while countZeros>1: if nums[left]==0: countZeros-=1 left+=1 res=max(res,right-left) return res
longest-subarray-of-1s-after-deleting-one-element
Most intuitive python3 solution
Karna61814
0
46
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,259
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1521676/Python-5-lines
class Solution: def longestSubarray(self, nums: List[int]) -> int: if 0 not in nums: return len(nums) - 1 # arrays = list of 1 subarrays [1,1,1,0,1,1] -> ['111', '11'] arrays = ''.join(map(str,nums)).split('0') ans = float('-inf') for i in range(1, len(arrays)): ans = max(ans, len(arrays[i-1] + arrays[i])) return ans
longest-subarray-of-1s-after-deleting-one-element
Python 5 lines
SmittyWerbenjagermanjensen
0
72
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,260
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1442568/Python-very-easy.-O(n)-time-O(1)-space.-No-DP-No-sliding-window
class Solution: def longestSubarray(self, nums: List[int]) -> int: n = len(nums) if nums.count(0) == 0: return n-1 if nums.count(1) == 0: return 0 nums.append(0) zeroes = [-1] ones = [] maxv = 0 for idx, num in enumerate(nums): if num == 0: if len(zeroes) == 1: zeroes.append(idx) else: zeroes = [zeroes[1], idx] one = zeroes[1]-zeroes[0] -1 if len(ones) <= 1: ones.append(one) elif len(ones) == 2: ones = [ones[1], one] if len(ones) == 2: maxv = max(maxv, ones[1]+ones[0]) return maxv
longest-subarray-of-1s-after-deleting-one-element
Python very easy. O(n) time O(1) space. No DP, No sliding window
byuns9334
0
66
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,261
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1430281/Python3-solution-two-approaches
class Solution: def longestSubarray(self, nums: List[int]) -> int: zeros_index = [] for i in range(len(nums)): if nums[i] == 0: zeros_index.append(i) if len(zeros_index) in [0,1]: return len(nums)-1 count = 0 for i in range(len(zeros_index)): if i == 0: count = zeros_index[i+1]-zeros_index[i] - 1 + zeros_index[i] elif i == len(zeros_index) - 1: count = max(count, zeros_index[i] - zeros_index[i-1] - 1 + len(nums)-zeros_index[i]-1) else: count = max(count, zeros_index[i] - zeros_index[i-1] - 1 + zeros_index[i+1] -zeros_index[i] - 1) return count
longest-subarray-of-1s-after-deleting-one-element
Python3 solution two approaches
EklavyaJoshi
0
29
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,262
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1430281/Python3-solution-two-approaches
class Solution: def longestSubarray(self, nums: List[int]) -> int: i = j = 0 flag = False res = 0 while j < len(nums): if nums[j] == 0: if flag == False: flag = True else: res = max(j-i-1,res) while i < j: if nums[i] == 0: break i += 1 i = i + 1 j += 1 res = max(j-i-1,res) return res
longest-subarray-of-1s-after-deleting-one-element
Python3 solution two approaches
EklavyaJoshi
0
29
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,263
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1311395/Python-Iterative-easy-to-understand
class Solution: def longestSubarray(self, nums: List[int]) -> int: # k is the number of possible replacements k = 1 left = 0 result = 0 for right in range(len(nums)): if nums[right] == 0: k -= 1 while k < 0: if nums[left] == 0: k += 1 left += 1 result = max(result, right - left) return result
longest-subarray-of-1s-after-deleting-one-element
[Python] Iterative easy to understand
dlog
0
146
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,264
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/1218096/Python-Solution-Beats-99.51
class Solution: def longestSubarray(self, nums: List[int]) -> int: if 0 not in nums: return len(nums)-1 if 1 not in nums: return 0 a = [] cnt = 0 for i in nums: if i == 0: if cnt != 0: a.append(cnt) cnt = 0 a.append(i) else: cnt += 1 if cnt!=0: a.append(cnt) Max = 0 for i in range(len(a)): if a[i] != 0: continue if a[i] == 0 and i == len(a)-1: Max = max(Max,a[i-1]) elif a[i] == 0 and i == 0: Max = max(Max,a[i+1]) elif a[i] == 0: Max = max(Max,a[i+1]+a[i-1]) return Max
longest-subarray-of-1s-after-deleting-one-element
Python Solution Beats 99.51%
Piyush_0411
0
105
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,265
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/980453/Intuitive-approach-by-sliding-windows
class Solution: def longestSubarray(self, nums: List[int]) -> int: ans, past_n, curr_n = 0, 0, 0 for n in nums: if n == 0: ans = max(past_n + curr_n, ans) past_n = curr_n curr_n = 0 else: curr_n += 1 ans = max(past_n + curr_n, ans) # if ans == len(nums) which means all numbers are 1. But we still have to delete one # number which lead to final result as `ans - 1` return ans if ans < len(nums) else ans - 1
longest-subarray-of-1s-after-deleting-one-element
Intuitive approach by sliding windows
puremonkey2001
0
34
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,266
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/713288/Python3-Better-100-Mem-75-Speed.-With-comments-(Game-Like)
class Solution: def longestSubarray(self, nums: List[int]) -> int: sums=0 #Summaries of our streaks before making two mistakes sumlist=list() #list of that summaries. So we can find our biggest streak later with max() if sum(nums)==len(nums): #First of all lets test the case there might be no penalties at all return sum(nums)-1 s=0 #Penalty counter. Be careful, 2 penalties and streak is over! i=0 #lets start our journey from beginning of our list. while i< len(nums): if nums[i]==0 and s==0: #First Penalty!(0) You can continue, for now... s+=1 #Saving that you already done your first penalty p=i #Saving your first penalty's location. i+=1 #Go next one! elif nums[i]==0 and s!=0: #Second Penalty(0) stop now!!! And tell everything you count by far to 'SUMLIST' sumlist.append(sums) #saving your streak... s=0 #new beginning no penalties... sums=0 #but ofcourse youre starting from bottom i=p #start from your first penalty's location! i+=1 #actually next of it. Since its a penalty, its not fair to start with a penalty already else: sums+=1 #No penalties? Add 1 more to your pocket i+=1 #Go next one sumlist.append(sums) #There might be only one zero so lets append sums just in case, we will return max of that sumlist so, no problem. return max(sumlist) #Returning maximum of our streaks with only one penalty!
longest-subarray-of-1s-after-deleting-one-element
[Python3] Better %100 Mem - %75 Speed. With comments (Game-Like)
justlookin
0
35
longest subarray of 1s after deleting one element
1,493
0.602
Medium
22,267
https://leetcode.com/problems/parallel-courses-ii/discuss/1111255/Python3-dp
class Solution: def minNumberOfSemesters(self, n: int, dependencies: List[List[int]], k: int) -> int: pre = [0]*n # prerequisites for u, v in dependencies: pre[v-1] |= 1 << (u-1) @cache def fn(mask): """Return min semesters to take remaining courses.""" if mask == (1 << n) - 1: return 0 # all courses taken can = [] # available courses for i in range(n): if not mask &amp; 1 << i and mask &amp; pre[i] == pre[i]: can.append(i) ans = inf for courses in combinations(can, min(k, len(can))): temp = mask | reduce(lambda x, y: x | 1 << y, courses, 0) ans = min(ans, 1 + fn(temp)) return ans return fn(0)
parallel-courses-ii
[Python3] dp
ye15
2
171
parallel courses ii
1,494
0.311
Hard
22,268
https://leetcode.com/problems/parallel-courses-ii/discuss/2381477/faster-than-100.00-of-Python3
class Solution: def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int: graph = [0] * n out_degree = [0] * n # -1 to fix 1-based indexing offset from prompt. for pre_req, course in relations: graph[course-1] += 1 << (pre_req-1) out_degree[pre_req-1] += 1 # Just converts course to its shifted value c2shift = [1<<course for course in range(n)] start = 0 goal = 2**n-1 # will eq course_total once all have been taken. queue = collections.deque([(start,0)]) seen = [0] * (2 ** n) # Similar to Bellman-Ford while queue: # course_total is state. Each bit representing a taken course. course_total, steps = queue.popleft() available = [] for course_num in range(n): if (course_total &amp; graph[course_num] == graph[course_num]) \ and (course_total &amp; c2shift[course_num] == 0): available.append(course_num) # pre_req courses can unlock others. pre_reqs = [c2shift[course_num] for course_num in available if out_degree[course_num]] leaves = [c2shift[course_num] for course_num in available if out_degree[course_num] == 0] # We only include leaf courses when we have extra space if len(pre_reqs) <= k: course_total += sum(pre_reqs) + sum(leaves[:k-len(pre_reqs)]) if course_total == goal: return steps + 1 if not seen[course_total]: queue.append((course_total,steps+1)) seen[course_total] = 1 else: # Trying every combination of the pre_reqs. # comb is required here because we can't simply take them all (len(pre_reqs) > k) for batch in itertools.combinations(pre_reqs, k): diff = sum(batch) t = course_total + diff if t == goal: return steps + 1 if not seen[t]: queue.append((t, steps+1)) seen[t] = 1![Uploading file...]()
parallel-courses-ii
faster than 100.00% of Python3
vimla_kushwaha
1
153
parallel courses ii
1,494
0.311
Hard
22,269
https://leetcode.com/problems/parallel-courses-ii/discuss/1859239/Python-Topological-Sort-with-Bitmask-and-Backtracking
class Solution: def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int: adj = defaultdict(list) in_deg = [0]*n for prev, nxt in relations: adj[prev-1].append(nxt-1) in_deg[nxt-1]+=1 # bit_mask: # 1 means not taken # 0 mean taken # initialize to 1<<n -1 @cache def backtrack(bit_mask): if not bit_mask: return 0 catalog = [i for i in range(n) if in_deg[i] == 0 and bit_mask &amp; 1<<i] ret = float("inf") for k_courses in combinations(catalog,min(k,len(catalog))): nxt_bit_mask = bit_mask for course in k_courses: nxt_bit_mask ^= 1<<course for parent in adj[course]: in_deg[parent]-=1 ret = min( ret, 1 + backtrack( nxt_bit_mask ) ) for course in k_courses: for parent in adj[course]: in_deg[parent]+=1 return ret return backtrack((1<<n) -1)
parallel-courses-ii
[Python] Topological Sort with Bitmask and Backtracking
haydarevren
1
237
parallel courses ii
1,494
0.311
Hard
22,270
https://leetcode.com/problems/parallel-courses-ii/discuss/708303/Python3-BFS-with-bit-mask-(commented)
class Solution: def minNumberOfSemesters(self, n: int, dependencies: List[List[int]], k: int) -> int: graph = collections.defaultdict(int) for x, y in dependencies: graph[y] |= 1 << (x - 1) # dependency mask of course y last_mask = (1 << n) - 1 # all course queue = collections.deque([(0, 0)]) # start with zero course taken visited = {0} while queue: mask, num_semesters = queue.popleft() # mask &amp; (1 << (x - 1)) == 0 course have not been taken # mask &amp; graph[x] == graph[x] but all its dependency course have been taken free_courses = [x for x in range(1, n + 1) if (mask &amp; (1 << (x - 1)) == 0) and mask &amp; graph[x] == graph[x]] for courses in itertools.combinations(free_courses, min(k, len(free_courses))): new_mask = mask for x in courses: new_mask |= 1 << (x - 1) if new_mask == last_mask: return num_semesters + 1 if new_mask not in visited: visited.add(new_mask) queue.append((new_mask, num_semesters + 1))
parallel-courses-ii
[Python3] BFS with bit mask (commented)
ChelseaChenC
0
124
parallel courses ii
1,494
0.311
Hard
22,271
https://leetcode.com/problems/path-crossing/discuss/1132447/Python3-simple-solution-faster-than-99-users
class Solution: def isPathCrossing(self, path: str) -> bool: l = [(0,0)] x,y = 0,0 for i in path: if i == 'N': y += 1 if i == 'S': y -= 1 if i == 'E': x += 1 if i == 'W': x -= 1 if (x,y) in l: return True else: l.append((x,y)) return False
path-crossing
Python3 simple solution faster than 99% users
EklavyaJoshi
4
252
path crossing
1,496
0.558
Easy
22,272
https://leetcode.com/problems/path-crossing/discuss/709229/Python3-10-line-simulation
class Solution: def isPathCrossing(self, path: str) -> bool: x, y = 0, 0 seen = {(x, y)} for move in path: if move == "N": y += 1 elif move == "S": y -= 1 elif move == "E": x += 1 else: x -= 1 if (x, y) in seen: return True seen.add((x, y)) return False
path-crossing
[Python3] 10-line simulation
ye15
4
381
path crossing
1,496
0.558
Easy
22,273
https://leetcode.com/problems/path-crossing/discuss/1194037/Python-Line-by-Line-Explanation(Using-dictionary)-Fast-and-efficient-solution
class Solution: def isPathCrossing(self, path: str) -> bool: #Store the directions(key) with their corresponding actions(values) directions = {'N': [0,1], 'E':[1,0], 'W':[-1,0], 'S':[0,-1]} #Keep the track of visited points visited = set() #Add the initial point from where you're starting visited.add((0,0)) #Current trackers of x and y coordinates curr_x,curr_y = 0,0 #Loop through all the path for i in path: curr_x += directions[i][0] curr_y += directions[i][1] #If visited for first time, add them to visited if (curr_x,curr_y) not in visited: visited.add((curr_x,curr_y)) else: return True #Else return True return False #Return True if there is no re-visiting
path-crossing
Python Line by Line Explanation(Using dictionary) - Fast and efficient solution
iamkshitij77
2
163
path crossing
1,496
0.558
Easy
22,274
https://leetcode.com/problems/path-crossing/discuss/2819934/Simple-Python-oror-Understandable-and-Clean
class Solution: def isPathCrossing(self, path: str) -> bool: coor = [0, 0] coors = [[0, 0]] for i in path: if i == 'N': coor[1] += 1 elif i == 'E': coor[0] += 1 elif i == 'S': coor[1] -= 1 else: coor[0] -= 1 if coor in coors: return True coors.append(coor[:]) return False
path-crossing
Simple Python || Understandable & Clean
qiy2019
1
24
path crossing
1,496
0.558
Easy
22,275
https://leetcode.com/problems/path-crossing/discuss/1878635/Python-Simple-and-Elegant!-Tuple-Set-and-Match-case!
class Solution: def isPathCrossing(self, path): point, points = (0,0), {(0,0)} for dir in path: match dir: case "N": point = (point[0]+1, point[1]) case "S": point = (point[0]-1, point[1]) case "E": point = (point[0], point[1]+1) case "W": point = (point[0], point[1]-1) if point in points: return True else: points.add(point) return False
path-crossing
Python - Simple and Elegant! Tuple, Set, and Match case!
domthedeveloper
1
69
path crossing
1,496
0.558
Easy
22,276
https://leetcode.com/problems/path-crossing/discuss/1856205/Simple-Python-Solution-oror-95-Faster-oror-Memory-less-than-75
class Solution: def isPathCrossing(self, path: str) -> bool: points=[(0,0)] ; i=0 ; j=0 for p in path: if p=='N': j+=1 if p=='S': j-=1 if p=='E': i+=1 if p=='W': i-=1 if (i,j) in points: return True else: points.append((i,j)) return False
path-crossing
Simple Python Solution || 95% Faster || Memory less than 75%
Taha-C
1
51
path crossing
1,496
0.558
Easy
22,277
https://leetcode.com/problems/path-crossing/discuss/1392134/Python-3-Easy-array-solution-or-32-ms-(58.69)-14.3-mb-(80.98)
class Solution: def isPathCrossing(self, path: str) -> bool: x, y = 0, 0 # Setup initial points points = [(0, 0)] # Add initial points to visited array for c in path: # Iterate through characters in string # Depending on direction, change x and y value if c == "N": y += 1 if c == "E": x += 1 if c == "S": y -= 1 if c == "W": x -= 1 if (x, y) in points: # Check if tuple of x and y is in points, if so, return true return True points.append((x, y)) # Add tuple of points to visited array # Return false beacuse we couldn't find any duplicate return False
path-crossing
[Python 3] Easy array solution | 32 ms (58.69%), 14.3 mb (80.98%)
SunCrusader
1
85
path crossing
1,496
0.558
Easy
22,278
https://leetcode.com/problems/path-crossing/discuss/709606/PYTHON-36ms-solution-using-set
class Solution: def isPathCrossing(self, path: str) -> bool: xCoordinate = 0 yCoordinate = 0 pointsCovered = [(0,0)] for direction in path: if direction == 'N': yCoordinate+=1 elif direction == 'S': yCoordinate-=1 elif direction == 'E': xCoordinate +=1 else: xCoordinate-=1 pointsCovered.append((xCoordinate,yCoordinate)) return not len(pointsCovered) == len(set(pointsCovered))
path-crossing
PYTHON - 36ms solution using set
amanpathak2909
1
82
path crossing
1,496
0.558
Easy
22,279
https://leetcode.com/problems/path-crossing/discuss/2741614/Python3-95-faster-with-explanation
class Solution: def isPathCrossing(self, path: str) -> bool: rmap = {} x, y = 0,0 rmap[x] = {y: False} for direction in path: if direction == 'N': y += 1 elif direction == 'W': x -= 1 elif direction == 'S': y -= 1 elif direction == 'E': x += 1 else: print('not valid') if x in rmap: if y in rmap[x]: return True else: rmap[x][y] = False else: rmap[x] = {y :False} return False
path-crossing
Python3, 95% faster with explanation
cvelazquez322
0
16
path crossing
1,496
0.558
Easy
22,280
https://leetcode.com/problems/path-crossing/discuss/2727109/Easy-understanding-Quick-Python-Solution
class Solution: def isPathCrossing(self, path: str) -> bool: i = 0 j = 0 hist = [[0,0]] for a in path: if a == 'N': i += 1 if a == 'S': i -= 1 if a == 'E': j += 1 if a == 'W': j -= 1 if [i,j] not in hist: hist.append([i,j]) else: return True return False
path-crossing
Easy-understanding Quick Python Solution
EdenXiao
0
1
path crossing
1,496
0.558
Easy
22,281
https://leetcode.com/problems/path-crossing/discuss/2723970/python-easy-solution-and-99-faster
class Solution: def isPathCrossing(self, path: str) -> bool: arr = [] x = 0 y = 0 for d in path: arr.append((x,y)) if d == "N": y+=1 elif d== "S": y-=1 elif d == "E": x+=1 elif d== "W": x-=1 if (x,y) in arr: return True return False
path-crossing
python easy solution and 99% faster
VikramKumarcoder
0
6
path crossing
1,496
0.558
Easy
22,282
https://leetcode.com/problems/path-crossing/discuss/2606044/Python-Set-Solution-or-Beats-90-time-or-O(N)
class Solution: def isPathCrossing(self, path: str) -> bool: x, y = 0, 0 visited = set() visited.add((x,y)) for d in path: if d == 'N': y += 1 elif d == 'S': y -= 1 elif d == 'E': x += 1 elif d == 'W': x -= 1 if (x, y) in visited: return True else: visited.add((x,y)) return False
path-crossing
Python Set Solution | Beats 90% time | O(N)
dos_77
0
9
path crossing
1,496
0.558
Easy
22,283
https://leetcode.com/problems/path-crossing/discuss/2408018/Python3-Easy-Approach-using-Sets-and-Dictionaries
class Solution: def isPathCrossing(self, path: str) -> bool: x, y = 0, 0 visited = {(x, y)} for move in path: if move == 'N': y += 1 elif move == 'S': y -= 1 elif move == 'E': x += 1 else: x -= 1 if (x, y) in visited: return True visited.add((x, y)) return False
path-crossing
Python3 Easy Approach using Sets and Dictionaries
vjgadre21
0
22
path crossing
1,496
0.558
Easy
22,284
https://leetcode.com/problems/path-crossing/discuss/2315103/Python-fast-Hashset
class Solution: def isPathCrossing(self, path: str) -> bool: c = set() x,y = 0,0 c.add((x,y)) for i in path: if i == 'N': y+=1 elif i == 'E': x+=1 elif i == 'W': x-=1 else: y-=1 if (x,y) in c: return True else: c.add((x,y)) return False
path-crossing
Python fast Hashset
sunakshi132
0
30
path crossing
1,496
0.558
Easy
22,285
https://leetcode.com/problems/path-crossing/discuss/2315098/Faster-than-98-Python-hashmap
class Solution: def isPathCrossing(self, path: str) -> bool: c = {(0,0):1} x,y = 0,0 for i in path: if i == 'N': y+=1 elif i == 'E': x+=1 elif i == 'W': x-=1 else: y-=1 if (x,y) in c: return True else: c[(x,y)]=1 return False
path-crossing
Faster than 98% Python hashmap
sunakshi132
0
25
path crossing
1,496
0.558
Easy
22,286
https://leetcode.com/problems/path-crossing/discuss/2289403/PythonorEasy-and-Detailed
class Solution: def isPathCrossing(self, path: str) -> bool: ns=0#this is for north and south direction ew=0#this is for east and north directions li=[[ns,ew]]#visited paths for i in path: if i=='N': ns+=1 elif i=='S': ns-=1 elif i=='E': ew+=1 else: ew-=1 if [ns,ew] not in li: li.append([ns,ew]) else: return True return False
path-crossing
Python|Easy and Detailed
ajay_keelu
0
20
path crossing
1,496
0.558
Easy
22,287
https://leetcode.com/problems/path-crossing/discuss/1986460/dictionary
class Solution: def isPathCrossing(self, path: str) -> bool: moves = {"N": 1, "S": -1, "E": 1, "W": -1} seen = [(0, 0)] for move in path: if move in "EW": location = (seen[-1][0] + moves[move], seen[-1][1]) else: location = (seen[-1][0], seen[-1][1] + moves[move]) if location in seen: return True else: seen.append(location) return False
path-crossing
dictionary
andrewnerdimo
0
44
path crossing
1,496
0.558
Easy
22,288
https://leetcode.com/problems/path-crossing/discuss/1905370/Python-easy-solution-faster-than-88-and-memory-less-than-95
class Solution: def isPathCrossing(self, path: str) -> bool: x = 0 y = 0 check = [[0, 0]] for i in path: if i == 'N': y += 1 elif i == 'S': y -= 1 elif i == 'E': x += 1 elif i == 'W': x -= 1 if [x, y] in check: return True check.append([x, y]) return False
path-crossing
Python easy solution faster than 88% and memory less than 95%
alishak1999
0
86
path crossing
1,496
0.558
Easy
22,289
https://leetcode.com/problems/path-crossing/discuss/1753810/Python-dollarolution
class Solution: def isPathCrossing(self, path: str) -> bool: d = {'N':[1,1],'S':[1,-1],'W':[0,-1],'E':[0,1]} xy = [0,0] v = [[0,0]] for i in path: xy[d[i][0]] += d[i][1] if xy in v: return True else: v.append(xy[0:]) return False
path-crossing
Python $olution
AakRay
0
54
path crossing
1,496
0.558
Easy
22,290
https://leetcode.com/problems/path-crossing/discuss/1420292/Python3-Faster-Than-84.25
class Solution: def isPathCrossing(self, path: str) -> bool: x, y, v = 0, 0, set() v.add((0, 0)) for i in path: if i == 'N': y += 1 elif i == 'S': y -= 1 elif i == 'E': x += 1 elif i == 'W': x -= 1 l = len(v) v.add((x, y)) if l == len(v): return True return False
path-crossing
Python3 Faster Than 84.25%
Hejita
0
58
path crossing
1,496
0.558
Easy
22,291
https://leetcode.com/problems/path-crossing/discuss/780771/Intuitive-approach-by-holding-all-visited-cell-in-set
class Solution: def isPathCrossing(self, path: str) -> bool: pos = [0, 0] pos_set = set([tuple(pos)]) for a in path: if a == 'N': pos[0] += 1 elif a == 'S': pos[0] -= 1 elif a == 'W': pos[1] -= 1 elif a == 'E': pos[1] += 1 if tuple(pos) in pos_set: return True pos_set.add(tuple(pos)) return False
path-crossing
Intuitive approach by holding all visited cell in set
puremonkey2001
0
35
path crossing
1,496
0.558
Easy
22,292
https://leetcode.com/problems/path-crossing/discuss/716480/Python3-Intuitive-100-Memory-67-Runtime-O(N)-solution
class Solution: def isPathCrossing(self, path: str) -> bool: curr_point = (0,0) visited = set() for d in path: if d == 'N': curr_point = (curr_point[0], curr_point[1] + 1) elif d == 'S': curr_point = (curr_point[0], curr_point[1] - 1) elif d == 'E': curr_point = (curr_point[0] + 1, curr_point[1]) elif d == 'W': curr_point = (curr_point[0] - 1, curr_point[1]) else: raise AttributeError('Direction: {} in path in invalid'.format(d)) if curr_point == (0,0) or curr_point in visited: return True visited.add(curr_point) return False
path-crossing
[Python3] - Intuitive 100% Memory 67% Runtime O(N) solution
skull_
0
102
path crossing
1,496
0.558
Easy
22,293
https://leetcode.com/problems/path-crossing/discuss/709373/Python3-complex-number-solution-Path-Crossing
class Solution: def isPathCrossing(self, path: str) -> bool: p = complex(0, 0) points = set((p,)) m = {'N': 1j, 'S': -1j, 'E': 1, 'W': -1} for d in path: p += m[d] if p in points: return True points.add(p) return False
path-crossing
Python3 complex number solution - Path Crossing
r0bertz
0
56
path crossing
1,496
0.558
Easy
22,294
https://leetcode.com/problems/path-crossing/discuss/709274/PythonPython3-Path-Crossing
class Solution: def isPathCrossing(self, path: str) -> bool: directions = { 'N': (0,1), 'E': (1,0), 'W': (-1,0), 'S': (0,-1) } s = (0, 0) storage = [(0,0)] for d in path: x,y = s i,j = directions[d] x, y = x+i, y+j s = x,y if s in storage: return True else: storage.append(s) return False
path-crossing
[Python/Python3] Path Crossing
newborncoder
0
109
path crossing
1,496
0.558
Easy
22,295
https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/709252/Python3-3-line-frequency-table
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)
check-if-array-pairs-are-divisible-by-k
[Python3] 3-line frequency table
ye15
3
255
check if array pairs are divisible by k
1,497
0.396
Medium
22,296
https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/2667459/Python3-oror-Hashmap-Solution-oror-O(n)-oror-BGG
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: h = {} for i in arr: r = i % k if r not in h: h[r] = 0 h[r]+=1 if h.get(0,0) %2 !=0: return False for r1 in h: r2 = k - r1 if r1 == 0: continue if h[r1] != h.get(r2,0): return False return True # Please upvote if you understand the solution
check-if-array-pairs-are-divisible-by-k
Python3 || Hashmap Solution || O(n) || BGG
hoo__mann
0
18
check if array pairs are divisible by k
1,497
0.396
Medium
22,297
https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/1756155/Python3oror-O(n)-time-O(n)-space
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: if sum(arr) % k != 0: return False freq = [0] * k for val in arr: freq[val % k] += 1 if freq[0] % 2 != 0 or (k % 2 == 0 and freq[k//2] % 2 != 0): return False start, end = 1, k - 1 while start < end: if freq[start] != freq[end]: return False start += 1 end -= 1 return True #TC -> O(n) || SC -> O(n)
check-if-array-pairs-are-divisible-by-k
Python3|| O(n) time O(n) space
s_m_d_29
0
185
check if array pairs are divisible by k
1,497
0.396
Medium
22,298
https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/1547778/Easy-for-beginers-just-use-list-fast-than-69
class Solution: def canArrange(self, arr: List[int], k: int) -> bool: n = len(arr) if n % 2 != 0: return False tmp = [] for i in range(n): tmp.append(arr[i] % k) zero = [n for n in tmp if n == 0] unzero = [n for n in tmp if n != 0] if len(zero) % 2 != 0: return False unzero.sort() m = len(unzero) for i in range(m): if unzero[i] + unzero[m - 1 - i] != k: return False return True
check-if-array-pairs-are-divisible-by-k
Easy for beginers, just use list fast than 69%
zixin123
0
171
check if array pairs are divisible by k
1,497
0.396
Medium
22,299