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/compare-strings-by-frequency-of-the-smallest-character/discuss/2059008/python-3-oror-simple-binary-search-solution
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: def f(s): return s.count(min(s)) words = sorted(map(f, words)) n = len(words) res = [] for query in queries: res.append(n - bisect.bisect_right(words, f(query))) return res
compare-strings-by-frequency-of-the-smallest-character
python 3 || simple binary search solution
dereky4
0
51
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,000
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1925994/7-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-80
class Solution: def numSmallerByFrequency(self, Q: List[str], W: List[str]) -> List[int]: def f(self,s): s=''.join(sorted(s)) return s.count(s[0]) CW=Counter([f(self,w) for w in W]).items() ; ans=[] for i in range(len(Q)): ans.append(sum([x[1] for x in CW if x[0]>f(self,Q[i])])) return ans
compare-strings-by-frequency-of-the-smallest-character
7-Lines Python Solution || 75% Faster || Memory less than 80%
Taha-C
0
65
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,001
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1383068/Python3-or-2-Methods-or-Easy-understanding
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: def FrequencyCount(word): temp = ord('z') for i in str(word): temp = min(temp,ord(i)) return len([i for i in str(word) if i==chr(temp)]) res = [] for query in queries: c = FrequencyCount(query) res.append(sum(list(map(lambda x: c < FrequencyCount(x),words)))) return res
compare-strings-by-frequency-of-the-smallest-character
Python3 🐍 | 2 Methods | Easy understanding
hritik5102
0
57
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,002
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1383068/Python3-or-2-Methods-or-Easy-understanding
class Solution: def numSmallerByFrequency(self, queries, words): def FrequencyCount(w): return w.count(min(w)) res = [] for query in queries: c = FrequencyCount(query) res.append(sum(list(map(lambda x: c < FrequencyCount(x), words)))) print(res) obj = Solution() obj.numSmallerByFrequency(["bbb", "cc"], ["a", "aa", "aaa", "aaaa"])
compare-strings-by-frequency-of-the-smallest-character
Python3 🐍 | 2 Methods | Easy understanding
hritik5102
0
57
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,003
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/577779/Simple-Python-Solution
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: l=[] result=[] for i in range(len(words)): l.append(words[i].count(min(words[i]))) for i in range(len(queries)): x=queries[i] countC=x.count(min(x)) countS=0 for j in range(len(l)): if countC<l[j]: countS+=1 result.append(countS) return result
compare-strings-by-frequency-of-the-smallest-character
Simple Python Solution
Ayu-99
0
139
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,004
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/556459/Easy-to-understand-Pythonic-solution
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: query_freqs = [s.count(min(s)) for s in queries] word_freqs = [s.count(min(s)) for s in words] result = [0] * len(query_freqs) for i,q in enumerate(query_freqs): for w in word_freqs: if q < w: result[i] += 1 return result ```
compare-strings-by-frequency-of-the-smallest-character
Easy to understand Pythonic solution
c0rv0s
0
173
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,005
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/477225/Python-3-Solution
class Solution: def numSmallerByFrequency(self, queries, words): quer_len = [] wrds_len = [] for i in range(0,len(queries)): quer_len.append(self.some(queries[i])) for j in range(0,len(words)): wrds_len.append(self.some(words[j])) some = [] for i in range(0,len(quer_len)): greater = 0 for j in range(0,len(wrds_len)): if quer_len[i] < wrds_len[j]: greater +=1 some.append(greater) return some def some(self,strings): strings = sorted(strings) return strings.count(strings[0])
compare-strings-by-frequency-of-the-smallest-character
Python 3 Solution
xevb
0
266
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,006
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/366334/Brute-force-y
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: def f(s): return s.count(min(s)) answer = [] w_count = [f(i) for i in words] for i in range(len(queries)): q_count = f(queries[i]) ctr = 0 for w in w_count: if q_count < w: ctr += 1 answer.append(ctr) return answer
compare-strings-by-frequency-of-the-smallest-character
Brute force-y
nablet
0
106
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,007
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1404153/Python3-simple-solution-using-dictionary
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: q = [] w = [] for i in queries: d = {} x = i[0] for j in i: d[j] = d.get(j,0) + 1 if j < x: x = j q.append(d[x]) for i in words: d = {} x = i[0] for j in i: d[j] = d.get(j,0) + 1 if j < x: x = j w.append(d[x]) w.sort() n = len(w) ans = [] for i in q: flag = True for j,k in enumerate(w): if i < k: flag = False ans.append(n-j) break if flag: ans.append(0) return ans
compare-strings-by-frequency-of-the-smallest-character
Python3 simple solution using dictionary
EklavyaJoshi
-1
62
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,008
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/417421/Python3-beats-100-10-lines-clear-code-O(n)
class Solution: def numreturn(self , inputlist): a = sorted(inputlist) res = sum([1 for i in a if i==a[0]]) return res def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: q = [self.numreturn(iq) for iq in queries] w = [self.numreturn(iw) for iw in words] res = [] for i in range(len(q)): temp = sum([1 for one in w if one>q[i]]) res.append(temp) return res
compare-strings-by-frequency-of-the-smallest-character
Python3 beats 100% 10 lines clear code O(n)
macqueen
-3
400
compare strings by frequency of the smallest character
1,170
0.614
Medium
18,009
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/1701518/Easiest-Approach-oror-Clean-and-Concise-oror-Well-Explained
class Solution: def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0,head) pre = 0 dic = {0: dummy} while head: pre+=head.val dic[pre] = head head = head.next head = dummy pre = 0 while head: pre+=head.val head.next = dic[pre].next head = head.next return dummy.next
remove-zero-sum-consecutive-nodes-from-linked-list
πŸ“ŒπŸ“Œ Easiest Approach || Clean & Concise || Well-Explained 🐍
abhi9Rai
7
282
remove zero sum consecutive nodes from linked list
1,171
0.43
Medium
18,010
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/1501120/Python3-O(n)-time-solution-with-hashmap
class Solution: def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]: fake = ListNode(0, head) d = {0: fake} prefix_sum = 0 while head: prefix_sum += head.val d[prefix_sum] = head head = head.next head = fake prefix_sum = 0 while head: prefix_sum += head.val head.next = d[prefix_sum].next head = head.next return fake.next
remove-zero-sum-consecutive-nodes-from-linked-list
[Python3] O(n) time solution with hashmap
maosipov11
5
224
remove zero sum consecutive nodes from linked list
1,171
0.43
Medium
18,011
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/1444010/O(N)-Time-complexity-Python3-prefix-sum
class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: dummy = ListNode(0) # we can't use anyother no. as all the starting number sum up to the -ve value of one take ex.1 dummy.next = head sum_ = 0 dict_ = {sum_:dummy} while head: sum_ += head.val dict_[sum_] = head # this will update node value of prefix head = head.next head = dummy sum_ = 0 while head: sum_ += head.val head.next = dict_[sum_].next head = head.next return dummy.next ``` Feel free to ask Q. if u don't get the code
remove-zero-sum-consecutive-nodes-from-linked-list
O(N) Time complexity - Python3 - prefix sum
Shubham_Muramkar
0
272
remove zero sum consecutive nodes from linked list
1,171
0.43
Medium
18,012
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/468158/Python-3-(10-lines)-(48-ms)
class Solution: def removeZeroSumSublists(self, H: ListNode) -> ListNode: A, b = ListNode(0), 1; A.next = H while b: s, b, D, C = 0, 0, {0:A}, A.next while C != None: s += C.val if s in D: D[s].next, b = C.next, 1 break else: D[s], C = C, C.next return A.next - Junaid Mansuri - Chicago, IL
remove-zero-sum-consecutive-nodes-from-linked-list
Python 3 (10 lines) (48 ms)
junaidmansuri
-3
570
remove zero sum consecutive nodes from linked list
1,171
0.43
Medium
18,013
https://leetcode.com/problems/prime-arrangements/discuss/2794041/Find-product-between-factorial-of-primes-and-non-primes
class Solution: def numPrimeArrangements(self, n: int) -> int: # find number of prime indices # ways to arrange prime indices # is prime indices factorial # amount of non-prime indices is # n - prime indices # the factorial of non - prime indices # times the factorial of prime indices # is the amount of ways to arrange the # prime numbers and i be valid # use helper to find factorial of a number # use helper to see if a number is prime # time O(n ^ 2) space O(1) def isPrime(num): if num <= 1: return False for i in range(2, num // 2 + 1): if num % i == 0: return False return True def factorial(num): res = 1 for i in range(1, num + 1): res *= i return res primes = 0 for num in range(1, n + 1): if isPrime(num): primes += 1 return int(factorial(primes) * factorial(n - primes) % (10**9 + 7))
prime-arrangements
Find product between factorial of primes & non-primes
andrewnerdimo
0
4
prime arrangements
1,175
0.537
Easy
18,014
https://leetcode.com/problems/prime-arrangements/discuss/2157373/Python-Solution
class Solution: def numPrimeArrangements(self, n: int) -> int: if n <= 2: return 1 primesList = [False]*2 + [True]*(n - 1) for i in range(2, math.floor(math.sqrt(n)) + 1): if not primesList[i]: continue for j in range(i * i, n + 1, i): primesList[j] = False primes = sum(primesList) return (math.factorial(primes) * math.factorial(n - primes)) % (10 ** 9 + 7)
prime-arrangements
Python Solution
creativerahuly
0
50
prime arrangements
1,175
0.537
Easy
18,015
https://leetcode.com/problems/prime-arrangements/discuss/1858696/Python-Soln
class Solution: def numPrimeArrangements(self, n: int) -> int: if n==1: return 1 def isprime(num): sqrt=int(num**(1/2)) for j in range(2,sqrt+1): if num%j==0: return False return True prime=0 composite=1# Keeping 1 in composite, though it is neither prime nor comp. mod=10**9+7 for i in range(2,n+1): if isprime(i): prime+=1 else: composite+=1 def factorial(x): if x==1: return 1 return x*factorial(x-1) return factorial(prime)*factorial(composite)%mod
prime-arrangements
Python Soln
heckt27
0
67
prime arrangements
1,175
0.537
Easy
18,016
https://leetcode.com/problems/prime-arrangements/discuss/1851545/2-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-80
class Solution: def numPrimeArrangements(self, n: int) -> int: k=len([x for x in [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] if x<=n]) return (factorial(k)*factorial(n-k))%(10**9+7)
prime-arrangements
2-Lines Python Solution || 75% Faster || Memory less than 80%
Taha-C
0
85
prime arrangements
1,175
0.537
Easy
18,017
https://leetcode.com/problems/prime-arrangements/discuss/1737642/Python-dollarolution
class Solution: def numPrimeArrangements(self, n: int) -> int: count, fact1, fact2, g = 1, 1, 1, 1000000007 #calculate number of prime and non-prime numbers for i in range(3,n+1): count += 1 for j in range(2,i-1): if i % j == 0: count -= 1 break m = n - count if m > count: m, count = count, m #calculate the factorials for i in range(1,count+1): fact1 *= i if i == m: fact2 = fact1 #mod operation return ((fact2 * fact1) % g)
prime-arrangements
Python $olution
AakRay
0
104
prime arrangements
1,175
0.537
Easy
18,018
https://leetcode.com/problems/prime-arrangements/discuss/411817/Python3%3A-Segmented-Sieve
class Solution: def numPrimeArrangements(self, n: int) -> int: def simplesieve(n): prime=[] mark=[True]*(n+1) p=2 while (p**2 <=n): if mark[p]: for i in range(p*p,n+1,p): mark[i]=False p+=1 for i in range(2,n+1): if mark[i]: prime.append(i) return prime def segementedsieve(n): result=[] limit=math.floor(math.sqrt(n))+1 primes=simplesieve(limit) result.extend(primes) low=limit high=low+limit while low<=n: if high>=n: high=n mark=[True]*(limit+1) for i in primes: lowlimit=int(math.floor(low/i)*i) if lowlimit<low: lowlimit+=i for j in range(lowlimit,high+1,i): mark[j-low]=False for i in range(low,high): if mark[i-low]: result.append(i) low+=limit high+=limit return result #print(segementedsieve(n+1)) number_of_primes_less_than_n=len(segementedsieve(n+1)) non_prime_number_count=n-number_of_primes_less_than_n prime_permutations=math.factorial(number_of_primes_less_than_n) non_prime_permutations=math.factorial(non_prime_number_count) return (prime_permutations*non_prime_permutations)%(10**9+7)
prime-arrangements
Python3: Segmented Sieve
mathewjose09
0
1,300
prime arrangements
1,175
0.537
Easy
18,019
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1201798/Python3-prefix-freq
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: prefix = [[0]*26] for c in s: elem = prefix[-1].copy() elem[ord(c)-97] += 1 prefix.append(elem) ans = [] for left, right, k in queries: cnt = sum(1&amp;(prefix[right+1][i] - prefix[left][i]) for i in range(26)) ans.append(cnt <= 2*k+1) return ans
can-make-palindrome-from-substring
[Python3] prefix freq
ye15
2
222
can make palindrome from substring
1,177
0.38
Medium
18,020
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1201798/Python3-prefix-freq
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: prefix = [0] for c in s: prefix.append(prefix[-1] ^ (1 << (ord(c)-97))) ans = [] for left, right, k in queries: cnt = bin(prefix[right+1] ^ prefix[left]).count("1") ans.append(cnt <= 2*k+1) return ans
can-make-palindrome-from-substring
[Python3] prefix freq
ye15
2
222
can make palindrome from substring
1,177
0.38
Medium
18,021
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/2281486/PYTHON-SOL-or-EXPLAINED-WELL-or-EASY-TO-UNDERSTAND-or-FAST-or
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: n = len(s) d = defaultdict(int) count = [None]*n for i in range(n): d[s[i]] += 1 count[i] = d.copy() def check(start,end,k): prev = defaultdict(int) if start == 0 else count[start-1] left = 0 for i in range(26): diff = (count[end][chr(i+97)] - prev[chr(i+97)]) % 2 if diff == 1: left += 1 left = left // 2 return left <= k ans = [] for start,end,k in queries: ans.append(check(start,end,k)) return ans
can-make-palindrome-from-substring
PYTHON SOL | EXPLAINED WELL | EASY TO UNDERSTAND | FAST |
reaper_27
0
135
can make palindrome from substring
1,177
0.38
Medium
18,022
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1946497/Accumulated-frequencies-of-letters-78-speed
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: len_s = len(s) freq = [defaultdict(int)] * len_s freq[0][s[0]] += 1 for i in range(1, len_s): freq[i] = freq[i - 1].copy() freq[i][s[i]] += 1 ans = [True] * len(queries) for i, (left, right, k) in enumerate(queries): left1 = left - 1 n_odd = sum((n - (freq[left1][c] if left1 > -1 else 0)) % 2 for c, n in freq[right].items()) ans[i] = n_odd - 2 * k <= 1 return ans
can-make-palindrome-from-substring
Accumulated frequencies of letters, 78% speed
EvgenySH
0
116
can make palindrome from substring
1,177
0.38
Medium
18,023
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1409257/Simple-short-python-beats-75-detailed-explanation
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: runningCount = [[0]*26] countSnapshot = [0]*26 a = ord("a") for c in s: countSnapshot[ord(c)-a] += 1 runningCount.append([*countSnapshot]) # the * is necessary to deep copy the list for left,right,k in queries: if k>=13: yield True continue odds = 0 for i in range(26): odds += (runningCount[right+1][i] - runningCount[left][i])%2 yield k>=odds//2
can-make-palindrome-from-substring
Simple, short python beats 75% detailed explanation
Brannonj
0
191
can make palindrome from substring
1,177
0.38
Medium
18,024
https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/1567415/Python-TrieBitmasking-Solutions-with-Explanation
class Solution: def mask(self, word: str) -> int: result = 0 for ch in word: result |= 1 << (ord(ch)-ord('a')) return result def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: word_count = Counter(self.mask(word) for word in words) result = [] for puzzle in puzzles: original_mask, first = self.mask(puzzle[1:]), self.mask(puzzle[0]) curr_mask, count = original_mask, word_count[first] while curr_mask: count += word_count[curr_mask|first] curr_mask = (curr_mask-1)&amp;original_mask result.append(count) return result
number-of-valid-words-for-each-puzzle
[Python] Trie/Bitmasking Solutions with Explanation
zayne-siew
16
596
number of valid words for each puzzle
1,178
0.465
Hard
18,025
https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/2624615/Hashtable-%2B-bit-masking-in-Python3
class Solution: def gen_combinations(self, word): if not word: yield 0 else: c = word.pop() for v in self.gen_combinations(word): yield v yield v | (1 << (ord(c) - ord('a'))) def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: table = defaultdict(Counter) for w in words: chars = set(list(w)) if len(chars) > 7: continue h = reduce(operator.or_, [1 << (ord(c) - ord('a')) for c in chars], 0) for c in chars: table[c][h] += 1 for i, p in enumerate(puzzles): puzzles[i] = sum(table[p[0]][h] for h in self.gen_combinations(list(p))) return puzzles
number-of-valid-words-for-each-puzzle
Hashtable + bit masking in Python3
metaphysicalist
0
4
number of valid words for each puzzle
1,178
0.465
Hard
18,026
https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/1208409/Python3-bit-mask
class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: freq = defaultdict(int) for word in words: mask = 0 for c in word: mask |= 1 << (ord(c) - 97) freq[mask] += 1 ans = [] for puzzle in puzzles: mask = val = 0 for c in puzzle: mask |= 1 << (ord(c) - 97) mask0 = mask # loop through sub-masks while mask: if mask &amp; (1 << ord(puzzle[0])-97): val += freq[mask] mask = mask0 &amp; (mask - 1) ans.append(val) return ans
number-of-valid-words-for-each-puzzle
[Python3] bit-mask
ye15
0
177
number of valid words for each puzzle
1,178
0.465
Hard
18,027
https://leetcode.com/problems/distance-between-bus-stops/discuss/377844/Python-Explanation
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: a, b = min(start, destination), max(start, destination) return min(sum(distance[a:b]), sum(distance) - sum(distance[a:b]))
distance-between-bus-stops
Python - Explanation
nuclearoreo
8
400
distance between bus stops
1,184
0.541
Easy
18,028
https://leetcode.com/problems/distance-between-bus-stops/discuss/1378831/Python-3-simple-solution
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: if start > destination: start, destination = destination, start d1 = sum(distance[start: destination]) d2 = sum(distance[:start]) + sum(distance[destination:]) return min(d1, d2)
distance-between-bus-stops
Python 3, simple solution
MihailP
2
190
distance between bus stops
1,184
0.541
Easy
18,029
https://leetcode.com/problems/distance-between-bus-stops/discuss/2182074/Python3-O(n)-oror-O(1)-Runtime%3A-63ms-60.00-Memory%3A-14.9mb-93.48
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: # O(n) || O(1) # Runtime: 63ms 60.00% Memory: 14.9mb 93.48% clockWiseDirection = 0 totalSum = 0 for idx, val in enumerate(distance): if start < destination and (idx >= start and idx < destination ): clockWiseDirection += val if start > destination and (idx >= start or idx < destination ): clockWiseDirection += val totalSum += val return min(clockWiseDirection, totalSum-clockWiseDirection)
distance-between-bus-stops
Python3 O(n) || O(1) # Runtime: 63ms 60.00% Memory: 14.9mb 93.48%
arshergon
1
62
distance between bus stops
1,184
0.541
Easy
18,030
https://leetcode.com/problems/distance-between-bus-stops/discuss/1155518/Python3-circular-sweep
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: ans = 0 i = start while i != destination: ans += distance[i] i = (i+1) % len(distance) return min(ans, sum(distance) - ans)
distance-between-bus-stops
[Python3] circular sweep
ye15
1
62
distance between bus stops
1,184
0.541
Easy
18,031
https://leetcode.com/problems/distance-between-bus-stops/discuss/380082/python3-solution-short-and-easy-to-understand
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: if start > destination: start, destination = destination, start return min(sum(distance[start:destination]), sum(distance[:start] + distance[destination:]))
distance-between-bus-stops
python3 solution short and easy to understand
user1996a
1
98
distance between bus stops
1,184
0.541
Easy
18,032
https://leetcode.com/problems/distance-between-bus-stops/discuss/2813259/3-liner-Python-Beats-Time-greater-98
class Solution: def distanceBetweenBusStops(self, distance: List[int], st: int, dest: int) -> int: if st == dest: return 0 one_way = sum(distance[st:dest]) if st < dest else sum(distance[dest:st]) return min(one_way, sum(distance) - one_way)
distance-between-bus-stops
3-liner Python Beats Time -> 98%
RandomNPC
0
1
distance between bus stops
1,184
0.541
Easy
18,033
https://leetcode.com/problems/distance-between-bus-stops/discuss/2812274/Python-2-loops-one-clockwise-one-anti
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: l = len(distance) temp = start if start == destination: return 0 clock_wise = 0 while start != destination: clock_wise += distance[start] start = (start + 1) % l anti = 0 start = temp while start != destination: anti += distance[(start - 1) % l ] start = (start - 1) % l return min(clock_wise, anti)
distance-between-bus-stops
Python 2 loops, one clockwise one anti
vijay_2022
0
3
distance between bus stops
1,184
0.541
Easy
18,034
https://leetcode.com/problems/distance-between-bus-stops/discuss/2659424/Python3-100-faster-with-explanation
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: # get the total distance going forward forwards = sum(distance[start:destination]) #remove the numbers used to go forwards del distance[start:destination] # simply add whatever is left to get the distance to go in reverse reverse = sum(distance) #return the min of those two return min(forwards, reverse)
distance-between-bus-stops
Python3, 100% faster with explanation
cvelazquez322
0
21
distance between bus stops
1,184
0.541
Easy
18,035
https://leetcode.com/problems/distance-between-bus-stops/discuss/2659424/Python3-100-faster-with-explanation
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: start, destination = min(start, destination), max(start, destination) forwards = sum(distance[start:destination]) del distance[start:destination] reverse = sum(distance) return min(forwards, reverse)
distance-between-bus-stops
Python3, 100% faster with explanation
cvelazquez322
0
21
distance between bus stops
1,184
0.541
Easy
18,036
https://leetcode.com/problems/distance-between-bus-stops/discuss/2399973/Python3-Super-fast-easy-solution%3A-start-is-always-minimum
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: start, destination=min(start, destination),max(start, destination) total=sum(distance) d1=sum(distance[start:destination]) return min(total-d1,d1)
distance-between-bus-stops
[Python3] Super fast easy solution: start is always minimum
sunakshi132
0
32
distance between bus stops
1,184
0.541
Easy
18,037
https://leetcode.com/problems/distance-between-bus-stops/discuss/2386777/Python-69ms
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: if start > destination: start, destination = destination, start return min( sum(distance[start:destination]), sum([*distance[destination:], *distance[:start]]) )
distance-between-bus-stops
Python 69ms
Potentis
0
19
distance between bus stops
1,184
0.541
Easy
18,038
https://leetcode.com/problems/distance-between-bus-stops/discuss/2024582/Python-Clean-and-Simple!
class Solution: def distanceBetweenBusStops(self, dist, start, dest): start, dest = (start, dest) if dest > start else (dest, start) route1, route2 = dist[start:dest], dist[:start] + dist[dest:] return min(sum(route1),sum(route2))
distance-between-bus-stops
Python - Clean and Simple!
domthedeveloper
0
78
distance between bus stops
1,184
0.541
Easy
18,039
https://leetcode.com/problems/distance-between-bus-stops/discuss/1836525/2-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-70
class Solution: def distanceBetweenBusStops(self, distance: List[int], s: int, d: int) -> int: if s>d: s,d=d,s return min(sum(distance[s:d]), sum(distance)-sum(distance[s:d]))
distance-between-bus-stops
2-Lines Python Solution || 75% Faster || Memory less than 70%
Taha-C
0
32
distance between bus stops
1,184
0.541
Easy
18,040
https://leetcode.com/problems/distance-between-bus-stops/discuss/1675897/Python3-dollarolution-(96-faster)
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: dist, i = 0, start while i != destination: dist += distance[i] i += 1 if i > len(distance) - 1: i = 0 if dist > sum(distance) - dist: dist = sum(distance) - dist return dist
distance-between-bus-stops
Python3 $olution (96% faster)
AakRay
0
95
distance between bus stops
1,184
0.541
Easy
18,041
https://leetcode.com/problems/distance-between-bus-stops/discuss/1422605/Python3-Easy-To-Understand-44-ms-Memory-Less-Than-92.27
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: n, i, c1, c2 = len(distance), start, 0, 0 while(i != destination): c1 += distance[i] i += 1 i %= n i = start while(i != destination): i -= 1 c2 += distance[i] i %= n return min(c1, c2)
distance-between-bus-stops
Python3 Easy To Understand, 44 ms, Memory Less Than 92.27%
Hejita
0
66
distance between bus stops
1,184
0.541
Easy
18,042
https://leetcode.com/problems/distance-between-bus-stops/discuss/1146976/Python3-simple-solution
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: x = sum(distance) if start < destination: a = sum(distance[start:destination]) return min(a,x-a) else: start,destination = destination,start a = sum(distance[start:destination]) return min(a,x-a)
distance-between-bus-stops
Python3 simple solution
EklavyaJoshi
0
30
distance between bus stops
1,184
0.541
Easy
18,043
https://leetcode.com/problems/distance-between-bus-stops/discuss/682668/Python-Easy-Solution
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: start, destination = min(start, destination), max(start, destination) return min(sum(distance[start:destination]), sum(distance) - sum(distance[start:destination]))
distance-between-bus-stops
Python - Easy Solution
noobie12
0
64
distance between bus stops
1,184
0.541
Easy
18,044
https://leetcode.com/problems/distance-between-bus-stops/discuss/620370/Intuitive-approach-by-pick-up-the-shorter-distance-from-clockwise-or-counterclockwise-paths
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: # corner/edge case if start == destination: return 0 n = len(distance) ''' Number of stop''' def dist_clockwise(s, e): return distance[s:e] def get_previous_stop(s): s = s - 1 return n + s if s < 0 else s def dist_counterclockwise(s, e): dist = 0 s = get_previous_stop(s) dist += distance[s] while s != e: s = get_previous_stop(s) dist += distance[s] return dist # Keep start stop before destination stop for easy process if start > destination: start ,destination = destination, start # Calculate the distances of clockwise/counterclockwise and return the shorter one return min(dist_clockwise(start, destination), dist_counterclockwise(start, destination))
distance-between-bus-stops
Intuitive approach by pick up the shorter distance from clockwise or counterclockwise paths
puremonkey2001
0
48
distance between bus stops
1,184
0.541
Easy
18,045
https://leetcode.com/problems/distance-between-bus-stops/discuss/556744/python3-easy-solution
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: ''' Time: O(n) Space: O(1) ''' # base case if start == destination: return 0 total, dist = 0, 0 flag = False for i, val in enumerate(distance): total += val if i == start or i == destination: flag = not flag if flag: dist += vala return min(dist, total-dist)
distance-between-bus-stops
python3 easy solution
nightybear
0
51
distance between bus stops
1,184
0.541
Easy
18,046
https://leetcode.com/problems/distance-between-bus-stops/discuss/401672/Easy-Python-Solution-2-liner-code
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: distance = distance[start:]+distance[:start] end = destination - start return min(sum(distance[:end]), sum(distance[end:]))
distance-between-bus-stops
Easy Python Solution 2 liner code
saffi
0
109
distance between bus stops
1,184
0.541
Easy
18,047
https://leetcode.com/problems/distance-between-bus-stops/discuss/377560/Solution-in-Python-3-(beats-100.0-)-(one-line)
class Solution: def distanceBetweenBusStops(self, D: List[int], s: int, d: int) -> int: return min(sum(D[min(s,d):max(s,d)]), sum(D)-sum(D[min(s,d):max(s,d)])) - Junaid Mansuri (LeetCode ID)@hotmail.com
distance-between-bus-stops
Solution in Python 3 (beats 100.0 %) (one line)
junaidmansuri
0
163
distance between bus stops
1,184
0.541
Easy
18,048
https://leetcode.com/problems/day-of-the-week/discuss/1084728/Python3-simple-solution
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: prev_year = year - 1 days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400 days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1]) days += day if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0): days += 1 return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][days % 7]
day-of-the-week
Python3 simple solution
EklavyaJoshi
7
333
day of the week
1,185
0.576
Easy
18,049
https://leetcode.com/problems/day-of-the-week/discuss/1155604/Python3-formula
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: def fn(y, m, d): """Return year-month-day in number format.""" if m < 3: y -= 1 m += 12 return 365*y + y//4 - y//100 + y//400 + (153*m + 8)//5 + d weekday = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") return weekday[(fn(year, month, day) - fn(2021, 4, 11)) % 7]
day-of-the-week
[Python3] formula
ye15
2
112
day of the week
1,185
0.576
Easy
18,050
https://leetcode.com/problems/day-of-the-week/discuss/2186971/Python-Solution-Tomokoshi-Sakamoto-Algorithm
class Solution: def dayOfTheWeek(self, d: int, m: int, y: int) -> str: day=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] if (m < 3) : y = y - 1 return day[((y + y // 4 - y // 100 + y // 400 + t[m - 1] + d) % 7)]
day-of-the-week
Python Solution Tomokoshi Sakamoto Algorithm
Kunalbmd
0
156
day of the week
1,185
0.576
Easy
18,051
https://leetcode.com/problems/day-of-the-week/discuss/2045923/Python-simple-solution
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: import time day_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return day_of_week[time.strptime(f'{day} {month} {year}', '%d %m %Y')[6]]
day-of-the-week
Python simple solution
StikS32
0
220
day of the week
1,185
0.576
Easy
18,052
https://leetcode.com/problems/day-of-the-week/discuss/1850058/2-Lines-Python-Solution-oror-40-Faster-oror-Memory-less-than-85
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: week_days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] return week_days[date(year,month,day).weekday()]
day-of-the-week
2-Lines Python Solution || 40% Faster || Memory less than 85%
Taha-C
0
176
day of the week
1,185
0.576
Easy
18,053
https://leetcode.com/problems/day-of-the-week/discuss/1850058/2-Lines-Python-Solution-oror-40-Faster-oror-Memory-less-than-85
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return date(year,month,day).strftime("%A")
day-of-the-week
2-Lines Python Solution || 40% Faster || Memory less than 85%
Taha-C
0
176
day of the week
1,185
0.576
Easy
18,054
https://leetcode.com/problems/day-of-the-week/discuss/1841590/No-import-Python3-solution-Sort-of-easy-to-understand
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: # Using this peculiar Quora answer: https://www.quora.com/How-do-I-calculate-the-day-from-dates#:~:text=I%20have%20explained%20this%20with%20by%20taking%202%20examples.%20hope%20this%20will%20help%20you. # For months after February in 2100, the day is off by one. n_non_leap_year = { 1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151, 7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334, } n_leap_year = { 1: 0, 2: 31, 3: 60, 4: 91, 5: 121, 6: 152, 7: 182, 8: 213, 9: 244, 10: 274, 11: 305, 12: 335, } k_non_leap_year = { 0: "Friday", 1: "Saturday", 2: "Sunday", 3: "Monday", 4: "Tuesday", 5: "Wednesday", 6: "Thursday", } k_leap_year = { 0: "Thursday", 1: "Friday", 2: "Saturday", 3: "Sunday", 4: "Monday", 5: "Tuesday", 6: "Wednesday", } if year != 2100: if year % 4 == 0: if year % 100 == 0: if year % 200 == 0: return k_leap_year[ math.floor( ((year / 4 + year + day + n_leap_year[month]) % 7) ) ] else: return k_non_leap_year[ math.floor( ((year / 4 + year + day + n_non_leap_year[month]) % 7) ) ] else: return k_leap_year[ math.floor(((year / 4 + year + day + n_leap_year[month]) % 7)) ] else: return k_non_leap_year[ math.floor(((year / 4 + year + day + n_non_leap_year[month]) % 7)) ] else: z = math.floor(((year / 4 + year + day + n_leap_year[month]) % 7)) if month == 1 or month == 2: return k_leap_year[z] else: return k_leap_year[z - 1]
day-of-the-week
No import Python3 solution - Sort-of easy to understand
y-arjun-y
0
121
day of the week
1,185
0.576
Easy
18,055
https://leetcode.com/problems/day-of-the-week/discuss/1411994/Python3-Zeller's-Formula-Memory-Less-Than-93.79
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: d = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] if month == 1: year -= 1 month = 11 elif month == 2: year -= 1 month = 12 else: month -= 2 D, C = int(str(year)[2:]), int(str(year)[:2]) r = day + ((13 * month - 1) // 5) + D + (D // 4) + (C // 4) - (2 * C) return d[int(r % 7)]
day-of-the-week
Python3 Zeller's Formula, Memory Less Than 93.79%
Hejita
0
169
day of the week
1,185
0.576
Easy
18,056
https://leetcode.com/problems/day-of-the-week/discuss/1120999/Easily-understandable-syntax-with-logic
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # The first day of 1971 was Thursday week_day = [ "Thursday", "Friday", "Saturday","Sunday", "Monday", "Tuesday", "Wednesday"] no_of_days = 0 for i in range(1971, year): if (i % 400 == 0) or (i % 4 == 0 and i % 100 != 0): no_of_days += 366 else: no_of_days += 365 # If current year is leap year and month is more than February then extra 1 day needs to be added if ((year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)): if (month > 2): no_of_days += 1 for i in range(1, month): no_of_days += months[i] no_of_days += day return (week_day[(no_of_days % 7)])
day-of-the-week
Easily understandable syntax with logic
ashish87
0
100
day of the week
1,185
0.576
Easy
18,057
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1104253/Python-Kadane's-Algorithm-easy-solution
class Solution: def maximumSum(self, arr: List[int]) -> int: n = len(arr) #maximum subarray starting from the last element i.e. backwards prefix_sum_ending = [float('-inf')]*n #maximum subarray starting from the first element i.e forwards prefix_sum_starting = [float('-inf')]*n prefix_sum_ending[n-1] = arr[n-1] prefix_sum_starting[0] = arr[0] for i in range(1,n): prefix_sum_starting[i] = max(prefix_sum_starting[i-1]+arr[i], arr[i]) for i in range(n-2,-1,-1): prefix_sum_ending[i] = max(prefix_sum_ending[i+1]+arr[i], arr[i]) max_without_deletion = max(prefix_sum_starting) max_with_deletion = float('-inf') for i in range(1,n-1): max_with_deletion = max(max_with_deletion, prefix_sum_starting[i-1]+prefix_sum_ending[i+1]) return max(max_without_deletion, max_with_deletion)
maximum-subarray-sum-with-one-deletion
[Python] Kadane's Algorithm easy solution
msd1311
8
522
maximum subarray sum with one deletion
1,186
0.413
Medium
18,058
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1155630/Python3-bottom-up-dp
class Solution: def maximumSum(self, arr: List[int]) -> int: ans = d0 = d1 = -inf # delete 0 &amp; delete 1 element for x in arr: d0, d1 = max(x, x + d0), max(d0, x + d1) ans = max(ans, d0, d1) return ans
maximum-subarray-sum-with-one-deletion
[Python3] bottom-up dp
ye15
2
149
maximum subarray sum with one deletion
1,186
0.413
Medium
18,059
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1079615/python-O(n)-time-and-O(n)-space-for-beginner's
class Solution: def maximumSum(self, arr: List[int]) -> int: def solve(): res=-sys.maxsize cur_max,max_so_far=arr[0],arr[0] fw[0]=cur_max for i in range(1,n): cur_max=max(arr[i], cur_max + arr[i]) max_so_far=max(max_so_far, cur_max) fw[i] = cur_max res=max(res,max_so_far) cur_max=max_so_far=bw[n-1]=arr[n-1] i=n-2 while i>=0: cur_max=max(arr[i],cur_max+arr[i]) max_so_far=max(max_so_far,cur_max) bw[i]=cur_max res=max(res,max_so_far) i-=1 i=0 while(i<n): x=max(i-1,0) y=min(i+1,n-1) if x!=y: res=max(res,fw[x]+bw[y]) i+=1 return res n = len(arr) fw = [0 for k in range(n)] bw = [0 for k in range(n)] return solve()
maximum-subarray-sum-with-one-deletion
python O(n) time and O(n) space for beginner's
_Rehan12
1
105
maximum subarray sum with one deletion
1,186
0.413
Medium
18,060
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/791512/Python-o(N)-time-and-o(1)-space
class Solution(object): def maximumSum(self, arr): arrLen = len(arr) prevMaxSub = arr[0] prevMaxSubWithDeletion = arr[0] maxSubWithDel = prevMaxSubWithDeletion for i in range(1, arrLen): newMaxSub = max(arr[i] + prevMaxSub, arr[i]) prevMaxSubWithDeletion = max(prevMaxSubWithDeletion + arr[i], newMaxSub, prevMaxSub) maxSubWithDel = max(maxSubWithDel, prevMaxSubWithDeletion) prevMaxSub = newMaxSub return maxSubWithDel """ :type arr: List[int] :rtype: int """
maximum-subarray-sum-with-one-deletion
Python o(N) time and o(1) space
masumvotres
1
316
maximum subarray sum with one deletion
1,186
0.413
Medium
18,061
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/2801414/Python-(Simple-Dynamic-Programming)
class Solution: def maximumSum(self, arr): n = len(arr) dp0, dp1, max_val = [0]*n, [0]*n, arr[0] dp0[0] = arr[0] for i in range(1,n): dp0[i] = max(dp0[i-1] + arr[i],arr[i]) dp1[i] = max(dp1[i-1] + arr[i],arr[i],dp0[i-1]) max_val = max(max_val,dp0[i],dp1[i]) return max_val
maximum-subarray-sum-with-one-deletion
Python (Simple Dynamic Programming)
rnotappl
0
4
maximum subarray sum with one deletion
1,186
0.413
Medium
18,062
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/2702770/ritik
class Solution: def maximumSum(self, nums: List[int]) -> int: f=[0]*len(nums) b=[0]*len(nums) n=len(nums) max1=nums[0] f[0]=nums[0] b=[0]*len(nums) b[n-1]=nums[n-1] for i in range(len(nums)-1): if f[i]<0: f[i+1]=nums[i+1] else: f[i+1]=nums[i+1]+f[i] if f[i+1]>max1: max1=f[i+1] for i in range(n-2,-1,-1): if b[i+1]<0: b[i]=nums[i] else: b[i]=nums[i]+b[i+1] if f[i+1]>max1: max1=f[i+1] for i in range(1,n-1): if f[i-1]+b[i+1]>max1: max1=f[i-1]+b[i+1] return max1
maximum-subarray-sum-with-one-deletion
ritik
RITIK_30454
0
4
maximum subarray sum with one deletion
1,186
0.413
Medium
18,063
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/2285767/PYTHON-or-O(N)-or-EXPLAINED-WITH-PICTURE-or-DETAILED-EXPLANATION-or
class Solution: def maximumSum(self, arr: List[int]) -> int: ans = -float('inf') m = max(arr) if m <= 0: return m n = len(arr) skip,noSkip = [0]*n,[0]*n for i in range(n): skip[i] = max(skip[i-1]+arr[i],noSkip[i-1]) noSkip[i] = max(arr[i],arr[i]+noSkip[i-1]) ans = max(skip[i],noSkip[i],ans) return ans
maximum-subarray-sum-with-one-deletion
PYTHON | O(N) | EXPLAINED WITH PICTURE | DETAILED EXPLANATION |
reaper_27
0
58
maximum subarray sum with one deletion
1,186
0.413
Medium
18,064
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1607280/Python3DP-O(n)-time-O(1)-space
class Solution: def maximumSum(self, arr: List[int]) -> int: # noDeletions, oneDeletion, max nodel = onedel = mx = arr[0] for i in range(1, len(arr)): nodel2 = nodel nodel = max(arr[i], arr[i] + nodel) onedel = max(arr[i], arr[i] + onedel, max(0, arr[i]) + nodel2) mx = max(mx, nodel, onedel) return mx
maximum-subarray-sum-with-one-deletion
[Python3][DP] O(n) time, O(1) space
mardlucca
0
136
maximum subarray sum with one deletion
1,186
0.413
Medium
18,065
https://leetcode.com/problems/make-array-strictly-increasing/discuss/1155655/Python3-top-down-dp
class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: arr2.sort() @cache def fn(i, prev): """Return min ops to make arr1[i:] increasing w/ given previous element.""" if i == len(arr1): return 0 ans = inf if (prev < arr1[i]): ans = fn(i+1, arr1[i]) k = bisect_right(arr2, prev) if k < len(arr2): ans = min(ans, 1 + fn(i+1, arr2[k])) return ans ans = fn(0, -inf) return ans if ans < inf else -1
make-array-strictly-increasing
[Python3] top-down dp
ye15
2
196
make array strictly increasing
1,187
0.452
Hard
18,066
https://leetcode.com/problems/make-array-strictly-increasing/discuss/2290360/PYTHON-or-DETAILED-EXPLANATION-or-INTUTION-EXPLAINED-or-DP-or-CLEAR-AND-CONCISE-or
class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: n1 , n2, dp = len(arr1) , len(arr2) , {} arr2.sort() def solve(i , j , prev): if i == n1:return 0 if (i,j,prev) in dp: return dp[(i,j,prev)] k = bisect.bisect_right(arr2[j:],prev) + j ans = float('inf') if k == n2 else solve(i+1,k+1,arr2[k]) + 1 if arr1[i] > prev:ans = min(ans,solve(i+1 , j ,arr1[i])) dp[(i,j,prev)] = ans return ans ans = solve(0,0,-float('inf')) return ans if ans != float('inf') else -1
make-array-strictly-increasing
PYTHON | DETAILED EXPLANATION | INTUTION EXPLAINED | DP | CLEAR AND CONCISE |
reaper_27
0
105
make array strictly increasing
1,187
0.452
Hard
18,067
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1013213/2-Line-Python-using-Counter
class Solution: def maxNumberOfBalloons(self, text: str) -> int: c = collections.Counter(text) return min(c['b'],c['a'],c['l']//2,c['o']//2,c['n'])
maximum-number-of-balloons
2 Line Python using Counter
majinlion
8
385
maximum number of balloons
1,189
0.618
Easy
18,068
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1115806/Easy-Python-Solution-O(n)-time-Simple-If-Else
class Solution: def maxNumberOfBalloons(self, text: str) -> int: b = a = l = o = n = 0 for i in text: if i == 'b': b += 1 elif i == 'a': a += 1 elif i == 'l': l += 1 elif i == 'n': n += 1 elif i == 'o': o += 1 count = 0 while b and a and l and o and n: if b and a and l - 1 and o - 1 and n: count += 1 b =- 1 a -= 1 l -= 2 o -= 2 n -= 1 else: break return count
maximum-number-of-balloons
Easy Python Solution O(n) time - Simple If-Else
vanigupta20024
5
544
maximum number of balloons
1,189
0.618
Easy
18,069
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1461848/Pythonic-2-Liner-With-Comments-or-O(n)-Time-and-Space
class Solution: def maxNumberOfBalloons(self, text: str) -> int: # Counts the frequency of each character in text seen = collections.Counter(text) # The minimum number of Balloons can be no more than the least frequent character return min(seen['b'], seen['a'], seen['l']//2, seen['o']//2, seen['n'])
maximum-number-of-balloons
Pythonic 2 Liner With Comments | O(n) Time & Space
APet99
4
202
maximum number of balloons
1,189
0.618
Easy
18,070
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1574357/Python-very-easy-fast-solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: counter = collections.Counter(text) counter['l'] //= 2 counter['o'] //= 2 return min(counter[c] for c in 'balon')
maximum-number-of-balloons
Python very easy fast solution
dereky4
3
394
maximum number of balloons
1,189
0.618
Easy
18,071
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2000263/Python-Clean-and-Simple!-Counter-%2B-One-Liner!
class Solution: def maxNumberOfBalloons(self, text): countText = Counter(text) countWord = Counter("balloon") return min(countText[c] // countWord[c] for c in countWord)
maximum-number-of-balloons
Python - Clean and Simple! Counter + One Liner!
domthedeveloper
1
203
maximum number of balloons
1,189
0.618
Easy
18,072
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2000263/Python-Clean-and-Simple!-Counter-%2B-One-Liner!
class Solution: def maxNumberOfBalloons(self, text): return (lambda w : (lambda t : min(t[c] // w[c] for c in w))(Counter(text)))(Counter("balloon"))
maximum-number-of-balloons
Python - Clean and Simple! Counter + One Liner!
domthedeveloper
1
203
maximum number of balloons
1,189
0.618
Easy
18,073
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1762456/Easy-Python-Solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: count = Counter(text) b = Counter('balloon') ans = [] for i in b.keys(): ans.append(count[i]//b[i]) return min(ans)
maximum-number-of-balloons
Easy Python Solution
MengyingLin
1
108
maximum number of balloons
1,189
0.618
Easy
18,074
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1723197/Python-3-Line-Solution-oror-Runtime-%3A-87-oror-Memory-Usage-%3A-100
class Solution: def maxNumberOfBalloons(self, text: str) -> int: balloon = {'b': 1, 'a': 1, 'l': 2, 'o': 2, 'n': 1} countText = Counter(text) return min([countText[c] // balloon[c] for c in balloon]) ```
maximum-number-of-balloons
Python 3 Line Solution || Runtime : 87% || Memory Usage : 100%
Pootato
1
223
maximum number of balloons
1,189
0.618
Easy
18,075
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1345044/Simple-Python-solution-using-dictionary
class Solution: def maxNumberOfBalloons(self, text: str) -> int: # create mapping dictionary that stores the number of frequency of each charater in the given text mapping = {} for i in text: if i in mapping: mapping[i] = mapping[i] + 1 else: mapping[i] = 1 # return the minimum possible number of combinations of 'balloon' if every character in ballon is found in the text, otherwise return 0 if 'b' in mapping and 'a' in mapping and 'l' in mapping and 'o' in mapping and 'n' in mapping: return min(mapping['b'],mapping['a'],mapping['l']//2,mapping['o']//2,mapping['n']) return 0
maximum-number-of-balloons
Simple Python solution using dictionary
tianshuhuang6
1
115
maximum number of balloons
1,189
0.618
Easy
18,076
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1311826/Python3-2-fast-and-simple-sollutions
class Solution: def maxNumberOfBalloons(self, text: str) -> int: count = collections.Counter(text) ht = {'a': 1, 'b': 1, 'l': 2, 'n': 1, 'o': 2, } return min(count[c] // ht[c] for c in ht)
maximum-number-of-balloons
Python3, 2 fast and simple sollutions
MihailP
1
175
maximum number of balloons
1,189
0.618
Easy
18,077
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1311826/Python3-2-fast-and-simple-sollutions
class Solution: def maxNumberOfBalloons(self, text: str) -> int: count = {c: 0 for c in 'ablno'} for c in text: if c in count: count[c] += 1 ht = {'a': 1, 'b': 1, 'l': 2, 'n': 1, 'o': 2, } return min(count[c] // ht[c] for c in count)
maximum-number-of-balloons
Python3, 2 fast and simple sollutions
MihailP
1
175
maximum number of balloons
1,189
0.618
Easy
18,078
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1200621/Python-Extremely-Easy-and-Slow-Solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: count = 0 txt = list(text) while(True): try: txt.remove('b') txt.remove('a') txt.remove('l') txt.remove('l') txt.remove('o') txt.remove('o') txt.remove('n') count+=1 except: return(count)
maximum-number-of-balloons
Python Extremely Easy and Slow Solution
ekagrashukla
1
75
maximum number of balloons
1,189
0.618
Easy
18,079
https://leetcode.com/problems/maximum-number-of-balloons/discuss/383163/PythonPython3-Two-lines-using-a-Counter
class Solution(object): def maxNumberOfBalloons(self, text): counts = Counter(text) return min( counts['b'], counts['a'], counts['l'] // 2, counts['o'] // 2, counts['n'] )
maximum-number-of-balloons
[Python/Python3] Two lines using a Counter
jacquerie
1
100
maximum number of balloons
1,189
0.618
Easy
18,080
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2812455/Solution-with-a-hashmap-using-Python3
class Solution: def maxNumberOfBalloons(self, text: str) -> int: # use a hashmap target = 'baloon' hashmap = {n: 0 for n in target} for t in text: if t in hashmap: hashmap[t] = hashmap.get(t, 0) + 1 res = float('inf') for key, val in hashmap.items(): if key == 'o' or key == 'l': hashmap[key] = int(val / 2) res = min(res, hashmap[key]) return res
maximum-number-of-balloons
Solution with a hashmap using Python3
Leah-Lyu
0
3
maximum number of balloons
1,189
0.618
Easy
18,081
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2802887/Faster-Python-solution-beat-80-People
class Solution: def maxNumberOfBalloons(self, text: str) -> int: dic = {'b':0,'a':0,'l':0,'o':0,'n':0} #print(dic) for i in text: if i in dic.keys(): dic[i]+=1 #print(dic) dic['l']//=2 dic['o']//=2 min=dic['b'] for i in dic.values(): if i<min: min=i return min
maximum-number-of-balloons
Faster Python solution beat 80% People
Ashil_3108
0
5
maximum number of balloons
1,189
0.618
Easy
18,082
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2800639/Simple-Python3-solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0} for char in text: if not char in freq: continue step = 0.5 if char == 'l' or char == 'o' else 1 freq[char] += step result = min(freq.values()) return floor(result)
maximum-number-of-balloons
βœ… Simple Python3 solution
zamaletdinov
0
4
maximum number of balloons
1,189
0.618
Easy
18,083
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2786071/Optimized-Solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: counterText = Counter(text) balloon = Counter("balloon") res = len(text) for c in balloon: res = min(res, counterText[c] // balloon[c]) return res
maximum-number-of-balloons
Optimized Solution
swaruptech
0
2
maximum number of balloons
1,189
0.618
Easy
18,084
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2777153/A-Very-Simple-Python-Dictionary-Solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: counts = {'b':0, 'a':0, 'l':0, 'o':0, 'n':0} for letter in text: if letter in counts: counts[letter] += 1 counts['l'] //= 2 counts['o'] //= 2 return min(counts.values())
maximum-number-of-balloons
A Very Simple Python Dictionary Solution
kcstar
0
4
maximum number of balloons
1,189
0.618
Easy
18,085
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2665388/Python%2BCounter
class Solution: def maxNumberOfBalloons(self, text: str) -> int: c1=Counter(text) c2=Counter("balloon") x=c1 k=0 if c2<=c1: while c2<=x: x=x-c2 k=k+1 return k
maximum-number-of-balloons
Python+Counter
Leox2022
0
6
maximum number of balloons
1,189
0.618
Easy
18,086
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2647762/Python-Solution-using-HashMap-and-Strings
class Solution: def maxNumberOfBalloons(self, text: str) -> int: ballon = {} balloon = 'balloon' for i in text: if i in balloon: if i in ballon: ballon[i] += 1 else: ballon[i] = 1 ball = [0]*len('balon') for i in ballon: if i == 'b': ball[0] = ballon[i] elif i == 'a': ball[1] = ballon[i] elif i == 'l': ball[2] = ballon[i] elif i == 'o': ball[3] = ballon[i] elif i == 'n': ball[4] = ballon[i] if ball[2] > ball[3]: ball[2] = ball[3] else: ball[3] = ball[2] minVal = min(ball[0], ball[1], ball[4]) ball[0], ball[1], ball[4] = minVal, minVal, minVal if ball[3]%2: ball[3], ball[2] = ball[3]-1, ball[3]-1 print(ball) if 0 in ball: return 0 if ball[3] < 2: return 0 return min(ball[3]//2, ball[0])
maximum-number-of-balloons
Python Solution using HashMap and Strings
joelkurien
0
5
maximum number of balloons
1,189
0.618
Easy
18,087
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2602555/over-complicated-%3A-)
class Solution: def maxNumberOfBalloons(self, text: str) -> int: text_counter = Counter(text) returned = inf for char, count in Counter("balloon").items(): if text_counter[char] < count: return 0 else: returned = min(returned, text_counter[char] // count) return returned
maximum-number-of-balloons
over complicated :-)
Potentis
0
18
maximum number of balloons
1,189
0.618
Easy
18,088
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2506773/Python-or-using-nested-if-else-loops-or-Beats-99-in-memory-usage-and-52-in-Runtime
class Solution: def maxNumberOfBalloons(self, text: str) -> int: lst=[] for i in "balloon": c=text.count(i) if c==0: return 0 break else: if i=="l" or i=="o": if c%2==0: lst.append(c//2) else: lst.append((c-1)//2) else: lst.append(c) return min(lst)
maximum-number-of-balloons
Python | using nested if-else loops | Beats 99% in memory usage and 52% in Runtime
keertika27
0
43
maximum number of balloons
1,189
0.618
Easy
18,089
https://leetcode.com/problems/maximum-number-of-balloons/discuss/2395077/Python-hashmap
class Solution: def maxNumberOfBalloons(self, text: str) -> int: d1={} for i in text: if i in d1: d1[i]+=1 else: d1[i]=1 d2={} for i in "balloon": if i in d2: d2[i]+=1 else: d2[i]=1 min_=10001 for i in d2: if i in d1: min_=min(min_,d1[i]//d2[i]) else: return 0 return min_
maximum-number-of-balloons
Python hashmap
sunakshi132
0
65
maximum number of balloons
1,189
0.618
Easy
18,090
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1937045/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def maxNumberOfBalloons(self, text: str) -> int: count = {'b':0, 'a':0, 'l':0, 'o':0,'n':0} op = 0 mini = 11111111111111 for i in text: if i in "balon": print(i) count[i]+=1 print(count) for i,n in count.items(): if i == 'o' or i == 'l': mini = min(n//2, mini) else: mini = min(n, mini) return mini
maximum-number-of-balloons
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
87
maximum number of balloons
1,189
0.618
Easy
18,091
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1723174/Python3-Memory-Usage-less-than-100
class Solution: def maxNumberOfBalloons(self, text: str) -> int: occ1 = {c : "balloon".count(c) for c in "balloon"} occ2 = {c : text.count(c) for c in text if c in occ1} if len(occ1) != len(occ2) or not all([occ1[key] <= occ2[key] for key in occ1]): return 0 return min([occ2[key] // occ1[key] for key in occ1])
maximum-number-of-balloons
Python3 Memory Usage less than 100%
Pootato
0
113
maximum number of balloons
1,189
0.618
Easy
18,092
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1544470/3-lines-Python-solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: char_count = defaultdict(int) for char in text: char_count[char] += 1 return min(char_count['b'], char_count['a'], char_count['l'] // 2, char_count['o'] // 2, char_count['n'])
maximum-number-of-balloons
3 lines Python solution
akshaykumar19002
0
144
maximum number of balloons
1,189
0.618
Easy
18,093
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1461057/Python3
class Solution: def maxNumberOfBalloons(self, text: str) -> int: d = { 'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0, } for t in text: if t in d: d[t] += 1 min_from_double = min(d['l'], d['o']) // 2 min_from_single = min(d['b'], d['a'], d['n']) return min(min_from_double, min_from_single)
maximum-number-of-balloons
[Python3]
maosipov11
0
31
maximum number of balloons
1,189
0.618
Easy
18,094
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1460990/Python3-solution-or-counting-aproach
class Solution: def maxNumberOfBalloons(self, text: str) -> int: d = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0} count = 0 for i in range(len(text)): if text[i] in d: d[text[i]] += 1 if d['a'] >= 1 and d['b'] >= 1 and d['l'] >= 2 and d['o'] >= 2 and d['n'] >= 1: d['a'] -= 1 d['b'] -= 1 d['o'] -= 2 d['l'] -= 2 d['n'] -= 1 count += 1 return count
maximum-number-of-balloons
Python3 solution | counting aproach
FlorinnC1
0
57
maximum number of balloons
1,189
0.618
Easy
18,095
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1191155/Simple-python-solution
class Solution: def maxNumberOfBalloons(self, text: str) -> int: dict = {"b":0,"a":0,"l":0,"o":0,"n":0} for i in text: if i in dict: dict[i] +=1 dict['l'] = dict['l']//2 dict['o'] = dict['o']//2 return min(dict.values())
maximum-number-of-balloons
Simple python solution
sunnysharma03
0
80
maximum number of balloons
1,189
0.618
Easy
18,096
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1155312/Python3-freq-table
class Solution: def maxNumberOfBalloons(self, text: str) -> int: ref = {"a":1, "b":1, "l":2, "n":1, "o":2} freq = Counter(text) return min(freq[c]//ref[c] for c in ref)
maximum-number-of-balloons
[Python3] freq table
ye15
0
63
maximum number of balloons
1,189
0.618
Easy
18,097
https://leetcode.com/problems/maximum-number-of-balloons/discuss/473152/Python3-24-ms-faster-than-94.96-of-Python-3
class Solution: def maxNumberOfBalloons(self, text: str) -> int: S = "balon" dir = dict() for s in S: if s in text: if s == 'l' or s == 'o': dir[s] = int(text.count(s)/2) else: dir[s] = text.count(s) text = text.replace(s, "") else: dir[s] = 0 return min(dir.values())
maximum-number-of-balloons
[Python3] 24 ms, faster than 94.96% of Python 3
stanley98745
0
307
maximum number of balloons
1,189
0.618
Easy
18,098
https://leetcode.com/problems/maximum-number-of-balloons/discuss/382510/Solution-in-Python-3-(beats-100.0-)-(one-line)
class Solution: def maxNumberOfBalloons(self, t: str) -> int: return (lambda x: min(x[i]//(1 + (i in 'lo')) for i in 'balon'))(collections.Counter(t)) - Junaid Mansuri (LeetCode ID)@hotmail.com
maximum-number-of-balloons
Solution in Python 3 (beats 100.0 %) (one line)
junaidmansuri
0
210
maximum number of balloons
1,189
0.618
Easy
18,099