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/replace-elements-in-an-array/discuss/2114715/Simple-Python-Solution-Hashmap-and-list-O(N%2BK)-time-O(N)-space-complexity
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: results = [0 for i in range(len(nums))] ht = defaultdict(list) for i in range(len(nums)): ht[nums[i]].append(i) for old, new in operations: ht[new].append(ht[old].pop()) for i in ht: for index in ht[i]: results[index] = i return results
replace-elements-in-an-array
Simple Python Solution - Hashmap and list - O(N+K) time, O(N) space complexity
lcshiung
0
11
replace elements in an array
2,295
0.576
Medium
31,700
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2114192/Python-Easy-and-Efficient-Map-Solution
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: d = {} for x, y in reversed(operations) : d[x] = d[y] if y in d else y for i, x in enumerate(nums) : if x in d : nums[i] = d[x] return nums
replace-elements-in-an-array
Python Easy and Efficient Map Solution
runtime-terror
0
23
replace elements in an array
2,295
0.576
Medium
31,701
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112631/Python-Simple-Python-Solution-Using-Dictionary-oror-HashMap
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: store_index = {} for i in range(len(nums)): store_index[nums[i]] = i for i in operations: old_value , new_value = i index = store_index[old_value] nums[store_index[old_value]] = new_value del store_index[old_value] store_index[new_value] = index return nums
replace-elements-in-an-array
[ Python ] ✅✅ Simple Python Solution Using Dictionary || HashMap 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
24
replace elements in an array
2,295
0.576
Medium
31,702
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112420/Concise-Python-Solution
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: d = {n: i for i, n in enumerate(nums)} for x, y in operations: d[y] = d[x] del d[x] ans = [0] * len(nums) for k, v in d.items(): ans[v] = k return ans
replace-elements-in-an-array
Concise Python Solution
user6397p
0
19
replace elements in an array
2,295
0.576
Medium
31,703
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112280/Python-3-DictHashmap-Solution-8-lines
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: hmap = {} for i,num in enumerate(nums): hmap[num] = i for op in operations: index = hmap[op[0]] nums[index] = op[1] hmap[op[1]] = index return nums
replace-elements-in-an-array
[Python 3] Dict/Hashmap Solution - 8 lines
parthberk
0
14
replace elements in an array
2,295
0.576
Medium
31,704
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2111972/Python-or-Easy-to-Understand
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: # traverse from the end to the front! n = len(operations) dic = defaultdict() for i in range(n-1, -1, -1): key, value = operations[i] if value in dic: tmp = dic[value] del dic[value] dic[key] = tmp else: dic[key] = value for i, num in enumerate(nums): if num in dic: nums[i] = dic[num] return nums
replace-elements-in-an-array
Python | Easy to Understand
Mikey98
0
27
replace elements in an array
2,295
0.576
Medium
31,705
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2111971/Python-or-Hashmap-or-dictionary-or-O(N)-time-complexity
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: d = {} for i in range(len(nums)): d[nums[i]] = i for a,b in operations: if a in d: d[b] = d[a] d[a] = -1 for i in d: if d[i]!=-1: nums[d[i]] = i return nums
replace-elements-in-an-array
Python | Hashmap | dictionary | O(N) time complexity
AkashHooda
0
16
replace elements in an array
2,295
0.576
Medium
31,706
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2111931/Python-Very-simple-Hashmap-solution-O(n-%2B-m)
class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: hashmap = {} for i, number in enumerate(nums): hashmap[number] = i for start, end in operations: if start in hashmap: nums[hashmap[start]] = end hashmap[end] = hashmap[start] return nums
replace-elements-in-an-array
Python Very simple Hashmap solution O(n + m)
tyrocoder
0
20
replace elements in an array
2,295
0.576
Medium
31,707
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139499/Nothing-Special
class Solution: def strongPasswordCheckerII(self, pwd: str) -> bool: return ( len(pwd) > 7 and max(len(list(p[1])) for p in groupby(pwd)) == 1 and reduce( lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0 ) == 15 )
strong-password-checker-ii
Nothing Special
votrubac
22
882
strong password checker ii
2,299
0.567
Easy
31,708
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139347/PythonJavaC%2B%2BCJavaScriptPHP-Regex
class Solution: def strongPasswordCheckerII(self, password): return re.match(r'^(?!.*(.)\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()+-]).{8,}$', password)
strong-password-checker-ii
[Python/Java/C++/C#/JavaScript/PHP] Regex
i-i
6
219
strong password checker ii
2,299
0.567
Easy
31,709
https://leetcode.com/problems/strong-password-checker-ii/discuss/2183796/Python-simple-solution
class Solution: def strongPasswordCheckerII(self, ps: str) -> bool: ln = len(ps) >= 8 lower = False upper = False dig = False spec = False spec_symb = "!@#$%^&*()-+" not_adj = True for i in ps: if i.islower(): lower = True if i.isupper(): upper = True if i.isdigit(): dig = True if i in spec_symb: spec = True for i in range(1, len(ps)): if ps[i] == ps[i-1]: not_adj = False return ln == lower == upper == dig == spec == not_adj
strong-password-checker-ii
Python simple solution
StikS32
1
69
strong password checker ii
2,299
0.567
Easy
31,710
https://leetcode.com/problems/strong-password-checker-ii/discuss/2815364/Python-one-liner
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: return len(password)>=8 \ and any([c.isdigit() for c in password]) \ and any([c.lower()!=c for c in password]) \ and any([c.upper()!=c for c in password]) \ and any([c in "!@#$%^&*()-+" for c in password]) \ and not any([password[i]==password[i+1] for i in range(len(password)-1)])
strong-password-checker-ii
Python one-liner
denfedex
0
2
strong password checker ii
2,299
0.567
Easy
31,711
https://leetcode.com/problems/strong-password-checker-ii/discuss/2783050/Single-Pass-Python-Solution
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: if len(password) < 8: return False lower = upper = digit = special = False prev = "" for char in password: if char == prev: return False if char.islower(): lower = True elif char.isupper(): upper = True elif char.isdigit(): digit = True else: special = True prev = char return lower and upper and digit and special
strong-password-checker-ii
Single Pass Python Solution
kcstar
0
2
strong password checker ii
2,299
0.567
Easy
31,712
https://leetcode.com/problems/strong-password-checker-ii/discuss/2649673/Python3-Use-A-Dict-for-character-types
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: if len(password) >=8: k = 1 else: return False for i in range(1,len(password)): if password[i] == password[i-1]: return False d = defaultdict(lambda: 0) for x in string.ascii_lowercase: d[x]=2 for x in string.ascii_uppercase: d[x]=4 for x in string.digits: d[x]=8 for x in "!@#$%^&amp;*()-+": d[x]=16 for x in password: k |= d[x] return k == 31
strong-password-checker-ii
Python3 Use A Dict for character types
godshiva
0
1
strong password checker ii
2,299
0.567
Easy
31,713
https://leetcode.com/problems/strong-password-checker-ii/discuss/2644047/Python-solution-or-space-O(1)-or-time-O(n)
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: if len(password)<8: return False lower=set('abcdefghijklmnopqrstuvwxyz') upper=set('ABCDEFGHIJKLMNOPQRSTUVWXYZ') digit=set('1234567890') sp_char=set("!@#$%^&amp;*()-+") count_lower=count_upper=count_sp=count_digit=0 for x in range(len(password)): if x>0 and password[x]==password[x-1]: return False if password[x] in upper: count_upper+=1 elif password[x] in lower: count_lower +=1 elif password[x] in digit: count_digit += 1 elif password[x] in sp_char: count_sp += 1 if count_lower>=1 and count_upper>=1 and count_digit>=1 and count_sp>=1: return True return False
strong-password-checker-ii
Python solution | space-O(1) | time-O(n)
I_am_SOURAV
0
12
strong password checker ii
2,299
0.567
Easy
31,714
https://leetcode.com/problems/strong-password-checker-ii/discuss/2147918/Python-Solution-oror-Simple-Approach-oror-June-Contest-2022
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: l="abcdefghijklmnopqrstuvwxyz" u="ABCDEFGHIJKLMNOPQRSTUVWXYZ" d="0123456789" s="!@#$%^&amp;*()-+" sett=set() f=0 for i in range(len(password)): if password[i] in l: sett.add(1) f=1 elif password[i] in u: sett.add(2) f=1 elif password[i] in d: sett.add(3) f=1 elif password[i] in s: sett.add(4) f=1 else: f=0 break for i in range(len(password)-1): if password[i]==password[i+1]: f=0 break if len(password)>=8 and len(sett)==4 and f==1: return True else: return False
strong-password-checker-ii
Python Solution || Simple Approach || June Contest 2022
T1n1_B0x1
0
41
strong password checker ii
2,299
0.567
Easy
31,715
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139950/Python-oror-Easy-Approach
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: l, u, p, d = 0, 0, 0, 0 if (len(password) >= 8): for i in password: # counting lowercase alphabets if (i.islower()): l+=1 # counting uppercase alphabets if (i.isupper()): u+=1 # counting digits if (i.isdigit()): d+=1 # counting the mentioned special characters if(i in "!@#$%^&amp;*()-+"): p+=1 flag = 1 k = 0 while k < len(password): if k + 1 < len(password) and password[k] == password[k + 1]: flag = 0 k += 1 if (l>=1 and u>=1 and p>=1 and d>=1 and flag == 1 and l+p+u+d==len(password)): return True else: return False
strong-password-checker-ii
✅Python || Easy Approach
chuhonghao01
0
12
strong password checker ii
2,299
0.567
Easy
31,716
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139868/python-O(n)
class Solution: def strongPasswordCheckerII(self, password: str) -> bool: if len(password) <= 7: return False lower_case = False upper_case = False digit = False special = False prev = None for char in password: if char in "!@#$%^&amp;*()-+": special = True elif char in string.ascii_lowercase: lower_case = True elif char in string.ascii_uppercase: upper_case = True elif char in string.digits: digit = True if char == prev: return False prev = char if all([lower_case, upper_case, digit, special]): return True else: return False
strong-password-checker-ii
python, O(n)
emersonexus
0
12
strong password checker ii
2,299
0.567
Easy
31,717
https://leetcode.com/problems/strong-password-checker-ii/discuss/2139485/Strong-password-oror-Python-oror-easy-solution
class Solution: def strongPasswordCheckerII(self, S: str) -> bool: if len(S)<8: return False num=0 upper=0 lower=0 spec=0 char="!@#$%^&amp;*()-+" for i in range(len(S)): if i>0 and S[i]==S[i-1]: return False if S[i].isdigit(): num+=1 if S[i].isupper(): upper+=1 if S[i].islower(): lower+=1 if S[i] in char: spec+=1 if num>0 and upper >0 and lower>0 and spec>0 : return True return False
strong-password-checker-ii
Strong password || Python || easy solution
Aniket_liar07
0
23
strong password checker ii
2,299
0.567
Easy
31,718
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139547/Python-3-or-Math-Binary-Search-or-Explanation
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() ans, n = [], len(potions) for spell in spells: val = success // spell if success % spell == 0: idx = bisect.bisect_left(potions, val) else: idx = bisect.bisect_right(potions, val) ans.append(n - idx) return ans
successful-pairs-of-spells-and-potions
Python 3 | Math, Binary Search | Explanation
idontknoooo
2
89
successful pairs of spells and potions
2,300
0.317
Medium
31,719
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2777879/or-Python-or-Binary-Search
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() N = len(potions) return [N - bisect_left(potions, success / x) for x in spells]
successful-pairs-of-spells-and-potions
✔️ | Python | Binary Search
code_alone
0
2
successful pairs of spells and potions
2,300
0.317
Medium
31,720
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2494724/Python-2-liner
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [math.ceil(success/potion) for potion in reversed(sorted(potions)) ] return [bisect_right(potions, spell) for spell in spells]
successful-pairs-of-spells-and-potions
Python 2 liner
mync
0
19
successful pairs of spells and potions
2,300
0.317
Medium
31,721
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2151263/Bisect-library-98-speed
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() len_p = len(potions) return [len_p - bisect_left(potions, ceil(success / s)) for s in spells]
successful-pairs-of-spells-and-potions
Bisect library, 98% speed
EvgenySH
0
25
successful pairs of spells and potions
2,300
0.317
Medium
31,722
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139972/Python-oror-O(nlogn)-oror-Binary-Search-oror-Easy-Approach
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: ans = [] potions.sort(reverse=True) for i in range(len(spells)): l, r = 0, len(potions) - 1 while l <= r: p = (l + r) // 2 if potions[p] * spells[i] >= success: l = p + 1 else: r = p - 1 if potions[p] * spells[i] >= success: ans.append(p + 1) else: ans.append(p) return ans
successful-pairs-of-spells-and-potions
✅Python || O(nlogn) || Binary Search || Easy Approach
chuhonghao01
0
9
successful pairs of spells and potions
2,300
0.317
Medium
31,723
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139931/Python3-binary-search
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: result = [] potions.sort() for i, spell in enumerate(spells): target = math.ceil(success / spell) cnt = bisect.bisect_left(potions, target) if cnt != -1: result.append(len(potions) - cnt) else: result.append(0) return result
successful-pairs-of-spells-and-potions
Python3 binary search
emersonexus
0
11
successful pairs of spells and potions
2,300
0.317
Medium
31,724
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139488/Python-or-Sort-and-Binary-Search
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: total = [] potions.sort() n = len(potions) for num in spells: total.append(n - bisect.bisect_left(potions, success/num)) return total
successful-pairs-of-spells-and-potions
Python | Sort and Binary Search
rbhandu
0
13
successful pairs of spells and potions
2,300
0.317
Medium
31,725
https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139400/python-3-oror-simple-binary-search
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() m = len(potions) return [m - bisect.bisect_left(potions, math.ceil(success / spell)) for spell in spells]
successful-pairs-of-spells-and-potions
python 3 || simple binary search
dereky4
0
17
successful pairs of spells and potions
2,300
0.317
Medium
31,726
https://leetcode.com/problems/match-substring-after-replacement/discuss/2140652/Python-Precalculation-O(n*k)-without-TLE
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: s_maps = defaultdict(lambda : set()) for x,y in mappings: s_maps[x].add(y) # build a sequence of set for substring match # eg: sub=leet, mappings = {e: 3, t:7} # subs = [{l}, {e, 3}, {e, 3}, {t, 7}] # precalculation helps to eliminate TLE subs = [s_maps[c] | {c} for c in sub] for i in range(len(s)-len(sub) + 1): c=s[i] j=i # Try to match substring while j-i<len(sub) and s[j] in subs[j-i]: j+=1 if j-i==len(sub): # a valid match if iterated through the whole length of substring return True return False
match-substring-after-replacement
✅ Python Precalculation O(n*k) without TLE
constantine786
7
181
match substring after replacement
2,301
0.393
Hard
31,727
https://leetcode.com/problems/match-substring-after-replacement/discuss/2142973/Python3-Easy-to-understand-Solution-using-Dictionary-and-HashSet
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: dic = {} for m in mappings: if m[0] not in dic: dic[m[0]] = {m[1]} else: dic[m[0]].add(m[1]) for i in range(len(s)-len(sub)+1): j = 0 while j < len(sub) and (s[i+j] == sub[j] or (sub[j] in dic and s[i+j] in dic[sub[j]])): j += 1 if j == len(sub): return True return False # Time: O(len(s) * len(sub)) # Space: O(len(mapping))
match-substring-after-replacement
[Python3] Easy to understand Solution using Dictionary and HashSet
samirpaul1
3
90
match substring after replacement
2,301
0.393
Hard
31,728
https://leetcode.com/problems/match-substring-after-replacement/discuss/2369542/faster-than-84.22-or-Simple-python-or-solution
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: if len(s) < len(sub): return False maps = defaultdict(set) for u, v in mappings: maps[u].add(v) def f(s1): for c1, c2 in zip(s1, sub): if c1 != c2 and c1 not in maps[c2]: return False return True for i in range(len(s) - len(sub) + 1): if f(s[i:i+len(sub)]): return True return False
match-substring-after-replacement
faster than 84.22% | Simple python | solution
vimla_kushwaha
1
59
match substring after replacement
2,301
0.393
Hard
31,729
https://leetcode.com/problems/match-substring-after-replacement/discuss/2147817/python3-Iteration-solution-for-refrence.
class Solution: def iteration(self, s, sub, mappings): h = defaultdict(int) # put mappings in hashmap data structure. for k, v in mappings: if k not in h: h[k] = {v: 1} else: h[k][v] = 1 siter = 0 subiter = 0 jump = -1 # Iterate through the string 's' and locate jump points as we go. while siter < len(s): # two chars are equal if they are same in both strings or mapping / replacement equates them if s[siter] == sub[subiter] or (sub[subiter] in h and s[siter] in h[sub[subiter]]): # keep track of jump location of next string if we encounter a start char while in the middle of an evaluation. # abbabbc would have two 'a' chars to start evaluating substring 'abbc' jump = siter if (s[siter] == sub[0] and subiter > 0) else -1 subiter += 1 if subiter == len(sub): return True else: # relocate the jump point to previously encoutered start character. siter = (jump-1) if jump != -1 else siter if s[siter] == sub[0] and jump == -1: siter -= 1 subiter = 0 jump = -1 siter += 1 return False def dp(self, s, sub, mappings): h = defaultdict(dict) S = len(s) SU = len(sub) for k, v in mappings: if k not in h: h[k] = {v: 1} else: h[k][v] = 1 dp = [[0 for _ in range(S)] for _ in range(SU)] for subiter in range(SU): for siter in range(S): if sub[subiter] == s[siter]: dp[subiter][siter] = dp[subiter-1][siter-1] + 1 elif dp[subiter-1][siter-1]: if (sub[subiter] in h and s[siter] in h[sub[subiter]]): dp[subiter][siter] = dp[subiter-1][siter-1] + 1 if dp[subiter][siter] == len(sub): for d in dp: print ("".join([str(i) for i in d])) return True return False def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: return self.iteration(s, sub, mappings)
match-substring-after-replacement
[python3] Iteration solution for refrence.
vadhri_venkat
0
11
match substring after replacement
2,301
0.393
Hard
31,730
https://leetcode.com/problems/match-substring-after-replacement/discuss/2140362/Python3-or-Short-Easy-Understanding-or-Examples-with-Explaination-or-Sliding-Window-%2B-Brute-Force
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: dic=defaultdict(set) for k,v in mappings: dic[k].add(v) # dic{'t':set{'l','3'}, 'e':set{'4'}} as an example def check(toCheck,sub): # Here len(toCheck) = len(sub) for char_check, char_sub in zip(toCheck, sub): if char_check != char_sub and char_check not in dic[char_sub]: return False return True for start in range(len(s)-len(sub)+1): if check(s[start:start+len(sub)],sub): # check sliding window with length of sub return True return False
match-substring-after-replacement
Python3 | Short Easy Understanding | Examples with Explaination | Sliding Window + Brute Force
yzhao156
0
29
match substring after replacement
2,301
0.393
Hard
31,731
https://leetcode.com/problems/match-substring-after-replacement/discuss/2140141/Python-3KMP-Algorithm
class Solution: def matchReplacement(self, s: str, p: str, mappings: List[List[str]]) -> bool: m = defaultdict(set) for a, b in mappings: m[a].add(b) # build pattern array i, j = 0, 1 arr = [0] * len(p) while j < len(p): if p[i] == p[j]: arr[j] = arr[j-1] + 1 i += 1 j += 1 else: # no need to go to beginning of pattern (only need to go to previous arr index) while i > 0 and p[j] != p[i]: i = arr[i-1] if p[i] == p[j]: arr[j] = arr[i] + 1 j += 1 i = j = 0 while i < len(s): if s[i] == p[j] or s[i] in m[p[j]]: i += 1 j += 1 if j == len(p): return True else: # find previous latest index as long as two characters matched or convertible origin_j = j while j > 0 and not (s[i] == p[j] or s[i] in m[p[j]]): j = arr[j - 1] i = i - (origin_j - j) + 1 # if s[i] != p[j]: # i += 1 return False
match-substring-after-replacement
[Python 3]KMP Algorithm
chestnut890123
0
74
match substring after replacement
2,301
0.393
Hard
31,732
https://leetcode.com/problems/match-substring-after-replacement/discuss/2138927/HashMap-or-Greedy-Approach-in-Python-or-O(N*K)
class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: # maintain a map to know which letters can be changed d = defaultdict(set) for i,j in mappings: d[i].add(j) k = len(sub) # iterate over all possibilities of size len(sub) for i in range(len(s)-k+1): st = s[i:i+k] fl = 0 # iterate greedily and try if we can replace cur character or not if not we break for j in range(k): if sub[j] != st[j]: if st[j] not in d[sub[j]]: fl = 1 break if fl ==0: return True return False
match-substring-after-replacement
HashMap | Greedy Approach in Python | O(N*K)
hash1023
0
12
match substring after replacement
2,301
0.393
Hard
31,733
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2138778/Sliding-Window
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: sum, res, j = 0, 0, 0 for i, n in enumerate(nums): sum += n while sum * (i - j + 1) >= k: sum -= nums[j] j += 1 res += i - j + 1 return res
count-subarrays-with-score-less-than-k
Sliding Window
votrubac
126
4,700
count subarrays with score less than k
2,302
0.522
Hard
31,734
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2140147/Python-3-or-Sliding-Window-Two-Pointers-Math-or-Explanation
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: nums += [k] slow = cur = ans = 0 for i, num in enumerate(nums): cur += num while cur * (i - slow + 1) >= k: ans += i - slow cur -= nums[slow] slow += 1 return ans
count-subarrays-with-score-less-than-k
Python 3 | Sliding Window, Two Pointers, Math | Explanation
idontknoooo
1
67
count subarrays with score less than k
2,302
0.522
Hard
31,735
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2769948/Python-or-Sliding-Window
class Solution: def countSubarrays(self, xs: List[int], k: int) -> int: n = len(xs) i, j, sub_sum = 0, 0, 0 ans = 0 while j < n: sub_sum += xs[j] if sub_sum * (j - i + 1) < k: ans += j - i + 1 j += 1 elif i == j: sub_sum = 0 j += 1 i = j else: sub_sum -= xs[i] + xs[j] i += 1 return ans
count-subarrays-with-score-less-than-k
Python | Sliding Window
on_danse_encore_on_rit_encore
0
3
count subarrays with score less than k
2,302
0.522
Hard
31,736
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2520338/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: i, start = 0, 0 n = len(nums) val, ans, sums = 1, 0, 0 while i < n: sums += nums[i] val = sums * (i-start+1) while start <= i and val >= k: sums -= nums[start] start += 1 val = sums * (i-start+1) ans += (i-start+1) i += 1 return ans
count-subarrays-with-score-less-than-k
Python easy to read and understand | sliding-window
sanial2001
0
32
count subarrays with score less than k
2,302
0.522
Hard
31,737
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2170246/python3-sliding-window-sol-for-ref.
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: start = 0 end = 0 N = len(nums) rolling_sum = 0 ans = 0 for idx, value in enumerate(nums): rolling_sum += value window_size = end-start while start < end and rolling_sum * (end-start+1) >= k: rolling_sum -= nums[start] start += 1 window_size -= 1 window_size = end-start if rolling_sum * (window_size+1) < k: ans += window_size if window_size >= 0 else 0 # add single self array if value < k: ans += 1 end += 1 return ans
count-subarrays-with-score-less-than-k
[python3] sliding window sol for ref.
vadhri_venkat
0
39
count subarrays with score less than k
2,302
0.522
Hard
31,738
https://leetcode.com/problems/count-subarrays-with-score-less-than-k/discuss/2139551/python-3-oror-simple-sliding-window-solution-oror-O(n)O(1)
class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: res = 0 left = 0 windowSum = 0 for right, num in enumerate(nums): windowSum += num windowLength = right - left + 1 while windowSum * windowLength >= k: windowSum -= nums[left] left += 1 windowLength -= 1 res += windowLength return res
count-subarrays-with-score-less-than-k
python 3 || simple sliding window solution || O(n)/O(1)
dereky4
0
20
count subarrays with score less than k
2,302
0.522
Hard
31,739
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141187/Python3-bracket-by-bracket
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = prev = 0 for hi, pct in brackets: hi = min(hi, income) ans += (hi - prev)*pct/100 prev = hi return ans
calculate-amount-paid-in-taxes
[Python3] bracket by bracket
ye15
14
535
calculate amount paid in taxes
2,303
0.634
Easy
31,740
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2140940/Simple-Python-Solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: brackets.sort(key=lambda x: x[0]) res = 0 # Total Tax prev = 0 # Prev Bracket Upperbound for u, p in brackets: if income >= u: # res += ((u-prev) * p) / 100 prev = u else: res += ((income-prev) * p) / 100 break # As total income has been taxed at this point. return res
calculate-amount-paid-in-taxes
Simple Python Solution
anCoderr
2
95
calculate amount paid in taxes
2,303
0.634
Easy
31,741
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2166711/Python3-solution-or-Easy-to-understand-or-concise-and-simple-code-or
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: lower = 0; tax = 0; left = income # amount left to be taxed for i in brackets: k = i[0]-lower # amount being taxed if k<= left: tax+=k*i[1]/100; left-=k; lower=i[0] else: tax+= left*i[1]/100 break return tax
calculate-amount-paid-in-taxes
Python3 solution | Easy to understand | concise and simple code |
rogan35
1
58
calculate amount paid in taxes
2,303
0.634
Easy
31,742
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2150061/Python-oror-Simple-6-Liner
class Solution: def calculateTax(self, l: List[List[int]], k: int) -> float: prev=sol=0 for x,y in l: t, prev = min(x,k)-prev, x if t<0:break sol+=t*y/100 return sol
calculate-amount-paid-in-taxes
Python || Simple 6-Liner
subin_nair
1
39
calculate amount paid in taxes
2,303
0.634
Easy
31,743
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2843675/Python-easy-solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: total_tax = 0 prev = 0 for i in range(len(brackets)): if income > brackets[i][0]: total_tax += (brackets[i][0] - prev) * brackets[i][1] prev = brackets[i][0] else: total_tax += (income - prev) * brackets[i][1] break return total_tax/100
calculate-amount-paid-in-taxes
Python easy solution
chacha_chaudhary
0
1
calculate amount paid in taxes
2,303
0.634
Easy
31,744
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2738499/Python3-Commented-Solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: # we will iterate through the tax brackets as long as there is income # left taxes = 0 prev = 0 for upper, percent in brackets: # check which dollars are in this tax bracket dollars = upper - prev # check whether the amount of dollars in the bracket is bigger # than the income if dollars < income: # tax the bracket taxes += dollars*(percent/100) # subtract this upper from the income income -= dollars else: # tax the leftover income taxes += income * (percent/100) break # set the prev prev = upper return taxes
calculate-amount-paid-in-taxes
[Python3] - Commented Solution
Lucew
0
8
calculate amount paid in taxes
2,303
0.634
Easy
31,745
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2708448/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: tax = 0 inc = income prev = 0 for i in brackets: if income > i[0] and income>0: tax+= ((i[0]-prev)*(i[1]/100)) prev = i[0] income -= abs(i[0]-prev) else: tax+= ((inc-prev)*(i[1]/100)) return tax return tax
calculate-amount-paid-in-taxes
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
6
calculate amount paid in taxes
2,303
0.634
Easy
31,746
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2586797/Python-O(n)-Easy-and-concise
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: brackets = [[0, 0]] + brackets # add [0, 0] as first element to make things easier total = 0 for i in range(1, len(brackets)): # calculate the difference between two consecutive uppers # and just get the minimum between the income and the diff so that you are not overtaxed diff = min(income, brackets[i][0] - brackets[i - 1][0]) # calculate the taxes total += diff * (brackets[i][1] / 100) # Update the income so that always is bigger or equal to 0 income = max(income - diff, 0) return total
calculate-amount-paid-in-taxes
Python O(n) Easy & concise
asbefu
0
44
calculate amount paid in taxes
2,303
0.634
Easy
31,747
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2367842/Python3-cumulative-brackets-easy
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: tax=0 last=0 for i,val in enumerate(brackets): bracket=val[0]-last tax+= min(income,bracket)*val[1] if income <=bracket: return tax/100 income-=bracket last=val[0] return tax/100
calculate-amount-paid-in-taxes
[Python3] cumulative brackets - easy
sunakshi132
0
29
calculate amount paid in taxes
2,303
0.634
Easy
31,748
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2329059/Python-easy-to-understand
class Solution: def calculateTax(self, b: List[List[int]], income: int) -> float: if income <= b[0][0]: return income * (b[0][1] / 100) res = b[0][0] * (b[0][1] / 100) for i in range(1, len(b)): print(res) if income <= b[i][0]: res += (income - b[i-1][0]) * (b[i][1] / 100) break else: res += (b[i][0]-b[i-1][0]) * (b[i][1] / 100) return res
calculate-amount-paid-in-taxes
Python easy to understand
scr112
0
43
calculate amount paid in taxes
2,303
0.634
Easy
31,749
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2184650/Python3-simple-solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = 0 c = 0 for i in range(len(brackets)): if income <= 0: break if income >= brackets[i][0]-c: ans += round(((brackets[i][0] - c) * brackets[i][1])/100,5) else: ans += round((income * brackets[i][1])/100,5) income -= (brackets[i][0]-c) c = brackets[i][0] return ans
calculate-amount-paid-in-taxes
Python3 simple solution
EklavyaJoshi
0
30
calculate amount paid in taxes
2,303
0.634
Easy
31,750
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2151359/Python-Solution-with-explanation
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: """ Time Complexity: O(n) Space Complexity: O(n) """ tax = 0 pre_upper = 0 for tax_bracket in brackets: upper = tax_bracket[0] percent = tax_bracket[1] split_income = upper - pre_upper if income >= upper else income - pre_upper tax += split_income * percent * 0.01 if income < upper: break pre_upper = upper return tax
calculate-amount-paid-in-taxes
Python Solution with explanation
Zewei_Liu
0
33
calculate amount paid in taxes
2,303
0.634
Easy
31,751
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2146243/Python3-Very-short-and-clean
class Solution: def calculateTax(self, brackets: list[list[int]], income: int) -> float: cur, res = 0, 0 for upper, percent in brackets: pre, cur = cur, min(upper, income) res += (cur - pre) * percent return res / 100
calculate-amount-paid-in-taxes
[Python3] Very short and clean
miguel_v
0
30
calculate amount paid in taxes
2,303
0.634
Easy
31,752
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2143867/One-pass
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: taxes = taxed_amount = prev_upper = 0 for upper_i, percent_i in brackets: amount = min(income - taxed_amount, upper_i - prev_upper) taxes += amount * percent_i / 100 taxed_amount += amount prev_upper = upper_i if taxed_amount == income: break return taxes
calculate-amount-paid-in-taxes
One pass
EvgenySH
0
14
calculate amount paid in taxes
2,303
0.634
Easy
31,753
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2142602/Python-Simple-Python-Solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: result = 0 previous = 0 for i in brackets: upper, percent = i new_upper= min(upper,income) if new_upper - previous<0: return result result = result + (( new_upper - previous) * percent / 100) previous = upper return result
calculate-amount-paid-in-taxes
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
113
calculate amount paid in taxes
2,303
0.634
Easy
31,754
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2142602/Python-Simple-Python-Solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: if income == 0 : return 0 result = 0 upper, percent = brackets[0] previous = upper if upper <= income: result = result + ( upper * percent )/ 100 else: return ( income * percent ) / 100 for i in brackets[1:]: new_upper, percent = i if new_upper <= income: result = result + (( new_upper - previous) * percent )/ 100 else: result = result + (( income - previous) * percent ) / 100 break previous = new_upper return result
calculate-amount-paid-in-taxes
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
113
calculate amount paid in taxes
2,303
0.634
Easy
31,755
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141825/java-python-easy-to-understand
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: i, summ, rest = 0, 0, 0 while i != len(brackets) : brackets[i][0], rest = brackets[i][0] - rest, brackets[i][0] if income > brackets[i][0] : summ += brackets[i][0] * brackets[i][1] income -= brackets[i][0] i += 1 else : if income != 0 : summ += income * brackets[i][1] break return summ / 100
calculate-amount-paid-in-taxes
java, python - easy to understand
ZX007java
0
12
calculate amount paid in taxes
2,303
0.634
Easy
31,756
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141720/Python-solution-with-explanation-or-Time-O(n)-or-Space-O(1)
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: result, sumValue = 0, 0 for value in brackets : if income >= value[ 0 ] : result += float( ( value[ 0 ] - sumValue ) * ( value[ 1 ] / 100 ) ) #important step sumValue = value[ 0 ] else : result += float( ( income - sumValue ) * ( value[ 1 ] / 100 ) ) break return result
calculate-amount-paid-in-taxes
Python solution with explanation | Time O(n) | Space O(1)
athrvb
0
13
calculate amount paid in taxes
2,303
0.634
Easy
31,757
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141427/Python-simple-solution
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: amount_tax = 0.0 total_tax = 0.0 money_left = income prev_bracket = 0.0 for upper, percent in brackets: if money_left > (upper - prev_bracket): amount_to_tax = upper - prev_bracket money_left = money_left - amount_to_tax else: amount_to_tax = money_left money_left = 0 # Nothing left to tax if amount_to_tax == 0: break total_tax += amount_to_tax * percent / 100.0 prev_bracket = upper return total_tax
calculate-amount-paid-in-taxes
[Python] 😎🍁😎🍁😎🍁 simple solution
LivesByTheOcean
0
11
calculate amount paid in taxes
2,303
0.634
Easy
31,758
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141089/Python-Simple-Solution-or-O(N)-or-Simple-maths
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: c=0 if brackets[0][0]>=income: return (brackets[0][1]*income*1.0)/100 else: c+=(brackets[0][0]*brackets[0][1]*1.0)/100 income-=brackets[0][0] i = 1 while i<len(brackets) and income>0: x = brackets[i][0]-brackets[i-1][0] if x>=income: c+=(brackets[i][1]*income*1.0)/100 income=0 else: c+=(brackets[i][1]*x*1.0)/100 income-=x i+=1 return c
calculate-amount-paid-in-taxes
Python Simple Solution | O(N) | Simple maths
AkashHooda
0
17
calculate amount paid in taxes
2,303
0.634
Easy
31,759
https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2140994/Python-oror-Easy-Approach
class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = 0 n = len(brackets) if income <= brackets[0][0]: return income * brackets[0][1] * 0.01 # brackets[k - 1] < income < brackets[k] k = 0 for i in range(n): if income > brackets[i][0]: k += 1 j = 1 ans += brackets[0][0] * brackets[0][1] * 0.01 while j < k: ans += (brackets[j][0] - brackets[j - 1][0]) * brackets[j][1] * 0.01 j += 1 ans += (income - brackets[j - 1][0]) * brackets[j][1] * 0.01 return ans
calculate-amount-paid-in-taxes
✅Python || Easy Approach
chuhonghao01
0
20
calculate amount paid in taxes
2,303
0.634
Easy
31,760
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141004/Python-Recursion-%2B-Memoization
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_row, max_col = len(grid), len(grid[0]) dp = [[-1] * max_col for _ in range(max_row)] def recursion(row, col): if row == max_row - 1: # If last row then return nodes value return grid[row][col] if dp[row][col] == -1: # If DP for this node is not computed then we will do so now. current = grid[row][col] # Current Node Value res = float('inf') # To store best path from Current Node for c in range(max_col): # Traverse all path from Current Node val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value res = min(res, val) dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val return dp[row][col] for c in range(max_col): recursion(0, c) # Start recursion from all nodes in 1st row return min(dp[0]) # Return min value from 1st row
minimum-path-cost-in-a-grid
Python Recursion + Memoization
anCoderr
13
501
minimum path cost in a grid
2,304
0.656
Medium
31,761
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2140985/Python-or-Memoization
class Solution: def minPathCost(self, grid: list[list[int]], moveCost: list[list[int]]) -> int: @lru_cache() def helper(i, j): if i >= len(grid) - 1: return grid[i][j] m_cost = 9999999999 cost = 0 for k in range(len(grid[0])): cost = grid[i][j] + moveCost[grid[i][j]][k] + helper(i + 1, k) m_cost = min(cost, m_cost) return m_cost cost, min_cost = 0, 999999999999 n = len(grid[0]) for j in range(n): cost = helper(0, j) min_cost = min(cost, min_cost) return min_cost
minimum-path-cost-in-a-grid
Python | Memoization
GigaMoksh
10
1,000
minimum path cost in a grid
2,304
0.656
Medium
31,762
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2140985/Python-or-Memoization
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @lru_cache() def helper(i, j): if i == 0: return grid[i][j] else: return grid[i][j] + min(moveCost[grid[i - 1][k]][j] + helper(i - 1, k) for k in range(n)) return min(helper(m - 1, j) for j in range(n))
minimum-path-cost-in-a-grid
Python | Memoization
GigaMoksh
10
1,000
minimum path cost in a grid
2,304
0.656
Medium
31,763
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141191/Python3-top-down-dp
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) @cache def fn(i, j): """Return min cost of moving from (i, j) to bottom row.""" if i == m-1: return grid[i][j] ans = inf for jj in range(n): ans = min(ans, grid[i][j] + fn(i+1, jj) + moveCost[grid[i][j]][jj]) return ans return min(fn(0, j) for j in range(n))
minimum-path-cost-in-a-grid
[Python3] top-down dp
ye15
4
251
minimum path cost in a grid
2,304
0.656
Medium
31,764
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141059/Python-or-DFS-%2B-Memoization
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: floor = len(grid) - 1 memo = {} def dfs(node, level): key = (node, level) if key in memo: return memo[key] if level == floor: return node min_path = float('inf') for i, next_node in enumerate(grid[level + 1]): path = dfs(next_node, level + 1) + moveCost[node][i] min_path = min(min_path, path) memo[key] = min_path + node return memo[key] result = float('inf') for node in grid[0]: result = min(result, dfs(node, 0)) return result
minimum-path-cost-in-a-grid
Python | DFS + Memoization
JustKievn
2
38
minimum path cost in a grid
2,304
0.656
Medium
31,765
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2849630/DP
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dummy = [[0]*n for _ in range(m)] dummy[0] = grid[0] for i in range(1,m): for j in range(n): min_cost = math.inf for k in range(n): if min_cost > dummy[i-1][k] + grid[i][j] + moveCost[grid[i-1][k]][j]: dummy[i][j] = dummy[i-1][k] + grid[i][j] + moveCost[grid[i-1][k]][j] min_cost = dummy[i-1][k] + grid[i][j] + moveCost[grid[i-1][k]][j] return(min(dummy[m-1]))
minimum-path-cost-in-a-grid
DP
amanjhurani5
0
1
minimum path cost in a grid
2,304
0.656
Medium
31,766
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2849437/Python-DP-based-solution
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dp = [[float("inf") for _ in range(n)] for _ in range(m)] <!-- only way to reach row 0 is from itself --> for i in range(n): dp[0][i] = grid[0][i] for i in range(1, m): for j in range(n): for k in range(n): <!-- dp[i-1][k] is the cost to reach the prev cell--> <!-- moveCost[grid[i-1][k]][j] is the cost to reach the cell from the diagonal/straight cell in prev row --> <!-- grid[i][j] is the cost of the cell visited --> dp[i][j] = min(dp[i][j], dp[i-1][k]+moveCost[grid[i-1][k]][j]+grid[i][j]) return int(min(dp[m-1]))
minimum-path-cost-in-a-grid
Python DP based solution
pranav_hq
0
1
minimum path cost in a grid
2,304
0.656
Medium
31,767
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2848964/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def solve(self, grid, move, row, col): m, n = len(grid), len(grid[0]) if row == m-1: return grid[row][col] if (row, col) in self.d: return self.d[(row, col)] self.d[(row, col)] = float("inf") for j in range(n): temp = self.solve(grid, move, row+1, j) + move[grid[row][col]][j] + grid[row][col] self.d[(row, col)] = min(self.d[(row, col)], temp) return self.d[(row, col)] def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) self.d = {} res = float("inf") for j in range(n): res = min(res, self.solve(grid, moveCost, 0, j)) return res
minimum-path-cost-in-a-grid
Python easy to read and understand | recursion + memoization
sanial2001
0
1
minimum path cost in a grid
2,304
0.656
Medium
31,768
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2153833/python-dp-solution
class Solution(object): def minPathCost(self, grid, moveCost): """ :type grid: List[List[int]] :type moveCost: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) res = copy.deepcopy(grid) for i in range(1, m): for j in range(n): res[i][j] += min([res[i - 1][k] + moveCost[grid[i - 1][k]][j] for k in range(n)]) return min(res[-1])
minimum-path-cost-in-a-grid
python dp solution
Kennyyhhu
0
34
minimum path cost in a grid
2,304
0.656
Medium
31,769
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2146195/java-python-simple-easy-fast
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: idx = grid[0] for i in range (1, len(grid)): add =[1000000000]*len(grid[0]) for j in range (0, len(grid[0])): for k in range (0, len(grid[0])): add[k] = min(add[k], grid[i-1][j] + moveCost[idx[j]][k]) for j in range (0, len(grid[0])): idx[j] = grid[i][j] grid[i][j] += add[j] return min(grid[-1])
minimum-path-cost-in-a-grid
java, python - simple, easy, fast
ZX007java
0
26
minimum path cost in a grid
2,304
0.656
Medium
31,770
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2144985/Python-Dynamic-Programming
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[0 for _ in range(n)] for _ in range(m)] for j in range(n): dp[0][j] = grid[0][j] for i in range(1, m): for j in range(n): dp[i][j] = min(dp[i-1][y] + grid[i][j] + moveCost[grid[i-1][y]][j] for y in range(n)) return min(dp[-1])
minimum-path-cost-in-a-grid
Python Dynamic Programming
lukefall425
0
23
minimum path cost in a grid
2,304
0.656
Medium
31,771
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2144293/Python-simple-breadth-first-search-with-sensible-use-of-visited-or-alternate-soln%3A-Dijkstra'ish
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: q = deque() m, n = len(grid), len(grid[0]) visited = [[math.inf]*n for d in range(m)] mincost = math.inf for j in range(n): q.append((0, j, grid[0][j])) visited[0][j] = grid[0][j] while q: i, j, cost = q.popleft() val = grid[i][j] if cost > visited[i][j]: continue if i == m - 1: mincost = min(mincost, cost) else: for newj in range(n): newcost = cost + moveCost[val][newj] + grid[i+1][newj] if newcost < visited[i+1][newj]: visited[i+1][newj] = newcost q.append((i+1, newj, newcost)) return mincost
minimum-path-cost-in-a-grid
[Python] simple breadth first search with sensible use of visited | alternate soln: Dijkstra'ish
megZo
0
21
minimum path cost in a grid
2,304
0.656
Medium
31,772
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2144293/Python-simple-breadth-first-search-with-sensible-use-of-visited-or-alternate-soln%3A-Dijkstra'ish
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: q = [] m, n = len(grid), len(grid[0]) visited = [[math.inf]*n for d in range(m)] mincost = math.inf for j in range(n): heappush(q, (0, j, grid[0][j])) visited[0][j] = grid[0][j] while q: i, j, cost = heappop(q) val = grid[i][j] if cost > visited[i][j]: continue if i == m - 1: mincost = min(mincost, cost) else: for newj in range(n): newcost = cost + moveCost[val][newj] + grid[i+1][newj] if newcost < visited[i+1][newj]: visited[i+1][newj] = newcost heappush(q, (i+1, newj, newcost)) return mincost
minimum-path-cost-in-a-grid
[Python] simple breadth first search with sensible use of visited | alternate soln: Dijkstra'ish
megZo
0
21
minimum path cost in a grid
2,304
0.656
Medium
31,773
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2143619/Python-or-Tabulation-or-Bottom-up-DP
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: dp = [[[float('inf'),float('inf')] for _ in range(len(grid[0]))] for _ in range(len(grid))] lmin = float('inf') for i in range(len(grid)): for j in range(len(grid[0])): dp[i][j][0] = grid[i][j] if i > 0: for k in range(len(grid[0])): dp[i][j][1] = min(dp[i][j][1], dp[i-1][k][0] + moveCost[grid[i-1][k]][j]) dp[i][j][0] += dp[i][j][1] if i == len(grid) - 1: lmin = min(lmin, dp[i][j][0]) return lmin
minimum-path-cost-in-a-grid
Python | Tabulation | Bottom-up DP
davidseungjin
0
16
minimum path cost in a grid
2,304
0.656
Medium
31,774
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2142001/Weekly-Contest-or-Python-or-Easy-understanding
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: max_int = 100000000 dp = [[0] * 100 for i in range(100)] rows, cols = len(grid), len(grid[0]) for r in range(rows): for c in range(cols): if r == 0: dp[r][c] = grid[r][c] else: dp[r][c] = max_int for k in range(cols): dp[r][c] = min(dp[r][c], dp[r - 1][k] + grid[r][c] + moveCost[grid[r-1][k]][c]) res = max_int for i in range(cols): res = min(res, dp[rows - 1][i]) return res
minimum-path-cost-in-a-grid
Weekly Contest | Python | Easy-understanding
JavanMyna
0
6
minimum path cost in a grid
2,304
0.656
Medium
31,775
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141174/python-or-memoization
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: def DFS(n,m,i,j): if i == n - 1: return grid[i][j] if (i,j) in dp: return dp[i,j] ans = float('inf') for k in range(m): ele = grid[i][j] curr = ele + moveCost[ele][k] + DFS(n,m,i+1,k) ans = min(ans,curr) dp[i,j] = ans return dp[i,j] n,m = len(grid),len(grid[0]) output = float("inf") dp = {} for c in range(m): currCost = DFS(n,m,0,c) output = min(output,currCost) return output
minimum-path-cost-in-a-grid
python | memoization
Jashwanthk
0
9
minimum path cost in a grid
2,304
0.656
Medium
31,776
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141061/Python-DP-solution-or-Optimized-Solution-(memoization)
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: l = [[0]*(len(grid[0])) for i in range(len(grid))] l[0] = grid[0] for i in range(1,len(grid)): for j in range(len(grid[0])): m = float('inf') for k in range(len(grid[0])): m = min(m,l[i-1][k] + moveCost[grid[i-1][k]][j]) l[i][j] = m + grid[i][j] return min(l[-1])
minimum-path-cost-in-a-grid
Python DP solution | Optimized Solution (memoization)
AkashHooda
0
22
minimum path cost in a grid
2,304
0.656
Medium
31,777
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141012/Python-or-Bottom-up-DP
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[float('inf') for _ in range(n)] for _ in range(m)] dp [-1] = grid[-1] for i in reversed(range(m-1)): for j in reversed(range(n)): for k in range(n): dp[i][j] = min(dp[i][j], grid[i][j] + moveCost[grid[i][j]][k] + dp[i+1][k]) return min(dp[0])
minimum-path-cost-in-a-grid
Python | Bottom up DP
rbhandu
0
28
minimum path cost in a grid
2,304
0.656
Medium
31,778
https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2140979/Python-or-DP
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dic = defaultdict(list) lastRow = set(grid[-1]) for i in range(m*n): for j in range(n): if i in lastRow: continue else: # (cost, dest_col) dic[i].append((moveCost[i][j], j)) dp = [[float('inf')] * n for _ in range(m)] for i in range(n): dp[0][i] = grid[0][i] for i in range(m-1): for j in range(n): start = grid[i][j] for cost, dest_col in dic[start]: dp[i + 1][dest_col] = min(dp[i + 1][dest_col], dp[i][j] + cost + grid[i + 1][dest_col]) return min(dp[-1])
minimum-path-cost-in-a-grid
Python | DP
Mikey98
0
34
minimum path cost in a grid
2,304
0.656
Medium
31,779
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141013/Python-optimized-solution-or-Backtracking-Implemented-or-O(KN)-Time-Complexity
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: l = [0]*k self.s = float('inf') def ser(l,i): if i>=len(cookies): self.s = min(self.s,max(l)) return if max(l)>=self.s: return for j in range(k): l[j]+=cookies[i] ser(l,i+1) l[j]-=cookies[i] ser(l,0) return self.s
fair-distribution-of-cookies
Python optimized solution | Backtracking Implemented | O(K^N) Time Complexity
AkashHooda
5
852
fair distribution of cookies
2,305
0.626
Medium
31,780
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141241/Python-or-Backtrack-or-Easy-to-Understand
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: result = float('inf') children = [0] * k def backtrack(index): nonlocal result, children if index == len(cookies): result = min(result, max(children)) return # key point to pass the TLE! if result <= max(children): return for i in range(k): children[i] += cookies[index] backtrack(index + 1) children[i] -= cookies[index] backtrack(0) return result
fair-distribution-of-cookies
Python | Backtrack | Easy to Understand
Mikey98
2
156
fair distribution of cookies
2,305
0.626
Medium
31,781
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141196/Python3-bitmask-dp
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: n = len(cookies) @cache def fn(mask, k): """Return min unfairness of distributing cookies marked by mask to k children.""" if mask == 0: return 0 if k == 0: return inf ans = inf orig = mask while mask: mask = orig &amp; (mask - 1) amt = sum(cookies[i] for i in range(n) if (orig ^ mask) &amp; 1<<i) ans = min(ans, max(amt, fn(mask, k-1))) return ans return fn((1<<n)-1, k)
fair-distribution-of-cookies
[Python3] bitmask dp
ye15
2
189
fair distribution of cookies
2,305
0.626
Medium
31,782
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2147138/Python3-or-BackTracking
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: bag=[0]*k self.ans=float('inf') self.helper(cookies,bag,0,k) return self.ans def helper(self,cookies,bag,start,k): if max(bag)>self.ans: return if start>=len(cookies): temp=max(bag) self.ans=min(self.ans,temp) return for j in range(k): bag[j]+=cookies[start] self.helper(cookies,bag,start+1,k) bag[j]-=cookies[start] return
fair-distribution-of-cookies
[Python3] | BackTracking
swapnilsingh421
1
71
fair distribution of cookies
2,305
0.626
Medium
31,783
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2851291/Python-(Simple-Backtracking)
class Solution: def distributeCookies(self, cookies, k): if k == len(cookies): return max(cookies) self.min_val = float("inf") def backtrack(idx,ans): if idx == len(cookies): self.min_val = min(self.min_val,max(ans)) return seen = set() for i in range(k): if ans[i] in seen: continue if ans[i] + cookies[idx] >= self.min_val: continue seen.add(ans[i]) ans[i] += cookies[idx] backtrack(idx+1,ans) ans[i] -= cookies[idx] backtrack(0, [0]*k) return self.min_val
fair-distribution-of-cookies
Python (Simple Backtracking)
rnotappl
0
1
fair distribution of cookies
2,305
0.626
Medium
31,784
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2829412/Python-or-Bottom-UP-DP
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: n=len(cookies) #if the number of kids is equivalent to number of bags then just return the bag with max value if n==k: return max(cookies) #initialize the set l=[[0]*k] division=set(tuple(i) for i in l) #calculate possible permutations for curr number of bags (i+1) for i in range(n): div=set() for d in division: for j in range(k): temp=list(d) temp[j]+=cookies[i] div.add(tuple(temp)) #we delete the previous set to get rid of previous permutations because we only need ith perm to calculate i+1th perm del division division=div # print(division) return min([max(t) for t in division])
fair-distribution-of-cookies
Python | Bottom-UP DP
jaidev2
0
11
fair distribution of cookies
2,305
0.626
Medium
31,785
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2743811/Backtracking-Python-or-with-bounding-condition-and-no-TLE
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: def backtrack(bagNumber): if bagNumber == len(cookies): self.minResult = min(self.minResult, max(self.fairDistribution)) return if self.minResult <= max(self.fairDistribution): return for child in range(k): self.fairDistribution[child] += cookies[bagNumber] backtrack(bagNumber+1) self.fairDistribution[child] -= cookies[bagNumber] self.minResult = float('inf') self.fairDistribution = [0 for _ in range(k)] if k == len(cookies): return max(cookies) backtrack(0) return self.minResult
fair-distribution-of-cookies
Backtracking - Python | with bounding condition and no TLE
shor123
0
10
fair distribution of cookies
2,305
0.626
Medium
31,786
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2465990/Python3-or-Avoid-TLE-With-One-Logical-Optimization-Check-Before-Recursing
class Solution: #Time-Complexity: O(k + k^n), O(k) time to intialize count array but branching factor is #still in worst case k and height of tree is at worst n!-> O(k^n) #Space-Complexity: O(k + n) -> O(n) due to call stack for recursion in terms of its #max depth! def distributeCookies(self, cookies: List[int], k: int) -> int: #Approach: For each and every ith bag of cookies, we have k choices! Give it to #0th index person, 1st index person, ..., k-1th person! #We can keep track of running total count of cookies per person in pass by ref array, #as well as the 2d pass by reference array also that keeps track of cookie bag counts #every ith person has! #n = number of cookie bags! Used to handle base case! n = len(cookies) #initialize min unfairness as garbage value! ans = float(inf) #3 paramters #1. i -> index of which ith cookie bag we are making decision for currently! #2. cur -> 2d array, passed by ref across rec. calls, which keeps track of #cookie bags held by each and every person! #3. count -> total number of cookies per person! def helper(i, count): nonlocal n, ans, k, cookies #base case: index i out of bounds! We distributed each and every bag of cookies! if(i == n): #flag will equal True if each and every person has positive amount of cookies! flag = True #initialize unfairness! unfairness = float(-inf) for e in count: #check if current count of cookies is zero! if(e == 0): flag = False break unfairness = max(unfairness, e) #check boolean flag! if(flag): ans = min(ans, unfairness) return num_of_cookies = cookies[i] #iterate through all people! for a in range(0, k): #also, update count array! count[a] += num_of_cookies #we should only recurse if giving num_of_cookies to ath child causes #his cookie count < current built up answer! If not, the recursive path #won't lead to solution anyways -> prevent unnecessary recursive calls! if(count[a] < ans): helper(i+1, count) count[a] -= num_of_cookies #once for loop is all exhausted, we recursively explored all possible ways to #give ith bag of cookies to each and every person! So, simply return! return #initialize count array initially to kick off recursion! initial_count = [0 for _ in range(k)] helper(0, initial_count) return ans
fair-distribution-of-cookies
Python3 | Avoid TLE With One Logical Optimization Check Before Recursing
JOON1234
0
80
fair distribution of cookies
2,305
0.626
Medium
31,787
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2465626/Python3-or-How-to-Optimize-to-Avoid-TLE-I-am-Facing
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: #Approach: For each and every ith bag of cookies, we have k choices! Give it to #0th index person, 1st index person, ..., k-1th person! #We can keep track of running total count of cookies per person in pass by ref array, #as well as the 2d pass by reference array also that keeps track of cookie bag counts #every ith person has! #n = number of cookie bags! Used to handle base case! n = len(cookies) #initialize min unfairness as garbage value! ans = float(inf) #3 paramters #1. i -> index of which ith cookie bag we are making decision for currently! #2. cur -> 2d array, passed by ref across rec. calls, which keeps track of #cookie bags held by each and every person! #3. count -> total number of cookies per person! def helper(i, count): nonlocal n, ans, k, cookies #base case: index i out of bounds! We distributed each and every bag of cookies! if(i == n): #flag will equal True if each and every person has positive amount of cookies! flag = True #initialize unfairness! unfairness = float(-inf) for e in count: #check if current count of cookies is zero! if(e == 0): flag = False break unfairness = max(unfairness, e) #check boolean flag! if(flag): ans = min(ans, unfairness) return num_of_cookies = cookies[i] #iterate through all people! for a in range(0, k): #also, update count array! count[a] += num_of_cookies #simply recurse! helper(i+1, count) count[a] -= num_of_cookies #once for loop is all exhausted, we recursively explored all possible ways to #give ith bag of cookies to each and every person! So, simply return! return #initialize count array initially to kick off recursion! initial_count = [0 for _ in range(k)] helper(0, initial_count) return ans
fair-distribution-of-cookies
Python3 | How to Optimize to Avoid TLE I am Facing
JOON1234
0
35
fair distribution of cookies
2,305
0.626
Medium
31,788
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2155799/Python-optimized-or-precompute-or-29ms-less-than-50-backtrack()-calls-per-test
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: n = len(cookies) if k == 1: return sum(cookies) elif k == n: return max(cookies) cookies.sort(reverse=True) if k == n - 1: return max(cookies[0], sum(cookies[-2:])) dist = [0] * k # precompute an approximate solution for cookie in cookies: heappush(dist, heappop(dist) + cookie) ans = max(dist) dist = [0] * k def backtrack(i=0): nonlocal ans if i < n: cookie = cookies[i] for d, j in {d: j for j, d in enumerate(dist)}.items(): if d + cookie < ans: dist[j] += cookie backtrack(i + 1) dist[j] -= cookie else: ans = min(ans, max(dist)) backtrack() return ans
fair-distribution-of-cookies
Python optimized | precompute | 29ms, less than 50 backtrack() calls per test
jmj1
0
103
fair distribution of cookies
2,305
0.626
Medium
31,789
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2147178/Python-backtracking
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: def backtrack(ci, dist): if ci == len(cookies): self.result = min(self.result, max(dist)) return for di in range(k): dist[di] += cookies[ci] if dist[di] < self.result: backtrack(ci + 1, dist) dist[di] -= cookies[ci] self.result = math.inf backtrack(0, [0]*k) return self.result
fair-distribution-of-cookies
Python, backtracking
blue_sky5
0
64
fair distribution of cookies
2,305
0.626
Medium
31,790
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2143569/Python-3DP-bit-mask%2B-Binary-search
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: n = len(cookies) @lru_cache(None) def dp(mask, k, tot): if k < 0 or tot < 0: return False if mask == (1 << n) - 1: return True for i in range(n): if mask &amp; (1 << i): continue if dp(mask ^ (1 << i), k, tot - cookies[i]) or dp(mask, k-1, mid): return True return False l, h = max(cookies), sum(cookies) while l < h: mid = l + (h - l) // 2 if dp(0, k-1, mid): h = mid else: l = mid + 1 dp.cache_clear() return l
fair-distribution-of-cookies
[Python 3]DP bit-mask+ Binary search
chestnut890123
0
76
fair distribution of cookies
2,305
0.626
Medium
31,791
https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141389/Python-Easy-Backtracking
class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: ans = sum(cookies) N = len(cookies) total = [0]*k def backtrack(i, total): nonlocal ans if i == N: ans = min(ans, max(total)) return if max(total) >= ans: return for j in range(k): total[j] += cookies[i] backtrack(i+1, total) total[j] -= cookies[i] backtrack(0, total) return ans
fair-distribution-of-cookies
[Python] Easy Backtracking
nightybear
0
49
fair distribution of cookies
2,305
0.626
Medium
31,792
https://leetcode.com/problems/naming-a-company/discuss/2147565/Python-or-Faster-than-100-or-groupby-detailed-explanation
class Solution: def distinctNames(self, ideas: List[str]) -> int: names=defaultdict(set) res=0 #to store first letter as key and followed suffix as val for i in ideas: names[i[0]].add(i[1:]) #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas) arr=list(names.keys()) ans,n=0,len(arr) for i in range(n): for j in range(i+1,n): #a,b => 2 distinct first letters a,b=arr[i],arr[j] # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be "newword1 newword2" or "newword2 newword1" res+=len(names[a]-names[b])*len(names[b]-names[a])*2 return res
naming-a-company
Python | Faster than 100% | groupby detailed explanation
anjalianupam23
4
172
naming a company
2,306
0.344
Hard
31,793
https://leetcode.com/problems/naming-a-company/discuss/2315350/Python3.-oror-dict-8-lines-w-explanation-oror-TM%3A-9965
class Solution: # Suppose, as an example, # ideas = [azz, byy, cxx, cww, bww, avv]. # Here's the plan: # # • We construct a dict with each initial as the key and the set of # suffixes accompanying that initial. For our example: # dct = {a:[zz,vv], b:[yy,ww], c:[xx,ww]} # # • Next, for each pair of initials we figure out the number of vaiid # names (we will worry about doubling the # of pairs at the end). # # For the pair a, b we get: # a, b -> ayy &amp; bzz, ayy &amp; bvv, aww &amp; bzz, aww &amp; bvv, # which is (2 "a" suffixes) x (2 "b" suffixes) = 4. # # Continuing: # a, c -> axx &amp; czz, axx &amp; cvv, aww &amp; czz, aww &amp; cvv. # again, 2x2 = 4 # However, the remaining pair: # b, c -> bxx &amp; cyy, {bxx &amp; cww, bww &amp; cyy, bww &amp; cww.} has # only one valid answer. The pairs in the {} are invalid. The reason # is that ww is in both suffixes. When we remove that common suffix # from both sets, we have 1x1 = 1. # # • Finally, we determine the answer to return. The # of overall valid # pairs from above is 4 + 4 + 1 = 9. Each valid pair can be reversed # to give another. We return the answer 2 x 9 = 18. def distinctNames(self, ideas: List[str]) -> int: dct, ans = defaultdict(set), 0 for idea in ideas: # <-- construct the dict w/ initial:{suffixes} dct[idea[0]].add(idea[1:]) # and sort the items to get a list of tuples to d = sorted(dct.items()) # help do the counting for init1, suff1 in d: # <-- evaluate the number for each pair of initials for init2, suff2 in d: if init2 >= init1: break c = len(suff1&amp;suff2) # <-- determine the # of suffixes in ans += (len(suff1)-c) * (len(suff2)-c) # common, and subtract that number from # the each suffix # before multiplying. return ans * 2 # <-- finally, return the sum times 2.
naming-a-company
Python3. || dict, 8 lines, w/ explanation || T/M: 99%/65%
warrenruud
3
111
naming a company
2,306
0.344
Hard
31,794
https://leetcode.com/problems/naming-a-company/discuss/2141202/Python3-freq-table
class Solution: def distinctNames(self, ideas: List[str]) -> int: seen = set(ideas) freq = Counter() letters = {x[0] for x in ideas} for idea in ideas: for ch in letters: if ch + idea[1:] not in seen: freq[idea[0], ch] += 1 ans = 0 for idea in ideas: for ch in letters: if ch + idea[1:] not in seen: ans += freq[ch, idea[0]] return ans
naming-a-company
[Python3] freq table
ye15
1
51
naming a company
2,306
0.344
Hard
31,795
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2168442/Counter
class Solution: def greatestLetter(self, s: str) -> str: cnt = Counter(s) return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), "")
greatest-english-letter-in-upper-and-lower-case
Counter
votrubac
37
2,500
greatest english letter in upper and lower case
2,309
0.686
Easy
31,796
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2731538/python-oror-O(N)
class Solution: def greatestLetter(self, s: str) -> str: s = set(s) upper, lower = ord('Z'), ord('z') for i in range(26): if chr(upper - i) in s and chr(lower - i) in s: return chr(upper - i) return ''
greatest-english-letter-in-upper-and-lower-case
python || O(N)
Sneh713
2
68
greatest english letter in upper and lower case
2,309
0.686
Easy
31,797
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2421496/Python-Elegant-and-Short-or-98.51-faster-or-Two-solutions-or-O(n*log(n))-and-O(n)
class Solution: """ Time: O(2*26*log(2*26)) Memory: O(2*26) """ def greatestLetter(self, s: str) -> str: letters = set(s) for ltr in sorted(letters, reverse=True): if ltr.isupper() and ltr.lower() in letters: return ltr return '' class Solution: """ Time: O(2*26) Memory: O(2*26) """ def greatestLetter(self, s: str) -> str: letters = set(s) greatest = '' for ltr in letters: if ltr.isupper() and ltr.lower() in letters: greatest = max(ltr, greatest) return greatest
greatest-english-letter-in-upper-and-lower-case
Python Elegant & Short | 98.51% faster | Two solutions | O(n*log(n)) and O(n)
Kyrylo-Ktl
2
99
greatest english letter in upper and lower case
2,309
0.686
Easy
31,798
https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2176707/Simple-Python-Solution
class Solution: def greatestLetter(self, s: str) -> str: l=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] for i in l[::-1]: if i.lower() in s and i in s: return i return ""
greatest-english-letter-in-upper-and-lower-case
Simple Python Solution
glavanya
2
63
greatest english letter in upper and lower case
2,309
0.686
Easy
31,799