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/number-of-dice-rolls-with-target-sum/discuss/2650329/Python-or-DP-or-95-Space-Optimized-Solution-or | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
module = 10**9 + 7
front = [0]*(target+1)
# base case..
for tar in range(target+1):
if tar >= 1 and tar <= k:
front[tar] = 1
else:
front[tar] = 0
for ind in range(n-2, -1, -1):
cur = [0]*(target+1)
for tar in range(target+1):
ways = 0
for x in range(1, k+1):
# can pick num from dice..
if x <= tar:
ways = ( ways + front[tar-x] )%module
else:
# cant pick num from dice..
break
cur[tar] = ways
front = cur
return front[target] | number-of-dice-rolls-with-target-sum | Python | DP | 95% Space Optimized Solution | | quarnstric_ | 0 | 7 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,900 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650177/Python-simple-recursion-with-memoization | class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
mod=(10**9)+7
memo={}
def tryforother(d,f,target,memo):
if target<d or target>d*f:
return 0
if d==1:
return 1 if target<=f else 0
if (d,f,target) in memo:
return memo[(d,f,target)]
pos_ways=0
for i in range(1,f+1):
pos_ways+=tryforother(d-1,f,target-i,memo)
pos_ways%=mod
memo[(d,f,target)]=pos_ways
return pos_ways
return tryforother(d,f,target,memo) | number-of-dice-rolls-with-target-sum | Python simple recursion with memoization | iliyazali | 0 | 2 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,901 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650115/Easy-explained-Dynamic-Programming-solution-on-Python | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
limit = 10**9 + 7
dp = [0 for x in range(target + 1)]
dp[0] = 1
for roll_number in range(n):
for sum_points in reversed(range(target + 1)):
if sum_points < roll_number:
dp[sum_points] = 0
else:
min_prev_points = max(0, sum_points - k)
dp[sum_points] = sum(dp[min_prev_points:sum_points])
return dp[target] % limit | number-of-dice-rolls-with-target-sum | Easy explained Dynamic Programming solution on Python | kisel_dv | 0 | 16 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,902 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650053/Number-of-Dice-Rolls-With-Target-Sum-Python-or-Java | class Solution:
def numRollsToTarget(self, d: int, f: int, target: int) -> int:
memo = {}
def dp(d, target):
if d == 0:
return 0 if target > 0 else 1
if (d, target) in memo:
return memo[(d, target)]
to_return = 0
for k in range(max(0, target-f), target):
to_return += dp(d-1, k)
memo[(d, target)] = to_return
return to_return
return dp(d, target) % (10**9 + 7) | number-of-dice-rolls-with-target-sum | Number of Dice Rolls With Target Sum [ Python | Java ] | klu_2100031497 | 0 | 68 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,903 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2650012/Python-simple-DP-solution | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
dp = [1] + [0 for _ in range(target)]
for _ in range(n):
n_dp = [0 for _ in range(target+1)]
for i in range(target+1):
if dp[i] != 0:
for j in range(1,k+1):
if i+j<=target:
n_dp[i+j] += dp[i]
dp = n_dp
return dp[-1]%(10**9+7) | number-of-dice-rolls-with-target-sum | Python simple DP solution | AllenXia | 0 | 3 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,904 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649360/Python-Simple-Python-Solution | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
dp = [[-1 for j in range(target+2)] for i in range(n+1)]
def cal(rem_d, tot_S):
if rem_d == 0 and tot_S == 0:
return 1
if tot_S < 0 or rem_d <= 0:
return 0
if dp[rem_d][tot_S] != -1: return dp[rem_d][tot_S]
ans = 0
for a in range(1,k+1):
ans += cal(rem_d-1, tot_S - a)
dp[rem_d][tot_S] = ans
return dp[rem_d][tot_S]
return cal(n, target)%(10**9+7) | number-of-dice-rolls-with-target-sum | [ Python ] ✅ Simple Python Solution ✅✅ | vaibhav0077 | 0 | 123 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,905 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649360/Python-Simple-Python-Solution | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
dp = [[0 for j in range(target+2)] for i in range(n+1)]
dp[0][0] = 1
for rem_d in range(1, n+1):
for tot_S in range(0, target + 2):
for a in range(1,min(k+1,tot_S + 1)):
dp[rem_d][tot_S] += dp[rem_d-1][tot_S - a]
return dp[n][target]%(10**9+7) | number-of-dice-rolls-with-target-sum | [ Python ] ✅ Simple Python Solution ✅✅ | vaibhav0077 | 0 | 123 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,906 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649248/2D-Dynamic-programming | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
dp = [[0 for _ in range(target+1)] for _ in range(n+1)]
dp[0][0] = 1
for t in range(target+1):
for i in range(n):
for face in range(1,k+1):
if t-face >= 0:
dp[i+1][t] += dp[i][t-face]
return dp[-1][-1]%(10**9+7) | number-of-dice-rolls-with-target-sum | 2D Dynamic programming | chris1nexus | 0 | 6 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,907 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649168/Python3%3A-Faster-than-99.35 | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
if target < n or target > k * n:
return 0
MAX = 10 ** 9 + 7
def binom(x, y):
if y > x or x < 0:
return 0
if y == 0 or y == x:
return 1
ans = 1
for t in range(1, y+1):
ans = ans * (x-y+t)
tmp = 0
while (ans + MAX * tmp) % t != 0:
tmp += 1
ans = (ans + MAX * tmp) // t
ans = ans % MAX
return ans
ans = 0
for i in range(target // k + 1):
sign = 1 if i % 2 == 0 else -1
update = sign * binom(n, i) * binom(target - 1 - i * k, n - 1)
ans = ans + update
ans = ans % MAX
return ans | number-of-dice-rolls-with-target-sum | Python3: Faster than 99.35% | Odinnnnnn | 0 | 75 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,908 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2649136/Python-or-Triple-loop-DP | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
modd=10**9+7
dp=[[0 for i in range(target+1)]for j in range(n+1)]
for i in range(1,min(target+1,k+1)):
dp[1][i]=1
for num in range(2,n+1):
for sm in range(1,target+1):
cpa=0
for j in range(sm-1,0,-1):
cpa+=1
# if sm-j>0:
dp[num][sm]+=dp[num-1][j]
if cpa==k:
break
dp[num][sm]%=modd
# print(dp)
# for i in range(1,target+1):
# for j in range(k+1):
# dp[i][n-i]+=dp[i-j][n-i-1]
return dp[n][target]%modd | number-of-dice-rolls-with-target-sum | Python | Triple loop DP | Prithiviraj1927 | 0 | 47 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,909 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648407/Python-solution-via-backtracking-and-cache-faster-than-89 | class Solution:
from functools import cache
@cache
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
if target > n * k:
return 0
elif target < 0 or (target == 0 and n > 0):
return 0
elif target == 0 and n == 0:
return 1
else:
return sum([self.numRollsToTarget(n-1, k, target - i) for i in range(1, k+1)]) % (10**9+7) | number-of-dice-rolls-with-target-sum | Python solution via backtracking and cache faster than 89% | Terry_Lah | 0 | 6 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,910 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648347/Python-Bottom-up-DP | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
MOD = 10 ** 9 + 7
# DP (n, target)
dp = [[0] * (target+1+k+1+1) for _ in range(n+1)]
for i in range(1, k+1):
dp[1][i] = 1
for i in range(1, n):
for t in range(0, target+1):
if dp[i][t] == 0:
continue
for j in range(1, k+1):
dp[i+1][t+j] += dp[i][t]
dp[i + 1][t + j] %= MOD
return dp[n][target] | number-of-dice-rolls-with-target-sum | [Python] Bottom-up DP | wtain | 0 | 5 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,911 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2648347/Python-Bottom-up-DP | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
MOD = 10 ** 9 + 7
# DP (n, target)
dp = [0] * (target+k+1)
for i in range(1, k+1):
dp[i] = 1
for i in range(n-1):
next_dp = [0] * (target+k+1)
for t in range(0, target+1):
if dp[t] == 0:
continue
for j in range(1, k+1):
if t+j > target:
break
next_dp[t+j] += dp[t]
next_dp[t + j] %= MOD
dp = next_dp
return dp[target] | number-of-dice-rolls-with-target-sum | [Python] Bottom-up DP | wtain | 0 | 5 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,912 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2250067/PYTHON-SOL-or-MEMO-%2B-RECURSION-or-WELL-EXPLAINED-or-EASY-or-FAST-or | class Solution:
def recursion(self,n,k,target):
if n == 1:
# base case
return 1 if 1 <= target <= k else 0
if (n,target) in self.dp: return self.dp[(n,target)]
ans = 0
for i in range(1,k+1):
ans += self.recursion(n-1,k,target - i)
self.dp[(n,target)] = ans
return ans
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
self.dp = {}
return self.recursion(n,k,target) % 1000000007 | number-of-dice-rolls-with-target-sum | PYTHON SOL | MEMO + RECURSION | WELL EXPLAINED | EASY | FAST | | reaper_27 | 0 | 134 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,913 |
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/2221149/Python-bottom-up-DP | class Solution:
def numRollsToTarget(self, n: int, k: int, target: int) -> int:
if n == 1:
if target > k: return 0
else: return 1
memo = [0 for t in range(target+1)]
# Note that we do not use memo[0]
for i in range(1, target+1):
if i <= k:
memo[i] = 1
else:
break
for _ in range(1, n):
tmp = [i for i in memo]
for t in range(1, target+1):
memo[t] = 0
for dice in range(1, k+1):
if t - dice > 0:
memo[t] += tmp[t-dice]
memo[t] = int(memo[t] % (1e9+7))
return int(memo[-1] % (1e9+7)) | number-of-dice-rolls-with-target-sum | Python bottom-up DP | sticky_bits | 0 | 113 | number of dice rolls with target sum | 1,155 | 0.536 | Medium | 17,914 |
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/2255000/PYTHON-or-AS-INTERVIEWER-WANTS-or-WITHOUT-ITERTOOLS-or-WELL-EXPLAINED-or | class Solution:
def maxRepOpt1(self, text: str) -> int:
first_occurence,last_occurence = {},{}
ans,prev,count = 1,0,0
n = len(text)
for i in range(n):
if text[i] not in first_occurence: first_occurence[text[i]] = i
last_occurence[text[i]] = i
for i in range(n+1):
if i < n and text[i] == text[prev]:
count += 1
else:
if first_occurence[text[prev]] < prev or last_occurence[text[prev]] > i : count += 1
ans = max(ans,count)
count = 1
prev = i
def someWork(item,before,after):
count = 0
while before >= 0 and text[before] == item:
count += 1
before -= 1
while after < n and text[after] == item:
count += 1
after += 1
if first_occurence[item] <= before or last_occurence[item] >= after:count+=1
return count
for i in range(1,n-1):
ans = max(ans,someWork(text[i+1],i-1,i+1))
return ans | swap-for-longest-repeated-character-substring | PYTHON | AS INTERVIEWER WANTS | WITHOUT ITERTOOLS | WELL EXPLAINED | | reaper_27 | 1 | 178 | swap for longest repeated character substring | 1,156 | 0.454 | Medium | 17,915 |
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/2825889/Python-Sliding-Window-O(N) | class Solution:
def maxRepOpt1(self, text: str) -> int:
freq = {}
for ch in text:
freq[ch] = freq.get(ch, 0)+1
n=len(text)
i=0
distinct = 0
cur={}
def include(ind):
nonlocal distinct
ch = text[ind]
cur[ch] = cur.get(ch,0)+1
if cur[ch] == 1:
distinct+=1
def exclude(ind):
nonlocal distinct
ch = text[ind]
cur[ch]-=1
if cur[ch]==0:
cur.pop(ch)
distinct-=1
for j in range(n):
#expansion
include(j)
if distinct >= 3:
#movement
exclude(i)
i+=1
continue
if distinct == 2:
keys = list(cur.keys())
a,b = keys[0], keys[1]
if cur[a] == 1 or cur[b] == 1:
if cur[a] == 1:
if freq[b] == cur[b]:
exclude(i)
i+=1
else:
if freq[a] == cur[a]:
exclude(i)
i+=1
else:
exclude(i)
i+=1
return n-i | swap-for-longest-repeated-character-substring | Python Sliding Window O(N) | saijayavinoth | 0 | 2 | swap for longest repeated character substring | 1,156 | 0.454 | Medium | 17,916 |
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/1490882/Python-O(n)-solution | class Solution:
def maxRepOpt1(self, text: str) -> int:
intervals = collections.defaultdict(list)
prev = ''
start = 0
# collect intervals for each letter
for i, ch in enumerate(text):
if ch != prev and i != 0:
intervals[prev].append((start, i))
start = i
prev = ch
intervals[prev].append((start, i + 1))
max_val = 0
# for each letter
for ch in intervals:
indices = intervals[ch]
n = len(indices)
third_interval_letter = n > 2
previ, prevj = indices[0]
max_val = max(max_val, prevj - previ)
# for each interval
for i in range(1, n):
curi, curj = indices[i]
# example aaabaaaba, intervals are
# a: (0,3) (4,6), (8,9)
# b: (3,4),(7,8)
# previ, prevj = 0, 2
# curi, curj = 4, 6
# curi - prevj = 4-3 = 1, we replace this letter with the last a
# (note: last letter is from the third interval)
# so this maximizes the consecutive substring length with the same letter
if curi - prevj == 1:
max_val = max(max_val, curj - previ + third_interval_letter - 1)
else:
# if gap is more one char and since n > 1 (since we are inside of the loop that means n is definitely > 1)
# we grab the letter from the neighbor interval for prev and current intervals
max_val = max(max_val, curj - curi + 1, prevj - previ + 1)
previ, prevj = curi, curj
return max_val | swap-for-longest-repeated-character-substring | Python O(n) solution | arsamigullin | 0 | 359 | swap for longest repeated character substring | 1,156 | 0.454 | Medium | 17,917 |
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/1480970/Groupby-and-Counter | class Solution:
def maxRepOpt1(self, text: str) -> int:
lst = [(key, len(list(seq))) for key, seq in groupby(text)]
len_lst_2 = len(lst) - 2
cnt = Counter(text)
max_len = 0
for i, (key, n) in enumerate(lst):
max_len = max(max_len, n)
if n < cnt[key]:
max_len = max(max_len, n + 1)
if i < len_lst_2 and lst[i + 1][1] == 1 and lst[i + 2][0] == key:
if (len_both := n + lst[i + 2][1]) < cnt[key]:
max_len = max(max_len, len_both + 1)
else:
max_len = max(max_len, len_both)
return max_len | swap-for-longest-repeated-character-substring | Groupby and Counter | EvgenySH | 0 | 99 | swap for longest repeated character substring | 1,156 | 0.454 | Medium | 17,918 |
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/816103/Python-O(n)-solution-with-comments | class Solution:
def maxRepOpt1(self, text: str) -> int:
inuse = collections.defaultdict(int) # chars used in the repeated substring
left = collections.defaultdict(int) # not used chars
MOVE_TO_THE_NEXT_CHAR = 1
REPLACE = 0
LEAVE_AS_IT_IS = -1
res, i, n = 1, 0, 0
# initially no chars are used yet
for ch in text:
left[ch] += 1
for j, ch in enumerate(text):
inuse[ch] += 1 # since we use this char
left[ch] -= 1 # subtract its count from left dict
n = max(inuse[ch], n)
# this defines action we are going to take
action = j - i - n
char_exists = False
if action >= MOVE_TO_THE_NEXT_CHAR:
inuse[text[i]] -= 1
left[text[i]] += 1 # add it to the left dict back, since it is no longer in use
i += 1
# we can replace only if we have unused char in the left dict
elif action == REPLACE:
char_exists = left[ch] > 0
elif action == LEAVE_AS_IT_IS:
char_exists = True
if char_exists and j - i >= res:
res = j - i + 1
return res | swap-for-longest-repeated-character-substring | Python O(n) solution with comments | arsamigullin | 0 | 260 | swap for longest repeated character substring | 1,156 | 0.454 | Medium | 17,919 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2177578/Python3-O(n2)-oror-O(1)-Runtime%3A-96ms-97.20-Memory%3A-14.5mb-84.92 | class Solution:
# O(n^2) || O(1)
# Runtime: 96ms 97.20% Memory: 14.5mb 84.92%
def countCharacters(self, words: List[str], chars: str) -> int:
ans=0
for word in words:
for ch in word:
if word.count(ch)>chars.count(ch):
break
else:
ans+=len(word)
return ans | find-words-that-can-be-formed-by-characters | Python3 O(n^2) || O(1) Runtime: 96ms 97.20% Memory: 14.5mb 84.92% | arshergon | 5 | 350 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,920 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2188726/Python-1-liner | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
return sum(len(word) if collections.Counter(word) <= collections.Counter(chars) else 0 for word in words) | find-words-that-can-be-formed-by-characters | Python 1-liner | russellizadi | 2 | 205 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,921 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2099811/Python-top-95-solution | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
ans = ''
for word in words:
for letter in word:
if chars.count(letter) < word.count(letter):
break
else:
ans += word
return len(ans) | find-words-that-can-be-formed-by-characters | Python top 95% solution | StikS32 | 2 | 253 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,922 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1875631/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
output = 0
for i in words:
count = 0
for j in i:
if chars.count(j) >= i.count(j):
count+=1
else:
break
if count == len(i):
output+=count
return output | find-words-that-can-be-formed-by-characters | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 2 | 160 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,923 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1918471/Python-One-Liner-or-Counter | class Solution:
def countCharacters(self, words, chars):
d, total = Counter(chars), 0
for w in words: total += self.helper(w, d.copy())
return total
def helper(self, w, d):
for c in w:
if c not in d or d[c] == 0: return 0
else: d[c]-=1
return len(w) | find-words-that-can-be-formed-by-characters | Python - One-Liner | Counter | domthedeveloper | 1 | 82 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,924 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1918471/Python-One-Liner-or-Counter | class Solution:
def countCharacters(self, words, chars):
return (lambda c:sum(len(x) for x in words if Counter(x) < c))(Counter(chars)) | find-words-that-can-be-formed-by-characters | Python - One-Liner | Counter | domthedeveloper | 1 | 82 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,925 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1806893/Python3-Solution | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
c = list(chars)
l,ans = 0,0
for i in words:
for j in list(i):
if j in c:
l += 1
c.remove(j)
if l == len(i):
ans += len(i)
c = list(chars)
l = 0
return (ans) | find-words-that-can-be-formed-by-characters | ✔Python3 Solution | Coding_Tan3 | 1 | 174 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,926 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1386031/Python3-Faster-Than-99.94-Memory-Less-Than-79.96 | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
from collections import Counter
c = Counter(chars)
cnt = 0
for word in words:
good = True
for letter in word:
if word.count(letter) > c[letter]:
good = False
break
if good:
cnt += len(word)
return cnt | find-words-that-can-be-formed-by-characters | Python3 Faster Than 99.94%, Memory Less Than 79.96% | Hejita | 1 | 109 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,927 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1177497/python-sol-faster-than-96-less-mem-than-93 | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
tot = 0
for i in range(len(words)):
for j in range(len(words[i])):
if (words[i][j] not in chars):
break
if (words[i].count(words[i][j]) > chars.count(words[i][j])):
break
if(j == len(words[i]) - 1):
tot += len(words[i])
return tot | find-words-that-can-be-formed-by-characters | python sol faster than 96% , less mem than 93% | elayan | 1 | 472 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,928 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2822917/Python-oror-Faster-than-99.85-and-Memory-beats-85.14 | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
c = 0
for word in words:
good = True
for l in word:
if chars.count(l) < word.count(l):
good = False
break
if good == True: c += len(word)
return c | find-words-that-can-be-formed-by-characters | Python ✅✅✅|| Faster than 99.85% and Memory beats 85.14% | qiy2019 | 0 | 5 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,929 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2813313/Simple-Python3-Solution-Runtime-101-ms-Beats-97.99-Memory-14.5-MB-Beats-85.3 | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
result_words = []
for word in words:
found = True
for ch in word:
if (ch not in chars) or (word.count(ch) > chars.count(ch)):
found = False
break
if (found):
result_words.append(word)
result = 0
for word in result_words:
result += len(word)
return result | find-words-that-can-be-formed-by-characters | Simple Python3 Solution Runtime 101 ms Beats 97.99% Memory 14.5 MB Beats 85.3% | SupriyaArali | 0 | 4 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,930 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2724771/Easy-Solution%3A-99.22-Faster | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
op=[]
for i in words:
na = 0
for j in i:
if (j not in chars)or (i.count(j)>chars.count(j)):
na = 1
break
if na==0:
op.append(i)
cnt=0
for i in op:
cnt+=len(i)
return cnt | find-words-that-can-be-formed-by-characters | Easy Solution: 99.22% Faster | BAparna97 | 0 | 9 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,931 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2673811/Python-solution-easy-to-understand | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
c = Counter(chars)
ans = 0
for w in words:
temp = Counter(w)
found = True
for k, v in temp.items():
if k in c:
if c[k] < v:
found = False
break
else:
found = False
break
if found:
print(w)
ans += len(w)
return ans | find-words-that-can-be-formed-by-characters | Python solution - easy to understand | phantran197 | 0 | 11 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,932 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2660999/Python%2BCounter | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
return sum([len(word) for word in words if Counter(word) <=Counter(chars) ]) | find-words-that-can-be-formed-by-characters | Python+Counter | Leox2022 | 0 | 3 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,933 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2602478/Python-1-liner | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
return sum(len(word) for word in words if Counter(word) <= Counter(chars)) | find-words-that-can-be-formed-by-characters | Python 1-liner | Potentis | 0 | 41 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,934 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2599299/91-ms-faster-than-99.21-(with-explanation) | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
charMap, result = [0] * 26, 0
for char in chars:
charMap[ord(char) - 97] += 1
for word in words:
if len(word) > len(chars):
continue
temp = charMap[::]
for letter in word:
index = ord(letter) - 97
if temp[index] == 0:
break
temp[index] -= 1
else:
result += len(word)
return result | find-words-that-can-be-formed-by-characters | 91 ms, faster than 99.21% (with explanation) | kcstar | 0 | 35 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,935 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2592278/A-Double-Dictionary-Approach | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
charMap, result = {}, 0
for char in chars:
charMap[char] = charMap.get(char, 0) + 1
for word in words:
if len(word) > len(chars):
continue
temp, count = {}, 0
for letter in word:
temp[letter] = temp.get(letter, 0) + 1
for key, val in temp.items():
if charMap.get(key, 0) < val:
break
count += val
else:
result += count
return result | find-words-that-can-be-formed-by-characters | A Double Dictionary Approach | kcstar | 0 | 14 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,936 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2508114/easy-Python-Solution-92-faster | class Solution(object):
def countCharacters(self, words, chars):
x=set(chars)
ans=0
for i in words:
a=set(i)
if a.issubset(x):
arr=[o for o in a if chars.count(o)<i.count(o)]
if len(arr)==0:
ans+=len(i)
return ans | find-words-that-can-be-formed-by-characters | easy Python Solution 92% faster | pranjalmishra334 | 0 | 53 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,937 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2395057/Easy-hashmap | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
d1={}
for i in chars:
if i in d1:
d1[i]+=1
else:
d1[i]=1
c=0
for i in words:
yes=len(i)
d={}
for j in i:
if j in d:
d[j]+=1
else:
d[j]=1
for l in d:
if l in d1:
if d1[l] < d[l]:
yes=0
else:
yes=0
break
c+=yes
return c | find-words-that-can-be-formed-by-characters | Easy hashmap | sunakshi132 | 0 | 75 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,938 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2294765/Python3-Simple-Solution | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
count = 0
d = {}
dd = {}
for c in chars:
d[c] = d.get(c, 0) + 1
dd[c] = dd.get(c, 0) + 1
for word in words:
flag = True
for w in word:
if w in d and d[w] != 0:
d[w] -= 1
else:
flag = False
break
if flag == True:
count += len(word)
for key in dd.keys():
d[key] = dd[key]
return count | find-words-that-can-be-formed-by-characters | Python3 Simple Solution | mediocre-coder | 0 | 131 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,939 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2175654/2-Easy-Methods | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
hmap1=Counter(chars)
res=0
for word in words:
if not (Counter(word) - hmap1):
res+=len(word)
return res | find-words-that-can-be-formed-by-characters | 2 Easy Methods | Defence | 0 | 42 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,940 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2067337/python3-easy-solution | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
l1=[]
sum=0
for i in range(len(words)):
temp=list(words[i])
l1=list(chars)
# print(l1)
c=0
for i in range(len(temp)):
if temp[i] in l1:
l1.remove(temp[i])
c=c+1
elif temp[i] not in l1:
c=0
break
if c>0:
k = len(temp)
sum = sum + k
return sum | find-words-that-can-be-formed-by-characters | python3 easy solution | vishwahiren16 | 0 | 90 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,941 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2043636/python-3-oror-counter-solution-oror-O(C)O(1) | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
charsCount = collections.Counter(chars)
res = 0
for word in words:
for c, count in collections.Counter(word).items():
if count > charsCount[c]:
break
else:
res += len(word)
return res | find-words-that-can-be-formed-by-characters | python 3 || counter solution || O(C)/O(1) | dereky4 | 0 | 176 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,942 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1675247/Python3-dollarolution | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
def dicts(s):
d = {}
for i in s:
if i not in d:
d[i] = 1
else:
d[i] += 1
return d
s, count = 0, 0
d1 = dicts(chars)
for i in words:
d2 = dicts(i)
for j in d2:
if j in d1:
if d2[j] > d1[j]:
s = 1
break
else:
s = 1
break
if s == 0: count += len(i)
s = 0
return count | find-words-that-can-be-formed-by-characters | Python3 $olution | AakRay | 0 | 154 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,943 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1508960/Python-solution-with-explanation-(for-loop-%2B-letter-count) | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
word_char_ct = 0
for word in words:
# initially assume that chars can create word
boolean_ind = True
# iterate thru each letter in word, if a word has MORE letters than available in "chars", it can't be made by "chars"
for letter in word:
if word.count(letter) > chars.count(letter):
boolean_ind = False
# if word can be made by "chars" += len of word
if boolean_ind:
word_char_ct += len(word)
return word_char_ct | find-words-that-can-be-formed-by-characters | Python solution with explanation (for loop + letter count) | jjluxton | 0 | 93 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,944 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1081328/Python3-freq-table | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
fc = {}
for c in chars: fc[c] = 1 + fc.get(c, 0)
ans = 0
for word in words:
fw = {}
for c in word: fw[c] = 1 + fw.get(c, 0)
if all(fw[c] <= fc.get(c, 0) for c in fw): ans += len(word)
return ans | find-words-that-can-be-formed-by-characters | [Python3] freq table | ye15 | 0 | 76 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,945 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1081328/Python3-freq-table | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
ans = 0
fc = Counter(chars)
for word in words:
if not Counter(word) - fc: ans += len(word)
return ans | find-words-that-can-be-formed-by-characters | [Python3] freq table | ye15 | 0 | 76 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,946 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1039312/Python3-easy-solution-using-Counter | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
count = 0
for i in words:
a = Counter(i)
b = Counter(chars)
flag = True
for j in i:
if not b[j] >= a[j]:
flag = False
if flag == True:
count += len(i)
return count | find-words-that-can-be-formed-by-characters | Python3 easy solution using Counter | EklavyaJoshi | 0 | 130 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,947 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/553095/Python-3-Solution-using-dictionary | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
good_words = []
usable_chars_dict = {}
for char in chars:
usable_chars_dict[char] = usable_chars_dict.get(char, 0) + 1
for word in words:
available_chars = usable_chars_dict.copy()
rejected = None
for char in word:
if char in available_chars and available_chars[char] > 0:
available_chars[char] -= 1
else:
rejected = True
break
if not rejected: good_words.append(word)
return len(''.join(good_words)) | find-words-that-can-be-formed-by-characters | Python 3 Solution using dictionary | duyh | 0 | 174 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,948 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1778478/6-Lines-Python-Solution-oror-Faster-than-96-oror-Memory-less-than-94 | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
ans = 0
for word in words:
for char in word:
if word.count(char) > chars.count(char): break
else: ans += len(word)
return ans | find-words-that-can-be-formed-by-characters | 6 Lines Python Solution || Faster than 96% || Memory less than 94% | Taha-C | -1 | 133 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,949 |
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/1722868/Python-60.01-Faster-180ms | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
#vars to hold values
wordlen = 0
runningsum = 0
charedits = chars
#evaluate words individually
for word in words:
wordlen = 0
charedits = chars
#Evaluate letters in words
for letter in word:
#check the letter in the updating list
if letter in charedits:
wordlen +=1
charedits = charedits.replace(letter,' ',1)
#check word char match
if len(word) == wordlen:
runningsum += len(word)
return(runningsum) | find-words-that-can-be-formed-by-characters | Python 60.01% Faster, 180ms | ovidaure | -1 | 172 | find words that can be formed by characters | 1,160 | 0.677 | Easy | 17,950 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/848959/BFS-Python-solution-with-comments! | class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
queue = deque() #init a queue for storing nodes as we traverse the tree
queue.append(root) #first node (level = 1) inserted
#bfs = [] #just for understanding- this will be a bfs list to store nodes as we conduct the search, but we don't need it here.
level_sum = 0 # for sum of each level
level_nodes = 1 # for knowing when a particular level has ended
sum_of_levels = [] #list to store all levels sum of nodes
while queue: #begin BFS
node = queue.popleft()
#bfs.append(node)
level_sum += node.val #add node
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
level_nodes -= 1 #reduce level number by 1, as we popped out a node
if level_nodes == 0: # if 0, then a level has ended, so calculate the sum
sum_of_levels.append(level_sum)
level_sum = 0
level_nodes = len(queue)
return sum_of_levels.index(max(sum_of_levels)) + 1 #return index of max level sum | maximum-level-sum-of-a-binary-tree | BFS Python solution - with comments! | tintsTy | 1 | 58 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,951 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/2825715/Python-DFS | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
def dfs(node, level):
if not node:
return
sums[level] += node.val
dfs(node.left, level + 1)
dfs(node.right, level +1 )
sums = defaultdict(int)
dfs(root, 1)
result = 1
max_sum = sums[1]
for level, s in sums.items():
if s > max_sum:
max_sum = s
result = level
return result | maximum-level-sum-of-a-binary-tree | Python, DFS | blue_sky5 | 0 | 2 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,952 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/2791988/Python-solution | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
levels = []
sums = float('-inf')
res = 0
def levelorder(node, level):
if level >= len(levels):
levels.append([])
if node:
levels[level].append(node.val)
if node.left:
levelorder(node.left, level + 1)
if node.right:
levelorder(node.right, level + 1)
levelorder(root, 0)
for i in range(len(levels)):
if sum(levels[i]) > sums:
sums = sum(levels[i])
res = i + 1
return res | maximum-level-sum-of-a-binary-tree | Python solution | maomao1010 | 0 | 5 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,953 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/2431412/python-bfs-beginner-friendly | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
q = collections.deque()
tracker = [float('-inf'),0]
q.append(root)
level = 1
while q:
levelSum = 0
for _ in range(len(q)):
node = q.popleft()
levelSum += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if levelSum > tracker[0]:
tracker[0] = levelSum
tracker[1] = level
level += 1
return tracker[1] | maximum-level-sum-of-a-binary-tree | python bfs beginner friendly | scr112 | 0 | 17 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,954 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/2209920/Short-and-Very-Intuitive-with-inline-comment | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
if not root:
return None
q=deque()
max_sum=-10**18 #assume the max_level_sum to be -10**18
level=0 #this is current level
level_ans=0 #this will store the level at which the max_sum has occured
q.append(root) #start our bfs with the root node obviously
while len(q)!=0: #do the bfs as long as the queue is not empty
level+=1 #update the level after each while loop
#start from level 1
curr_sum=0 #store the levelwise sum
for i in range(len(q)): #traverse through each node of current level
curr_sum+=q[i].val #store the sum of val of each node of the current level
if curr_sum>max_sum: #check if the current_level_sum is greater than the max_level_sum
max_sum=curr_sum #update the max_sum
level_ans=level #update the level at which max_sum is found
# now take the node from left to right of each level
#below is typical bfs traversal
for i in range(len(q)):
node=q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return level_ans
#pls upvote if it helps you in any manner regarding understanding the solution | maximum-level-sum-of-a-binary-tree | Short and Very Intuitive with inline-comment | Taruncode007 | 0 | 23 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,955 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/1984012/Python-solution-100-Test-Cases | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
def getHeight(root):
if root.left==None and root.right==None:
return 0
left=0
if root.left!=None:
left = getHeight(root.left)
right=0
if root.right!=None:
right=getHeight(root.right)
return (max(left, right) + 1)
def calculateLevelSum(root, level, sum):
if root == None:
return sum
sum[level]+=root.val
calculateLevelSum(root.left, level+1, sum)
calculateLevelSum(root.right, level+1, sum)
return sum
levels=getHeight(root) + 1
sum=[0]*levels
sum=calculateLevelSum(root, 0, sum)
return sum.index(max(sum))+1 | maximum-level-sum-of-a-binary-tree | Python solution 100% Test Cases | Siddharth_singh | 0 | 25 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,956 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/1503224/python-dfs | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
stack = [(root, 1)]
h = defaultdict(int)
while stack:
node, depth = stack.pop()
if node:
h[depth] += node.val
stack.append((node.left, 1+depth))
stack.append((node.right, 1+depth))
minv = float('-inf')
res = -1
for key in h:
v = h[key]
if v > minv:
minv = v
res = key
return res | maximum-level-sum-of-a-binary-tree | python dfs | byuns9334 | 0 | 95 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,957 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/1422714/PYTHON3-BFS-or-87-Fast! | class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
if not root :
return
q = deque()
q.append(root)
res = []
while q :
sum = 0
size = len(q)
for _ in range(size) :
node = q.popleft()
sum += node.val
if node.left :
q.append(node.left)
if node.right :
q.append(node.right)
res.append(sum)
return 1+ res.index(max(res)) | maximum-level-sum-of-a-binary-tree | PYTHON3 - BFS | 87% Fast! | athrvb | 0 | 45 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,958 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/1081332/Python3-bfs-by-level | class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
ans = level = 0
val = -inf
queue = [root]
while queue:
level += 1
newq = []
tmp = 0
for node in queue:
tmp += node.val
if node.left: newq.append(node.left)
if node.right: newq.append(node.right)
if tmp > val: ans, val = level, tmp
queue = newq
return ans | maximum-level-sum-of-a-binary-tree | [Python3] bfs by level | ye15 | 0 | 79 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,959 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/981681/python-3-simple-solution-bfs | class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
if not root:
return None
stack = [root]
values = []
while stack:
queue = []
for _ in range(len(stack)):
node = stack.pop(0)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
queue.append(node.val)
values.append(sum(queue))
return values.index(max(values)) + 1 | maximum-level-sum-of-a-binary-tree | python 3 simple solution bfs | GiorgosMarga | 0 | 45 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,960 |
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/361116/Python3-level-order-BFS | class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
from collections import deque
if not root: return []
queue, res = deque([root]), []
while queue:
cur_level, size = [], len(queue)
for i in range(size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
cur_level.append(node.val)
res.append(cur_level)
res = [sum(i) for i in res]
return res.index(max(res))+1 | maximum-level-sum-of-a-binary-tree | Python3 level order BFS | aj_to_rescue | 0 | 41 | maximum level sum of a binary tree | 1,161 | 0.661 | Medium | 17,961 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1158339/A-general-Explanation-w-Animation | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
# The # of rows and # of cols
M, N, result = len(grid), len(grid[0]), -1
# A list of valid points
valid_points = {(i, j) for i in range(M) for j in range(N)}
# A double-ended queue of "land" cells
queue = collections.deque([(i, j) for i in range(M) for j in range(N) if grid[i][j] == 1])
# Check if all land, or all water, an edge case
if len(queue) == M*N or len(queue) == 0:
return -1
# BFS
while queue:
# One iteration here
for _ in range(len(queue)):
i, j = queue.popleft()
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
if (x, y) not in valid_points: continue
if grid[x][y] == 1: continue
queue.append((x, y))
grid[x][y] = 1 # We mark water cells as land to avoid visiting them again
# Increase the iteration/result count
result += 1
return result | as-far-from-land-as-possible | A general Explanation w/ Animation | dev-josh | 8 | 367 | as far from land as possible | 1,162 | 0.486 | Medium | 17,962 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2258475/PYTHON-or-EXPLAINED-WITH-INTUTION-or-FAST-or-BFS-or-WELL-WRITTEN-or | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
queue = []
vist = [[False for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
queue.append((i,j,0))
vist[i][j] = True
ans = 0
while queue:
r,c,d = queue.pop(0)
if grid[r][c] == 0 :ans = max(ans,d)
for x,y in ((r+1,c),(r-1,c),(r,c+1),(r,c-1)):
if 0 <= x < n and 0 <= y < n and vist[x][y] == False:
vist[x][y] = True
queue.append((x,y,d+1))
return ans if ans != 0 else -1 | as-far-from-land-as-possible | PYTHON | EXPLAINED WITH INTUTION | FAST | BFS | WELL WRITTEN | | reaper_27 | 4 | 71 | as far from land as possible | 1,162 | 0.486 | Medium | 17,963 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2102946/Python-BFS.-FASTER-THAN-94. | class Solution:
def maxDistance(self, grid: list[list[int]]) -> int:
n = len(grid)
dq = deque((i, j) for i in range(n) for j in range(n) if grid[i][j])
res = 0
while dq:
r0, c0 = dq.popleft()
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
r1, c1 = r0 + dr, c0 + dc
if 0 <= r1 < n and 0 <= c1 < n and not grid[r1][c1]:
dq.append((r1, c1))
grid[r1][c1] = grid[r0][c0] + 1
res = max(res, grid[r1][c1])
return res - 1 | as-far-from-land-as-possible | Python BFS. FASTER THAN 94%. | miguel_v | 4 | 182 | as far from land as possible | 1,162 | 0.486 | Medium | 17,964 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1552850/Easy-Approach-oror-Thought-Process-oror-Well-Explained-and-Coded | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
q = []
dp = [[-1 for _ in range(n)] for _ in range(n)]
def isvalid(i,j):
if 0<=i<n and 0<=j<n and grid[i][j]==0:
return True
return False
for i in range(n):
for j in range(n):
if grid[i][j]==1:
q.append((i,j))
dp[i][j]=0
res = -1
while q:
x,y = q.pop(0)
for dx,dy in [(1,0),(-1,0),(0,-1),(0,1)]:
if isvalid(x+dx,y+dy) and dp[x+dx][y+dy]==-1:
q.append((x+dx,y+dy))
dp[x+dx][y+dy] = dp[x][y]+1
res = max(res,dp[x+dx][y+dy])
return res | as-far-from-land-as-possible | 📌📌 Easy-Approach || Thought Process || Well-Explained and Coded 🐍 | abhi9Rai | 4 | 196 | as far from land as possible | 1,162 | 0.486 | Medium | 17,965 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1081337/Python3-multi-source-bfs | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid) # dimension
ans = -1
queue = [(i, j) for i in range(n) for j in range(n) if grid[i][j]]
while queue:
newq = []
for i, j in queue:
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < n and 0 <= jj < n and not grid[ii][jj]:
newq.append((ii, jj))
grid[ii][jj] = 1 # mark as visited
queue = newq
ans += 1
return ans or -1 | as-far-from-land-as-possible | [Python3] multi-source bfs | ye15 | 2 | 94 | as far from land as possible | 1,162 | 0.486 | Medium | 17,966 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1035927/Python-BFS-by-your-senpai | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
row, col = len(grid),len(grid[0])
queue = deque([])
water_cell = 0
for x in range(row):
for y in range(col):
if grid[x][y] == 1:
queue.append((x,y))
else:
water_cell+=1
if water_cell == 0:
return -1
visited = set([])
step = 0
while queue:
for _ in range(len(queue)):
x ,y = queue.popleft()
if (x,y) in visited: continue
visited.add((x,y))
for nx, ny in [(x+1,y), (x-1,y), (x,y+1), (x,y-1)]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny]!=1:
grid[nx][ny] = 1
queue.append((nx,ny))
step+=1
return step-1 | as-far-from-land-as-possible | Python BFS by your senpai | Skywalker5423 | 1 | 156 | as far from land as possible | 1,162 | 0.486 | Medium | 17,967 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2846547/Python-oror-BFS-oror-easy | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
visited = [[False for _ in range(m)] for _ in range(n)]
max_distance = 0
queue = deque()
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
queue.append((i, j, 0))
while queue:
size = len(queue)
for i in range(size):
x, y, d = queue.popleft()
for (row, col) in [(1,0),(0,1),(-1, 0), (0, -1)]:
r = row+x
c = col+y
if r<0 or r>=n or c<0 or c>=m or grid[r][c] == 1 or visited[r][c]:
continue
visited[r][c] = True
max_distance = max(max_distance, d+1)
queue.append((r, c, d+1))
return max_distance if max_distance > 0 else -1 | as-far-from-land-as-possible | Python || BFS || easy | dhanu084 | 0 | 1 | as far from land as possible | 1,162 | 0.486 | Medium | 17,968 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2645835/Simple-Multi-Source-BFS-Solution-Python | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
m = len(grid[0])
delrow = [-1,0,1,0]
delcol = [0,1,0,-1]
queue = []
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
queue.append([i,j,0])
maxdist = -1
while queue:
row, col, dist = queue.pop(0)
maxdist = max(maxdist,dist)
for i in range(4):
nrow = row + delrow[i]
ncol = col + delcol[i]
if nrow>=0 and nrow<n and ncol>=0 and ncol<m and grid[nrow][ncol] == 0:
grid[nrow][ncol] = 1
queue.append([nrow,ncol,dist+1])
return -1 if maxdist == 0 else maxdist | as-far-from-land-as-possible | Simple Multi Source BFS Solution - Python | abroln39 | 0 | 32 | as far from land as possible | 1,162 | 0.486 | Medium | 17,969 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/2420440/Ad-far-from-land-as-possible-oror-Python3-oror-DP | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
dist = [[math.inf] * len(grid[0]) for i in range(0, len(grid))]
land = 0
for i in range(0, len(grid)):
for j in range(0, len(grid[0])):
if(grid[i][j] == 1):
dist[i][j] = 0
land += 1
else:
if(i > 0):
dist[i][j] = min(dist[i-1][j] + 1, dist[i][j])
if(j > 0):
dist[i][j] = min(dist[i][j-1] + 1, dist[i][j])
if(i > 0 and j > 0):
dist[i][j] = min(dist[i-1][j-1] + 2, dist[i][j])
if(len(grid) * len(grid[0]) == land or land == 0):
return -1
for i in range(len(grid)-1, -1, -1):
for j in range(len(grid[0]) -1 , -1, -1):
if(i < len(grid) - 1):
dist[i][j] = min(dist[i+1][j] + 1, dist[i][j])
if(j < len(grid[0]) - 1):
dist[i][j] = min(dist[i][j+1] + 1, dist[i][j])
if(i < len(grid) - 1 and j < len(grid[0]) - 1):
dist[i][j] = min(dist[i+1][j+1] + 2, dist[i][j])
ans = 0
for i in range(len(grid)-1, -1, -1):
for j in range(len(grid[0])-1, -1, -1):
ans = max(ans, dist[i][j])
return ans | as-far-from-land-as-possible | Ad far from land as possible || Python3 || DP | vanshika_2507 | 0 | 33 | as far from land as possible | 1,162 | 0.486 | Medium | 17,970 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1810940/Python-BFS | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
directions = ((0, 1), (0, -1), (-1, 0), (1, 0))
# position class to represent land coordinates
Position = namedtuple('Position', ['row', 'col'])
def withinBounds(pos):
return 0 <= pos.row < rows and 0 <= pos.col < cols
# get all land positions in our queue
queue = deque([Position(r,c) for r in range(rows) for c in range(cols) if grid[r][c]])
if not queue or len(queue) == rows * cols:
return -1
distance = 0
while queue:
# level order bfs, so we check the closest neighbors for each cell at every iteration
for i in range(len(queue)):
pos = queue.popleft()
# explore the neighbors
for dr, dc in directions:
newPos = Position(pos.row + dr, pos.col + dc)
if withinBounds(newPos) and grid[newPos.row][newPos.col] == 0:
# change the 0s to 1s to we don't visit them again
grid[newPos.row][newPos.col] = 1
# add the neighbor,
queue.append(newPos)
# level is done so increment distance
distance += 1
return distance - 1 # negate by one to account for searching when all neighbor cells are already visited | as-far-from-land-as-possible | Python BFS | Rush_P | 0 | 69 | as far from land as possible | 1,162 | 0.486 | Medium | 17,971 |
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1031999/Easy-to-Read-and-Understand-Python-with-Comments! | class Solution:
def maxDistance(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
q = collections.deque()
zeros = 0
# Get our number of zeros and our 1 starting locations.
for row in range(rows):
for col in range(cols):
if grid[row][col] == 0:
zeros += 1
if grid[row][col] == 1:
q.append((row, col, 0))
# Two edge cases where we will want to return -1.
if not q or not zeros:
return -1
# Our manhattan distance based movements (d, u, r, l)
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Keep record of the largest encountered distance.
dist = 0
# while there are 0's left to move to.
while zeros and q:
r, c, d = q.popleft()
# Try to move in all of our possible directions.
for y, x in directions:
nr = y + r
nc = x + c
# Make sure the new location is in the grid and is a 0.
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0:
# record the new disr, mark the location as visited and put back into the queue.
dist = max(d + 1, dist)
zeros -= 1
grid[nr][nc] = '#'
q.append((nr, nc, d + 1))
return dist | as-far-from-land-as-possible | Easy to Read and Understand Python with Comments! | Pythagoras_the_3rd | -1 | 98 | as far from land as possible | 1,162 | 0.486 | Medium | 17,972 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/361321/Solution-in-Python-3-(beats-100) | class Solution:
def lastSubstring(self, s: str) -> str:
S, L, a = [ord(i) for i in s] + [0], len(s), 1
M = max(S)
I = [i for i in range(L) if S[i] == M]
if len(I) == L: return s
while len(I) != 1:
b = [S[i + a] for i in I]
M, a = max(b), a + 1
I = [I[i] for i, j in enumerate(b) if j == M]
return s[I[0]:]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | last-substring-in-lexicographical-order | Solution in Python 3 (beats 100%) | junaidmansuri | 3 | 742 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,973 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/2263217/PYTHON-or-EXPLANATION-WITH-PHOTO-or-LINEAR-TIME-or-EASY-or-INTUITIVE-or | class Solution:
def lastSubstring(self, s: str) -> str:
n = len(s)
cmax = max(s)
indexes = [ i for i,c in enumerate(s) if c == cmax ]
gap = 1
while len(indexes) > 1:
new_indexes = []
cmax = max(s[i+gap] for i in indexes if i+gap < n)
for i,st in enumerate(indexes):
if i > 0 and indexes[i-1] + gap == st: continue
if st + gap < n and s[st + gap] == cmax:new_indexes.append(st)
indexes = new_indexes
gap += 1
return s[indexes[0]:] | last-substring-in-lexicographical-order | PYTHON | EXPLANATION WITH PHOTO | LINEAR TIME | EASY | INTUITIVE | | reaper_27 | 1 | 273 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,974 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/1081371/Python3-brute-force | class Solution:
def lastSubstring(self, s: str) -> str:
return max(s[i:] for i in range(len(s))) | last-substring-in-lexicographical-order | [Python3] brute-force | ye15 | 1 | 222 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,975 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/1081371/Python3-brute-force | class Solution:
def lastSubstring(self, s: str) -> str:
ii = k = 0
i = 1
while i + k < len(s):
if s[ii+k] == s[i+k]: k += 1
else:
if s[ii+k] > s[i+k]: i += k+1
else:
ii = max(ii+k+1, i)
i = ii+1
k = 0
return s[ii:] | last-substring-in-lexicographical-order | [Python3] brute-force | ye15 | 1 | 222 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,976 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/482282/Python3-two-methods | class Solution:
def lastSubstring(self, s: str) -> str:
i,j,k,n = 0,1,0,len(s)
while j+k<n:
if s[i+k]==s[j+k]:
k+=1
continue
elif s[i+k]>s[j+k]:
j+=k+1
else:
i=max(j,i+k+1)
j=i+1
k=0
return s[i:]
def lastSubstringBF(self, s: str) -> str:
if len(s)<=1: return s
i,res=1,set()
while i<len(s)+1:
for j in range(len(s)):
if len(s[j:])<i:
break
res.add(s[j:j+i])
i+=1
res = sorted(res)
return res[-1] | last-substring-in-lexicographical-order | Python3 two methods | jb07 | 1 | 361 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,977 |
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/1073707/Python-O(n)-less-than-10-lines | class Solution:
def lastSubstring(self, s: str) -> str:
max_substring = ""
max_char = ""
for i in range(len(s)):
if s[i] >= max_char:
max_char = s[i]
max_substring = max(max_substring, s[i : ])
return max_substring | last-substring-in-lexicographical-order | Python O(n) less than 10 lines | michaellin986 | -6 | 630 | last substring in lexicographical order | 1,163 | 0.35 | Hard | 17,978 |
https://leetcode.com/problems/invalid-transactions/discuss/670649/Simple-clean-python-only-10-lines | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
invalid = []
for i, t1 in enumerate(transactions):
name1, time1, amount1, city1 = t1.split(',')
if int(amount1) > 1000:
invalid.append(t1)
continue
for j, t2 in enumerate(transactions):
if i != j:
name2, time2, amount2, city2 = t2.split(',')
if name1 == name2 and city1 != city2 and abs(int(time1) - int(time2)) <= 60:
invalid.append(t1)
break
return invalid | invalid-transactions | Simple clean python - only 10 lines | auwdish | 7 | 1,600 | invalid transactions | 1,169 | 0.312 | Medium | 17,979 |
https://leetcode.com/problems/invalid-transactions/discuss/2507495/Python-Solution-or-Hashmap-or-Set | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
hashmap = {}
#Hashset is used to skip redudant transactions being added to the result
#We will only store index of the transaction because the same transaction can repeat.
result = set()
for i, t in enumerate(transactions):
name, time, amount, city = t.split(",")
#If there is no transaction record for the user
if name not in hashmap:
hashmap[name] = []
if int(amount) > 1000:
result.add(i)
#If there are pass transaction records
else:
#Fetching past transaction from hashmap
prevTrans = hashmap[name]
#Iterating over the past transaction of the user and finding anomalies
for j in range(len(prevTrans)):
prevName, prevTime, prevAmount, prevCity = transactions[prevTrans[j]].split(",")
#Checking whether the amount exceeds $1000
if int(amount) > 1000:
result.add(i)
#Checking whether it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
if abs(int(time) - int(prevTime)) <= 60 and city != prevCity:
result.add(i)
result.add(prevTrans[j])
#Recording transaction in the hashmap for the user
hashmap[name].append(i)
#Fetching transaction using indexes stored in the result set and returning
return [transactions[t] for t in result] | invalid-transactions | Python Solution | Hashmap | Set | reeteshz | 5 | 684 | invalid transactions | 1,169 | 0.312 | Medium | 17,980 |
https://leetcode.com/problems/invalid-transactions/discuss/2536635/Python%3A-very-simple-and-straightforward-solution | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
cities = defaultdict(lambda: defaultdict(list))
output = []
#build city map.
for t in transactions:
name, time, amount, city = t.split(',')
cities[city][name].append(time)
#Check each transaction against all transactions in a given city name from a given person
for t in transactions:
name, time, amount, city = t.split(',')
#Case 1
if int(amount) > 1000:
output.append(t)
continue
#Case 2
for k,v in cities.items():
if k == city:
continue
if any([abs(int(x) - int(time)) <= 60 for x in v[name]]):
output.append(t)
break;
return output | invalid-transactions | Python: very simple and straightforward solution | jesse14 | 3 | 1,100 | invalid transactions | 1,169 | 0.312 | Medium | 17,981 |
https://leetcode.com/problems/invalid-transactions/discuss/2827880/Python3-Linear-time-Solution-O(N) | class Solution(object):
def invalidTransactions(self, transactions: List[str]) -> List[str]:
# make a defaultdict to save the transactions first
mapped_transactions = collections.defaultdict(lambda: collections.defaultdict(set))
# go through the transactions and save all of them in the structure
for transaction in transactions:
name, time, amount, city = Solution.parse_transaction(transaction)
mapped_transactions[name][time].add(city)
# go through the transactions again and check for invalid ones
result = []
for transaction in transactions:
# parse the transcation
name, time, amount, city = Solution.parse_transaction(transaction)
# check for the amount
if amount > 1000:
result.append(transaction)
continue
# check whether we have a transaction with the same name
if name not in mapped_transactions:
continue
# check if other transaction exist within the invalid timeframe
for time_point in range(time-60, time+61):
# time point does not exist
if time_point not in mapped_transactions[name]:
continue
# check if there are more cities in within the time frame and the name
# and if it is only one check that it is not the same city!
if len(mapped_transactions[name][time_point]) > 1 or (city not in mapped_transactions[name][time_point]):
result.append(transaction)
break
return result
@staticmethod
def parse_transaction(transaction: str) -> Tuple[str, int, int, str]:
name, time, amount, city = transaction.split(',')
time = int(time)
amount = int(amount)
return name, time, amount, city | invalid-transactions | [Python3] - Linear time Solution O(N) | Lucew | 2 | 45 | invalid transactions | 1,169 | 0.312 | Medium | 17,982 |
https://leetcode.com/problems/invalid-transactions/discuss/2794530/Python3-Solution-faster-than-99.90-(with-HashMap) | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
invalid = []
txn = collections.defaultdict(list)
for trn in transactions:
name, time, amount, city = trn.split(",")
txn[name].append([time,amount,city])
for trans in range(len(transactions)):
name, time, amount, city = transactions[trans].split(",")
if int(amount) > 1000:
invalid.append(transactions[trans])
else:
for trn in txn[name]:
time_i, _, city_i = trn
if city != city_i and abs(int(time) - int(time_i)) <= 60:
invalid.append(transactions[trans])
break
return invalid | invalid-transactions | Python3 Solution faster than 99.90% (with HashMap) | aikyab | 1 | 36 | invalid transactions | 1,169 | 0.312 | Medium | 17,983 |
https://leetcode.com/problems/invalid-transactions/discuss/2739439/Brute-Force-Easy-To-Understand-Python-Solution | class Solution:
'''
transaction:
- name
- time
- city
- amount
transaction is possibly invalid if;
- amount is over 1000
OR all of the following are met;
- within 60 minutes of other_transaction
- same name as another other_transaction
- different city as other_transaction
transaction = {
name: [time, city, amount],
}
iterate through transactions
find all transactions with the same name and add to transaction map
-> transaction[name] = [transaction1, transaction2, etc..]
iterate through transactions
if the current transaction is over 1000
add current transaction to the output
if current transaction is within 60 mins, same name and different city as
other transaction
add current transaction to the output
break the loop because otherwise we can have duplicate values
'''
def invalidTransactions(self, transactions: List[str]) -> List[str]:
stored_transactions = collections.defaultdict(list)
for transaction in transactions:
split_transaction = transaction.split(',')
stored_transactions[split_transaction[0]].append(split_transaction)
results = []
for current_transaction in transactions:
current_split_transaction = current_transaction.split(',')
name, time, amount, city = current_split_transaction
if int(amount) >= 1000:
results.append(current_transaction)
else:
for stored_transaction in stored_transactions[name]:
if abs(int(time) - int(stored_transaction[1])) <= 60 and city != stored_transaction[3]:
results.append(current_transaction)
break
return results | invalid-transactions | Brute Force Easy-To-Understand Python Solution | trietostopme | 0 | 17 | invalid transactions | 1,169 | 0.312 | Medium | 17,984 |
https://leetcode.com/problems/invalid-transactions/discuss/2733602/Python-O(n2)-with-HashMap | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
nameMap = collections.defaultdict(list)
ans = []
for t in transactions:
splitT = t.split(",")
name = splitT[0]
time = splitT[1]
amount = splitT[2]
city = splitT[3]
nameMap[name].append((name,time,amount,city))
for p in nameMap:
for trans in nameMap[p]:
if(not self.isValid(trans,nameMap[p])):
ans.append(",".join(trans))
return ans
def isValid(self,t,listT):
name,time,amount,city = t
if(int(amount) > 1000):
return False
for current in listT:
cName,cTime,cAmount,cCity = current
if city == cCity:
continue
if (abs(int(time) - int(cTime)) <= 60):
return False
return True | invalid-transactions | Python O(n^2) with HashMap | chinclashs | 0 | 40 | invalid transactions | 1,169 | 0.312 | Medium | 17,985 |
https://leetcode.com/problems/invalid-transactions/discuss/2263406/or-PYTHON-WELL-WRITTEN-or-O(N2)-or-EASY-or-FAST-or | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
n = len(transactions)
for i in range(n):
transactions[i] = transactions[i].split(',')
transactions.sort(key = lambda x: int(x[1]))
ans = []
failed = [False for i in range(n)]
for i in range(n):
if int(transactions[i][2]) > 1000 : failed[i] = True
for j in range(i+1,n):
if int(transactions[j][1]) - int(transactions[i][1]) > 60: break
if transactions[j][0] == transactions[i][0] and\
transactions[j][-1] != transactions[i][-1]:
failed[i] = failed[j] = True
if failed[i] == True:
ans.append(','.join(transactions[i]))
return ans | invalid-transactions | | PYTHON WELL WRITTEN | O(N^2) | EASY | FAST | | reaper_27 | 0 | 204 | invalid transactions | 1,169 | 0.312 | Medium | 17,986 |
https://leetcode.com/problems/invalid-transactions/discuss/1565057/Python-O(N-%2B-KlogK)-Time-Straightforward-Python-Solutions-beats-100 | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
N = len(transactions)
# parse strings in transactions for later references
data = [(n, int(t), int(m), c) for n, t, m, c in map(lambda s: s.split(','), transactions)]
get_name = lambda i: data[i][0]
get_time = lambda i: data[i][1]
get_money = lambda i: data[i][2]
get_city = lambda i: data[i][3]
# O(K), k is the max length of indices
def collect_city_conflicts(indices, invalids):
t1 = t2 = float('inf')
c1 = c2 = ''
for i in indices:
city, time = get_city(i), get_time(i)
if city == c1:
if abs(time - t2) <= 60:
invalids.add(i)
t1 = time
else:
if abs(time - t1) <= 60:
invalids.add(i)
t2, c2 = t1, c1
t1, c1 = time, city
# O(KlogK)
def get_invalids(indices, invalids):
# O(KlogK)
indices.sort(key = lambda i: get_time(i))
# O(K), from past to future to see any conflict happens before cur time
collect_city_conflicts(indices, invalids)
# O(K), from future to past to see any conflict happens after cur time
collect_city_conflicts(indices[::-1], invalids)
# O(K) find any index of the invalid transactions whose amount > 1000
invalids |= {i for i in indices if get_money(i) > 1000}
# O(N), K = max(map(len, data_by_person.values()))
data_by_person = collections.defaultdict(list)
for i in range(N):
data_by_person[get_name(i)].append(i)
# O(N)
invalids = set()
for indices in data_by_person.values():
get_invalids(indices, invalids)
return [transactions[i] for i in invalids] | invalid-transactions | [Python] O(N + KlogK) Time Straightforward Python Solutions, beats 100% | licpotis | 0 | 238 | invalid transactions | 1,169 | 0.312 | Medium | 17,987 |
https://leetcode.com/problems/invalid-transactions/discuss/1084468/Python3-brute-force | class Solution:
def invalidTransactions(self, transactions: List[str]) -> List[str]:
flag = [False]*len(transactions)
for i, transaction in enumerate(transactions):
n, t, a, c = transaction.split(",")
if int(a) > 1000: flag[i] = True
for ii in range(i+1, len(transactions)):
nn, tt, aa, cc = transactions[ii].split(",")
if n == nn and abs(int(t) - int(tt)) <= 60 and c != cc: flag[i] = flag[ii] = True
return [t for t, f in zip(transactions, flag) if f] | invalid-transactions | [Python3] brute-force | ye15 | 0 | 142 | invalid transactions | 1,169 | 0.312 | Medium | 17,988 |
https://leetcode.com/problems/invalid-transactions/discuss/366512/Solution-in-Python-3 | class Solution:
def invalidTransactions(self, T: List[str]) -> List[str]:
u, V = list(map(lambda x: [x[0],x[3],int(x[1]),int(x[2])], map(lambda x: x.split(','), T))), set()
N = {i[0]:[] for i in u}
for i,[n,c,t,a] in enumerate(u):
N[n].append([t,c,i])
if a > 1000: V.add(T[i])
for i in N.keys():
s = sorted(N[i])
for j in range(len(s)-1):
for k in range(j+1,len(s)):
if s[k][0] - s[j][0] > 60: break
if s[k][1] != s[j][1]: V.update([T[s[j][2]],T[s[k][2]]])
return V
- Junaid Mansuri
(LeetCode ID)@hotmail.com | invalid-transactions | Solution in Python 3 | junaidmansuri | 0 | 750 | invalid transactions | 1,169 | 0.312 | Medium | 17,989 |
https://leetcode.com/problems/invalid-transactions/discuss/366522/Simple-13-Line-Python-Solution | class Solution:
def invalidTransactions(self, ts: List[str]) -> List[str]:
nts = [t.split(',') for t in ts]
nts = sorted([[a, int(b), int(c), d] for a, b, c, d in nts])
res = set()
for a in nts:
if a[2] > 1000: res.add(','.join(map(str,a)))
for i in range(len(nts)):
for j in range(i + 1, len(nts)):
a, b = nts[i], nts[j]
if a[0] != b[0] or abs(a[1] - b[1]) > 60: break
if a[3] != b[3]:
res.add(','.join(map(str,a)))
res.add(','.join(map(str,b)))
return list(res) | invalid-transactions | Simple 13 Line Python Solution | code_report | -1 | 785 | invalid transactions | 1,169 | 0.312 | Medium | 17,990 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/401039/Python-Simple-Code-Memory-efficient | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def f(s):
t = sorted(list(s))[0]
return s.count(t)
query = [f(x) for x in queries]
word = [f(x) for x in words]
m = []
for x in query:
count = 0
for y in word:
if y>x:
count+=1
m.append(count)
return m | compare-strings-by-frequency-of-the-smallest-character | Python Simple Code Memory efficient | saffi | 14 | 1,700 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,991 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1236328/Python3-Brute-Force-Solution | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def f(x):
return x.count(min(x))
ans = []
for i in queries:
count = 0
for j in words:
if(f(i) < f(j)):
count += 1
ans.append(count)
return ans | compare-strings-by-frequency-of-the-smallest-character | [Python3] Brute Force Solution | VoidCupboard | 3 | 77 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,992 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/1203192/Python-Easy-Solution | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
q = []
for query in queries:
query = sorted(query)
temp = query.count(query[0])
q.append(temp)
w = []
for word in words:
word = sorted(word)
temp = word.count(word[0])
w.append(temp)
ans = []
w.sort()
for i in q:
temp = 0
for j in range(len(w)):
if w[j]>i:
temp+=len(w)-j
break
ans.append(temp)
return ans | compare-strings-by-frequency-of-the-smallest-character | Python Easy Solution | iamkshitij77 | 2 | 97 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,993 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/2558508/Python3-or-Solved-Using-Binary-Search-By-Translating-Each-and-Every-word-into-Function-Value | class Solution:
#Let n = len(queries) and m = len(words)
#Time-Complexity: O(m + mlog(m) + n*log(m)) -> O(mlog(m) + nlog(m))
#Space-Complexity: O(10*m + n*10 + m) -> O(n + m)
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
#Approach: Traverse linearly through each and every word in words array
#and get its function value and append it to seperate array!
#Then, sort the separate array in increasing order.
#Then, for each ith query, get the function value from applying
#function on ith query string -> look for leftmost index in
#new array s.t. from that particular index onwards, all values
#will be larger than the ith query function value!
#This will help us get number of words in words input array that
#have higher function value than current query!
#We need to also define helper function that computes
#function value for any non-empty string!
def helper(s):
hashmap = {}
for c in s:
if c not in hashmap:
hashmap[c] = 1
continue
else:
hashmap[c] += 1
#iterate through each key value and put it in array of tuples,
#where first element is letter and second element is its frequency!
array = []
for k,v in hashmap.items():
array.append((k, v))
#then sort the array by lexicographical order: first element of tuple!
array.sort(key = lambda x: x[0])
#return the first element of array: lexicographically smallest
#char frequency!
return array[0][1]
ans = []
arr = []
for word in words:
arr.append(helper(word))
#sort the new array arr!
arr.sort()
#iterate through each and every query!
for query in queries:
requirement = helper(query)
#initiate binary search to find leftmost index pos in arr!
l, r = 0, (len(arr) - 1)
leftmost_index = None
while l <= r:
mid = (l + r) // 2
middle = arr[mid]
if(middle > requirement):
leftmost_index = mid
r = mid - 1
continue
else:
l = mid + 1
continue
#once binary search is over, we should have leftmost index!
#Append the difference val since it tells number of words
#with function value greater than requirement!
#we have to check whether leftmost_index still equals None ->
#if none of words in words array have function val greater than
#the requirement!
if(leftmost_index == None):
ans.append(0)
continue
ans.append(len(arr) - leftmost_index)
return ans | compare-strings-by-frequency-of-the-smallest-character | Python3 | Solved Using Binary Search By Translating Each and Every word into Function Value | JOON1234 | 1 | 20 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,994 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/416774/Python3 | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
queries_frequecy = [self.f(i) for i in queries]
words_frequecy = [self.f(i) for i in words]
words_frequecy.sort()
res = []
length = len(words_frequecy)
for i in range(len(queries_frequecy)):
for j in range(length):
if queries_frequecy[i] < words_frequecy[j]:
res.append(length -j)
break
if len(res) < i+1:
res.append(0)
return res
def f(self, s):
smallest = min(s)
return s.count(smallest) | compare-strings-by-frequency-of-the-smallest-character | [Python3] | zhanweiting | 1 | 235 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,995 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/2768919/python3-count-and-binary-search-sol-for-reference. | class Solution:
def smallestCharFreq(self, s):
sc = s[0]
cnt = 1
for idx in range(1,len(s)):
c = s[idx]
if c < sc:
cnt = 1
sc= c
elif c == sc:
cnt += 1
return cnt
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
W = sorted([self.smallestCharFreq(i) for i in words])
ans = []
for q in queries:
target = self.smallestCharFreq(q)
ans.append(len(W) - bisect_left(W, target+1))
return ans | compare-strings-by-frequency-of-the-smallest-character | [python3] count and binary search sol for reference. | vadhri_venkat | 0 | 7 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,996 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/2498001/easy-python-solution | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
output, query_count, word_count = [], [], []
for word in queries :
query_word = [ch for ch in word]
query_word.sort()
f_query_word = query_word.count(query_word[0])
query_count.append(f_query_word)
for word in words :
word = [ch for ch in word]
word.sort()
f_word = word.count(word[0])
word_count.append(f_word)
for q in query_count :
counter = 0
for i in range(len(word_count)) :
if q < word_count[i] :
counter += 1
output.append(counter)
return output | compare-strings-by-frequency-of-the-smallest-character | easy python solution | sghorai | 0 | 14 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,997 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/2485310/Beginner-friendly-python-solution | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
res = []
words = [w.count(min(w)) for w in words]
queries = [q.count(min(q)) for q in queries]
for q in queries:
count = 0
for w in words:
count += q < w
res.append(count)
return res | compare-strings-by-frequency-of-the-smallest-character | Beginner friendly python solution | yhc22593 | 0 | 3 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,998 |
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/2263490/PYTHON-or-AS-INTERVIEWER-WANTS-or-WITHOUT-USING-PRE-DEFINED-FUNCTIONS | class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
def freq(word):
l = len(word)
ans,minn = 1,word[0]
for i in range(1,l):
if word[i] == minn: ans += 1
elif word[i] < minn :
minn = word[i]
ans = 1
return ans
n = len(words)
m = len(queries)
words_fs = []
for i,word in enumerate(words):
words_fs.append(freq(word))
words_fs.sort()
def binarysearch(x):
low ,high = 0,n-1
while low <= high:
mid = (low+high)//2
if words_fs[mid] == x:
low = mid + 1
elif words_fs[mid] < x:
low = mid + 1
else:
high = mid - 1
return high
ans = [0]*m
for i,word in enumerate(queries):
fq = freq(word)
idx = binarysearch(fq)
ans[i] = n - idx - 1
return ans | compare-strings-by-frequency-of-the-smallest-character | PYTHON | AS INTERVIEWER WANTS | WITHOUT USING PRE DEFINED FUNCTIONS | reaper_27 | 0 | 36 | compare strings by frequency of the smallest character | 1,170 | 0.614 | Medium | 17,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.