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/count-vowels-permutation/discuss/2393400/Easy-to-understand-DP-solution-with-comments-or-python3 | class Solution:
# O(n) time,
# O(n) space,
# Approach: dynamic programming,
def countVowelPermutation(self, n: int) -> int:
vowels = ['a', 'e', 'i', 'o', 'u']
# we store our vowel indexes in the above list
# for faster access on later operations
vowel_index = {
'a' : 0,
'e' : 1,
'i' : 2,
'o' : 3,
'u' : 4,
}
# we use a dictonary which maps a specific vowel to list of vowels that span it,
# for eg, vowels 'e', 'i' and 'u' can be followed by vowel 'a'
# these are rules given in the question
vowel_span = {
'a' : ['e', 'i', 'u'],
'e' : ['a', 'i'],
'i' : ['e', 'o'],
'o' : ['i'],
'u' : ['i', 'o']
}
# we initialize a dp array(2D) of n columns and 5(our vowel count) rows,
# You can see the image down below for better visualization
dp = [ [1 for i in range(n)] for j in range(5) ]
# now we build our dp array starting from n = 2, or i = 1, since our dp array is 0 indexed and for n = 1,
# we have strings with length 1 and we only have 5 permutations for that.
# so the intution here is we store how many permutations/strings end with for each vowel for each lenght till length =n,
# so we will know how many strings will end with a specific character, say A,
# since we know how many characters span the vowel A on the next length,
# now we build our dp starting from length = 1, to length = n
# so for eg, when our length = 2, if we had 2 strings that end with 'e', 1 with 'u' and 1 in 'i',
# then strings that end with 'a' when we reach length = 3 will be the sum of the vowels that end with 'i', 'e' and 'u' in the length-1, in our case 2,
# i.e, dp[a][3] = dp[e][2] + dp[i][2] + dp[u][2]
# letters are stored in form of their index in the dp array
for i in range(1, n):
for j in range(5):
vowel = vowels[j]
v_index = vowel_index[vowel]
vowel_spanners = vowel_span[vowel]
tot = 0
for vp in vowel_spanners:
index = vowel_index[vp]
tot += dp[index][i-1]
dp[v_index][i] = tot
result = 0
# then we add all the counts in the last col, and return the result
for i in range(5):
result +=dp[i][n-1]
return result % ((10**9) + 7) | count-vowels-permutation | Easy to understand DP solution with comments | python3 | destifo | 0 | 17 | count vowels permutation | 1,220 | 0.605 | Hard | 18,400 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2393016/Python3-Solution-with-using-dp | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp = [[0] * 5 for _ in range(n + 1)]
for i in range(5):
dp[1][i] = 1
mod = 10**9 + 7
"""
0 - a
1 - e
2 - i
3 - o
4 - u
"""
for i in range(1, n):
dp[i + 1][0] = (dp[i][1] + dp[i][2] + dp[i][4]) % mod
dp[i + 1][1] = (dp[i][0] + dp[i][2]) % mod
dp[i + 1][2] = (dp[i][1] + dp[i][3]) % mod
dp[i + 1][3] = dp[i][2] % mod
dp[i + 1][4] = (dp[i][2] + dp[i][3]) % mod
res = 0
for i in range(5):
res = (res + dp[-1][i]) % mod
return res | count-vowels-permutation | [Python3] Solution with using dp | maosipov11 | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,401 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392985/Python-Accurate-Solution-using-Tuples-as-DP-Numbers-oror-Documented | class Solution:
def countVowelPermutation(self, n: int) -> int:
MOD = 10**9 + 7
a, e, i, o, u = 1, 1, 1, 1, 1 # dp numbers with initial value of 1
while n > 1:
# modify the dp numbers by adding previous values based on Follows rules
a, e, i, o, u = (e+i+u) % MOD, (a+i) % MOD, (e+o) % MOD, i, (i+o) % MOD
n -= 1
return (a+e+i+o+u) % MOD # result is sum of all dp numbers | count-vowels-permutation | [Python] Accurate Solution using Tuples as DP Numbers || Documented | Buntynara | 0 | 3 | count vowels permutation | 1,220 | 0.605 | Hard | 18,402 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392961/Fastest-and-memory-effective-Python-Solution | class Solution:
def countVowelPermutation(self, n: int) -> int:
a, e, i, o, u = 1, 1, 1, 1, 1
z = pow(10, 9)+7
for k in range(2, n+1):
a, e, i, o, u = (e + i + u) % z, (a + i) % z, (e + o) % z, i, (o + i) % z
return (a + e + i + o + u) % z | count-vowels-permutation | Fastest and memory effective Python Solution | zip_demons | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,403 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392373/GoPython-O(n)-time-or-O(n)-space | class Solution:
def countVowelPermutation(self, n: int) -> int:
modulo = (10**9+7)
vowel = 5
digits_to_letters = {0:"a",
1:"e",
2:"i",
3:"o",
4:"u"}
letters_to_digits = {"a":0,
"e":1,
"i":2,
"o":3,
"u":4}
next_letters = {"a":("e"),
"e":("a","i"),
"i":("a","e","o","u"),
"o":("i","u"),
"u":("a")}
prev = [1 for _ in range(vowel)]
curr = [0 for _ in range(vowel)]
for i in range(1,n):
for j in range(vowel):
curr[j] = 0
for letter in next_letters[digits_to_letters[j]]:
curr[j]+= prev[letters_to_digits[letter]]
curr,prev = prev,curr
return sum(prev) % modulo | count-vowels-permutation | Go/Python O(n) time | O(n) space | vtalantsev | 0 | 24 | count vowels permutation | 1,220 | 0.605 | Hard | 18,404 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392373/GoPython-O(n)-time-or-O(n)-space | class Solution:
def countVowelPermutation(self, n: int) -> int:
modulo = (10**9+7)
a, e, i, o, u = 1, 1, 1, 1, 1
for _ in range(n-1):
a, e, i, o, u = e, a+i, a+e+o+u, i+u, a
return (a+e+i+o+u) % modulo | count-vowels-permutation | Go/Python O(n) time | O(n) space | vtalantsev | 0 | 24 | count vowels permutation | 1,220 | 0.605 | Hard | 18,405 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392213/Python3-Memoization-DFS | class Solution:
def countVowelPermutation(self, n: int) -> int:
return (self.dfs("", 0, n, {})) % (10**9 + 7)
def dfs(self, curr, count, n, dp):
if count > n: return 0
elif count == n: return 1
if (curr,count) in dp: return dp[(curr,count)]
if curr == "":
dp[(curr, count)] = self.dfs("a", count + 1, n, dp) + self.dfs("e", count + 1, n, dp) + self.dfs("i", count + 1, n, dp) + self.dfs("o", count + 1, n, dp) + self.dfs("u", count + 1, n, dp)
if curr == "a":
dp[(curr, count)] = self.dfs("e", count + 1, n, dp)
elif curr == "e":
dp[(curr, count)] = self.dfs("a", count + 1, n, dp) + self.dfs("i", count + 1, n, dp)
elif curr == "i":
dp[(curr, count)] = self.dfs("a", count + 1, n, dp) + self.dfs("e", count + 1, n, dp) + self.dfs("o", count + 1, n, dp) + self.dfs("u", count + 1, n, dp)
elif curr == "o":
dp[(curr, count)] = self.dfs("i", count + 1, n, dp) + self.dfs("u", count + 1, n, dp)
elif curr == "u":
dp[(curr, count)] = self.dfs("a", count + 1, n, dp)
return dp[(curr, count)] | count-vowels-permutation | [Python3] Memoization DFS | AustinHuang823 | 0 | 8 | count vowels permutation | 1,220 | 0.605 | Hard | 18,406 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2392182/Python-Fast-and-trivial-solution | class Solution:
def countVowelPermutation(self, n: int) -> int:
# Complexity::
# - Time: O(N)
# - Space: O(1)
i = numEndingWithA = numEndingWithE = numEndingWithI = numEndingWithO = numEndingWithU = 1
while i < n:
i += 1
numEndingWithA, numEndingWithE, numEndingWithI, numEndingWithO, numEndingWithU = (
(numEndingWithE + numEndingWithI + numEndingWithU) % _MODULO,
(numEndingWithA + numEndingWithI) % _MODULO,
(numEndingWithE + numEndingWithO) % _MODULO,
(numEndingWithI) % _MODULO,
(numEndingWithI + numEndingWithO) % _MODULO,
)
return (numEndingWithA + numEndingWithE + numEndingWithI + numEndingWithO + numEndingWithU) % _MODULO
_MODULO = 10 ** 9 + 7 | count-vowels-permutation | [Python] Fast and trivial solution | RegInt | 0 | 10 | count vowels permutation | 1,220 | 0.605 | Hard | 18,407 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2391837/Python3-oror-Dynamic-Programming-oror-TC%3A-O(n)-oror-Commented-code | class Solution:
def countVowelPermutation(self, n: int) -> int:
mod = (10 ** 9) + 7
dp = [[0 for c in range(5)] for r in range(n+1)]
#dp[i][j] -> number of strings of len = i that ends with j-th vowel
#0th vowel: a || 1st: e || 2nd: i || 3rd: o || 4th : u
ends_with = {0: [1,2,4],
1: [0,2],
2: [1,3],
3: [2],
4: [2,3]}
#0th char is a(idx = 0), a can be the last char if prev chars are e(idx = 1), i(idx=2) or u(idx=3)
#... similar for other chars
for r in range(n+1):
for c in range(5):
if r == 0 or r == 1:
dp[r][c] = r
else:
for idx in ends_with[c]:
dp[r][c] += dp[r-1][idx]
return sum(dp[-1]) % mod | count-vowels-permutation | Python3 || Dynamic Programming || TC: O(n) || Commented code | s_m_d_29 | 0 | 15 | count vowels permutation | 1,220 | 0.605 | Hard | 18,408 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2391476/Easy-to-understand-or-python3-or-with-diagram | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp = [[1,1,1,1,1]]
n -= 1
while n!=0:
a = dp[-1][0]
e = dp[-1][1]
i = dp[-1][2]
o = dp[-1][3]
u = dp[-1][4]
dp.append([e+i+u,a+i,e+o,i,i+o])
n -= 1
return sum(dp[-1])%1000000007 | count-vowels-permutation | Easy to understand | python3 | with diagram | jayeshmaheshwari555 | 0 | 4 | count vowels permutation | 1,220 | 0.605 | Hard | 18,409 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390281/%22python%22-simple-solution-for-you-%3A) | class Solution:
def countVowelPermutation(self, n: int) -> int:
dp = [[], [1, 1, 1, 1, 1]]
a, e, i, o, u = 0, 1, 2, 3, 4
mod = 10 ** 9 + 7
for j in range(2, n + 1):
dp.append([0, 0, 0, 0, 0])
dp[j][a] = (dp[j - 1][e] + dp[j - 1][i] + dp[j - 1][u])
dp[j][e] = (dp[j - 1][a] + dp[j - 1][i]) % mod
dp[j][i] = (dp[j - 1][e] + dp[j - 1][o]) % mod
dp[j][o] = dp[j - 1][i]
dp[j][u] = dp[j - 1][i] + dp[j - 1][o]
return sum(dp[n]) % mod | count-vowels-permutation | "python" simple solution for you :) | anandchauhan8791 | 0 | 15 | count vowels permutation | 1,220 | 0.605 | Hard | 18,410 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390243/1220.-Python3-one-liners%3A-slow-to-267ms81.58 | class Solution:
@lru_cache
def countVowelPermutation(self, n: int, lastchar: str='') -> int:
return (
sum(self.countVowelPermutation(n-1, nextchar)
for nextchar in
{'': 'aeiou', 'a':'e', 'e':'ai', 'i': 'aeou', 'o':'iu', 'u':'a'}[lastchar]) % 1000000007
if n>0 else 1) | count-vowels-permutation | 1220. Python3 one-liners: slow to 267ms/81.58% | leetavenger | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,411 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390243/1220.-Python3-one-liners%3A-slow-to-267ms81.58 | class Solution:
predecessors = {'a': 'eiu', 'e': 'ai', 'i': 'eo', 'o': 'i', 'u': 'io'}
def countVowelPermutation(self, n: int) -> int:
vowels, result = 'aeiou', [1, 1, 1, 1, 1]
for i in range(1, n):
result = [sum(result[vowels.index(v)]
for v in self.predecessors[lastchar]) for lastchar in vowels]
return sum(result)%1000000007 | count-vowels-permutation | 1220. Python3 one-liners: slow to 267ms/81.58% | leetavenger | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,412 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390243/1220.-Python3-one-liners%3A-slow-to-267ms81.58 | class Solution:
@cache
def countVowelPermutation(self, n: int) -> int:
prednums = {0: (1, 2, 4), 1: (0, 2), 2: (1, 3), 3: (2,), 4: (2, 3)}
result = [1, 1, 1, 1, 1]
for _ in range(n-1):
result = [sum(result[v] for v in prednums[j]) for j in range(5)]
return sum(result) % 1000000007 | count-vowels-permutation | 1220. Python3 one-liners: slow to 267ms/81.58% | leetavenger | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,413 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390243/1220.-Python3-one-liners%3A-slow-to-267ms81.58 | class Solution:
def countVowelPermutation(self, n: int) -> int:
r0 = r1 = r2 = r3 = r4 = 1;
for i in range(n-1):
r0, r1, r2, r3, r4 = r1+r2+r4,r0+r2,r1+r3,r2,r2+r3
return (r0+r1+r2+r3+r4) % 1000000007; | count-vowels-permutation | 1220. Python3 one-liners: slow to 267ms/81.58% | leetavenger | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,414 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390243/1220.-Python3-one-liners%3A-slow-to-267ms81.58 | class Solution:
def countVowelPermutation(self, n: int, a=1,b=1,c=1,d=1,e=1,m=10**9+7) -> int:
return (self.countVowelPermutation(n-1,(b+c+e)%m,(a+c)%m,(b+d)%m,c,(c+d)%m)
if n>1 else (a+b+c+d+e)%m) | count-vowels-permutation | 1220. Python3 one-liners: slow to 267ms/81.58% | leetavenger | 0 | 9 | count vowels permutation | 1,220 | 0.605 | Hard | 18,415 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390191/Simple-DP-or-Python3-or-O(n)-O(1) | class Solution:
def countVowelPermutation(self, n: int) -> int:
MOD = 10**9 + 7
d = (1,1,1,1,1)
for i in range(n - 1):
d = (
(d[1] + d[2] + d[4]) % MOD,
(d[0] + d[2]) % MOD,
(d[1] + d[3]) % MOD,
d[2] % MOD,
(d[2] + d[3]) % MOD,
)
return sum(d) % MOD | count-vowels-permutation | Simple DP | Python3 | O(n) O(1) | ritou11 | 0 | 30 | count vowels permutation | 1,220 | 0.605 | Hard | 18,416 |
https://leetcode.com/problems/count-vowels-permutation/discuss/2390141/Python3-DP | class Solution:
def countVowelPermutation(self, n: int) -> int:
# backtrack, evaluating all the rules
MOD = 10 ** 9 + 7
@lru_cache(maxsize=None)
def dfs(i, last):
if i == n:
return 1
if i > n:
return 0
available_chars = set(['a', 'e', 'i', 'o', 'u'])
if last == 'a':
available_chars = set(['e'])
if last == 'e':
available_chars = set(['a', 'i'])
if last == 'o':
available_chars = set(['i', 'u'])
if last == 'i' and 'i' in available_chars:
available_chars.remove('i')
if last == 'u':
available_chars = set(['a'])
total = 0
for c in list(available_chars):
total += dfs(i+1, c) % MOD
return total
ans = 0
available_chars = set(['a', 'e', 'i', 'o', 'u'])
for c in list(available_chars):
ans += dfs(1,c)
return ans % MOD | count-vowels-permutation | Python3 DP | roborovski | 0 | 12 | count vowels permutation | 1,220 | 0.605 | Hard | 18,417 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1315976/Python-time-O(n)-space-O(1)-120-ms-faster-than-81.70 | class Solution:
def countVowelPermutation(self, n: int) -> int:
# char - aeiou
# idx - 01234
count = [1] * 5
mod = 1000000007
for _ in range(n - 1):
count = [
(count[1] + count[2] + count[4]) % mod,
(count[0] + count[2]) % mod,
(count[1] + count[3]) % mod,
count[2] % mod,
(count[2] + count[3]) % mod
]
return sum(count) % mod | count-vowels-permutation | Python, time O(n), space O(1), 120 ms, faster than 81.70% | MihailP | 0 | 122 | count vowels permutation | 1,220 | 0.605 | Hard | 18,418 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1229851/python3-concise-DP-solution-with-time-O(n)-space-O(1) | class Solution:
def countVowelPermutation(self, n: int) -> int:
key = ['a', 'e', 'i', 'o', 'u']
h = {k: 1 for k in key}
while n > 1:
h['a'], h['e'], h['i'], h['o'], h['u'] = \
h['e'] + h['i'] + h['u'], h['a'] + h['i'], h['e'] + h['o'], h['i'], h['i'] + h['o']
n -= 1
return sum(list(h.values())) % (10 ** 9 + 7) | count-vowels-permutation | python3 concise DP solution with time O(n) space O(1) | savikx | 0 | 63 | count vowels permutation | 1,220 | 0.605 | Hard | 18,419 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1090226/Python3-top-down-and-bottom-up-dp | class Solution:
def countVowelPermutation(self, n: int) -> int:
@cache
def fn(n, c):
"""Return count of n vowels starting with c."""
if n == 1: return 1
if c == "a": return fn(n-1, "e")
elif c == "e": return fn(n-1, "a") + fn(n-1, "i")
elif c == "i": return fn(n-1, "a") + fn(n-1, "e") + fn(n-1, "o") + fn(n-1, "u")
elif c == "o": return fn(n-1, "i") + fn(n-1, "u")
else: return fn(n-1, "a")
return sum(fn(n, c) for c in "aeiou") % 1_000_000_007 | count-vowels-permutation | [Python3] top-down & bottom-up dp | ye15 | 0 | 197 | count vowels permutation | 1,220 | 0.605 | Hard | 18,420 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1090226/Python3-top-down-and-bottom-up-dp | class Solution:
def countVowelPermutation(self, n: int) -> int:
a = e = i = o = u = 1
for _ in range(n-1):
a, e, i, o, u = e+i+u, a+i, e+o, i, i+o
return (a+e+i+o+u) % 1_000_000_007 | count-vowels-permutation | [Python3] top-down & bottom-up dp | ye15 | 0 | 197 | count vowels permutation | 1,220 | 0.605 | Hard | 18,421 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1090226/Python3-top-down-and-bottom-up-dp | class Solution:
def countVowelPermutation(self, n: int) -> int:
a = e = i = o = u = 1
for _ in range(n-1):
a, e, i, o, u = e, a+i, a+e+o+u, i+u, a
return (a+e+i+o+u) % 1_000_000_007 | count-vowels-permutation | [Python3] top-down & bottom-up dp | ye15 | 0 | 197 | count vowels permutation | 1,220 | 0.605 | Hard | 18,422 |
https://leetcode.com/problems/count-vowels-permutation/discuss/1315340/Count-Vowel-Permutations-Most-easy-solution-97-speed-minimum-lines-of-codes | class Solution:
def countVowelPermutation(self, n: int) -> int:
a, e, i, o, u, MOD = 1, 1, 1, 1, 1, 10**9+7
for _ in range(n-1):
a, e, i, o, u = e, (a+i)%MOD, (a+e+o+u)%MOD, (i+u)%MOD, a
return sum([a, e, i, o, u])%MOD | count-vowels-permutation | Count Vowel Permutations Most easy solution ,97 % speed , minimum lines of codes | user8744WJ | -1 | 76 | count vowels permutation | 1,220 | 0.605 | Hard | 18,423 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403688/Python-3-(three-lines)-(beats-100.00-) | class Solution:
def balancedStringSplit(self, S: str) -> int:
m = c = 0
for s in S:
if s == 'L': c += 1
if s == 'R': c -= 1
if c == 0: m += 1
return m | split-a-string-in-balanced-strings | Python 3 (three lines) (beats 100.00 %) | junaidmansuri | 30 | 2,700 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,424 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403688/Python-3-(three-lines)-(beats-100.00-) | class Solution:
def balancedStringSplit(self, S: str) -> int:
m, c, D = 0, 0, {'L':1, 'R':-1}
for s in S: c, m = c + D[s], m + (c == 0)
return m
- Junaid Mansuri | split-a-string-in-balanced-strings | Python 3 (three lines) (beats 100.00 %) | junaidmansuri | 30 | 2,700 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,425 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/942608/Python-Easy-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
c=out=0
for i in s:
if i=='R':
c+=1
else:
c-=1
if c==0:
out+=1
return out | split-a-string-in-balanced-strings | Python Easy Solution | lokeshsenthilkumar | 7 | 634 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,426 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1202574/Python-easy-solution-Runtime-98.69-and-memory-90.53 | class Solution:
def balancedStringSplit(self, s: str) -> int:
ans =0
count = 0
for i in s:
if i=='R':
count+=1
else:
count-=1
if count==0:
ans +=1
return ans | split-a-string-in-balanced-strings | Python easy solution , Runtime 98.69% and memory 90.53% | malav_mevada | 5 | 177 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,427 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1706669/Python3-oror-easy-to-understand-oror-beginner-friendly | class Solution:
def balancedStringSplit(self, s: str) -> int:
count,amount=0,0
for i in s:
if i == "R":
count+=1
else:
count-=1
if count==0:
amount+=1
return amount | split-a-string-in-balanced-strings | Python3 || easy to understand || beginner friendly | Anilchouhan181 | 4 | 93 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,428 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1126796/WEEB-DOES-PYTHON(BEATS-94.47) | class Solution:
def balancedStringSplit(self, s: str) -> int:
r = l = 0
balanced = 0
for i in range(len(s)):
if s[i] == "R":
r+=1
else:
l+=1
if l == r:
balanced+=1
l = r = 0
return balanced | split-a-string-in-balanced-strings | WEEB DOES PYTHON(BEATS 94.47%) | Skywalker5423 | 4 | 297 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,429 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1241482/Python3-faster95-with-sum-of-boolean | class Solution:
def balancedStringSplit(self, s: str) -> int:
n = ans = 0
for c in s:
n += (c == "L") - (c == "R")
ans += n == 0
return ans | split-a-string-in-balanced-strings | Python3 faster95% with sum of boolean | albezx0 | 3 | 72 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,430 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2794169/Python3-O(N)-Stack-Greedy-Algorithm-Approach-beats-99.9 | class Solution:
def balancedStringSplit(self, s: str) -> int:
stack, result = [], 0
for char in s:
if stack == []:
stack.append(char)
result += 1
elif char == stack[-1]:
stack.append(char)
else:
# []
stack.pop()
return result | split-a-string-in-balanced-strings | Python3 O(N) - Stack Greedy Algorithm Approach beats 99.9% | MohammedAl-Rasheed | 2 | 101 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,431 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/927198/Faster-than-93.99-of-Python3-No-stack | class Solution:
def balancedStringSplit(self, s: str) -> int:
count=ch= 0
for x in s:
if x == 'R':
ch = ch+1
if x == 'L':
ch = ch-1
if ch == 0:
count = count+1
return count | split-a-string-in-balanced-strings | Faster than 93.99% of Python3, No stack | sgrdswl | 2 | 78 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,432 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2808381/Simple-Python-Solution-O(N)-time-beats-89 | class Solution:
def balancedStringSplit(self, s: str) -> int:
count = {
"L": 0,
"R": 0,
}
result = 0
for ch in s:
count[ch] += 1
if count['L'] == count['R']:
result += 1
return result | split-a-string-in-balanced-strings | Simple Python Solution O(N) time, beats 89% | roygarcia | 1 | 47 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,433 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2780858/Python-Hash-map-solution-using-dictionary | class Solution:
def balancedStringSplit(self, s: str) -> int:
ans = i = 0
while i < len(s):
d = {}
while not d or d.get('R') != d.get('L'): # while the substring isn't balanced
d[s[i]] = d.get(s[i], 0) + 1
i += 1
ans += 1
return ans | split-a-string-in-balanced-strings | [Python] Hash map solution using dictionary | Mark_computer | 1 | 7 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,434 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2010517/Python-easy-solution-for-beginners-using-one-tracking-variable | class Solution:
def balancedStringSplit(self, s: str) -> int:
flag = 0
res = 0
for i in s:
if i == "R":
flag += 1
elif i == "L":
flag -= 1
if flag == 0:
res += 1
return res | split-a-string-in-balanced-strings | Python easy solution for beginners using one tracking variable | alishak1999 | 1 | 107 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,435 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1701545/Simple-Python-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
var = const = 0
for i in s:
if i =="R":
var += 1
else:
var -= 1
if var == 0:
const += 1
return const | split-a-string-in-balanced-strings | Simple Python Solution | vijayvardhan6 | 1 | 144 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,436 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1396306/PYTHON-Explained-with-very-clear-and-verbose-comments.-Complexity-O(1) | class Solution:
def balancedStringSplit(self, s: str) -> int:
"""
Time complexity : O(n)
Space complexity : O(1)
The idea is simple.
1) Maintain three counters to count left, right, count value.
2) Start counting from the start of the string and count the no of left and right encountered.
3) When the left and right count equals , that means it can now be splitted.
4) So, instead of splitting and consuming extra memory , just increase the count
5) Return count
"""
rc = lc = cnt = 0
for i in s:
if i == 'R':
rc += 1
elif i == 'L':
lc += 1
if lc == rc:
cnt += 1
return cnt | split-a-string-in-balanced-strings | [PYTHON] Explained with very clear & verbose comments. Complexity O(1) | er1shivam | 1 | 99 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,437 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1312426/Python-Easy-to-understand-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
# If val = s[0] we increment counter by 1, else we decrement counter by 1
# Counter variable = 0 means we have found one split so we increment the "res" variable
val = s[0]
counter = 1 # To check for a valid split
res = 0 # To count the number of splits
for i in range(1, len(s)):
if s[i] == val:
counter += 1
else:
counter -= 1
if counter == 0:
res += 1
return res | split-a-string-in-balanced-strings | [Python] Easy to understand solution | mizan-ali | 1 | 128 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,438 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1300131/Easy-Fast-Python-Solution-(faster-than-99.20) | class Solution:
def balancedStringSplit(self, s: str) -> int:
s = list(s)
r_count = 0
l_count = 0
balanced = 0
for i in s:
if i == "R":
r_count += 1
elif i == "L":
l_count += 1
if r_count == l_count:
balanced += 1
return balanced | split-a-string-in-balanced-strings | Easy, Fast Python Solution (faster than 99.20%) | the_sky_high | 1 | 133 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,439 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/535861/Python3-(99.5)-Simple-example-with-description-and-commentary | class Solution:
def balancedStringSplit(self, s: str) -> int:
# Space: O(2) ~ O(1)
count, balance_count = 0, 0
# Time: O(s)
# Logic is each time count hits zero we have another balanced string.
# Critical to solve RLRRRLLRLL which isn't just an expansion of RL -> RRLL
# but RRR -2 LL +2 R -1 LL +2 for balance
for char in s:
if char == "R":
count -= 1
else:
count += 1
if count == 0:
balance_count += 1
return balance_count | split-a-string-in-balanced-strings | Python3 (99.5%) Simple example with description and commentary | dentedghost | 1 | 54 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,440 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/405186/Python-Efficient-and-Easy-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
balance = 0
count=0
d = {'R' : +1, 'L' : -1}
for i in range(len(s)):
balance+=d[s[i]]
if balance==0:
count+=1
return count | split-a-string-in-balanced-strings | Python Efficient and Easy Solution | saffi | 1 | 297 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,441 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2848456/Python3-Simple-Answer | class Solution:
def balancedStringSplit(self, s: str) -> int:
#set variables to count R & L
R, L, answer = 0, 0, 0
#loop through s, increment either R or L
for l in s:
if l == "R":
R += 1
else:
L += 1
#if L and R equal, reset & increment answer
if L == R:
answer +=1
R = 0
L = 0
return answer | split-a-string-in-balanced-strings | Python3 Simple Answer | mbmatthewbrennan | 0 | 1 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,442 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2832758/Python-Sliding-window | class Solution:
def balancedStringSplit(self, s: str) -> int:
left = 0
right = 0
map = {}
count = 0
while right < len(s):
c = s[right]
if c in map:
map[c] = map[c]+1
else:
map[c] =1
if 'R' in map and 'L' in map and map['R'] == map['L']:
count +=1
map.clear
right +=1
left = right
else:
right +=1
return count | split-a-string-in-balanced-strings | Python Sliding window | munenek | 0 | 2 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,443 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2806768/O(n)-python-easy-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
count = 0
right = 0
for i in s:
if i == "R":
right+=1
else:
right-=1
if not right:
count += 1
return count | split-a-string-in-balanced-strings | O(n) python easy solution | nikhilmatta | 0 | 2 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,444 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2770175/python-stack-easy-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
stack = []
res = 0
for i in s:
if len(stack) == 0:
stack.append(i)
elif stack[-1] == i:
stack.append(i)
else:
stack.pop()
if len(stack) == 0:
res += 1
return res | split-a-string-in-balanced-strings | python stack easy solution | muge_zhang | 0 | 1 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,445 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2750627/python-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
sum_balanced = 0
count = 0
for ch in s:
if ch == "R":
sum_balanced += 1
else:
sum_balanced -= 1
if sum_balanced == 0:
count += 1
return count | split-a-string-in-balanced-strings | python solution | samanehghafouri | 0 | 1 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,446 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2671754/Python-solution-easy-to-understanding | class Solution:
def balancedStringSplit(self, s: str) -> int:
ans, seen_l, seen_r = 0, 0, 0
for i in range(len(s)):
if s[i] == "L":
seen_l += 1
elif s[i] == "R":
seen_r += 1
if seen_r == seen_l:
seen_r, seen_l = 0, 0
ans += 1
return ans | split-a-string-in-balanced-strings | Python solution easy to understanding | phantran197 | 0 | 4 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,447 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2652437/Python3-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
i, k = 0, 2
count = 0
while i < len(s):
k = i + 2
while k <= len(s):
if s[i:k].count('R') == s[i:k].count('L'):
count += 1
i = k - 2
break
k += 2
i += 2
return count | split-a-string-in-balanced-strings | Python3 Solution | sipi09 | 0 | 3 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,448 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2467429/Python-Solution-or-O(N)-Time-and-O(1)-Space | class Solution:
def balancedStringSplit(self, s: str) -> int:
count = 0
bal = 0
for symbol in s:
if symbol == 'R':
bal += 1
else:
bal -= 1
if bal == 0:
count += 1
return count | split-a-string-in-balanced-strings | Python Solution | O(N) Time & O(1) Space | yash921 | 0 | 56 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,449 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2371453/Python3-Simple-or-Faster-than-97 | class Solution:
def balancedStringSplit(self, s: str) -> int:
res_dict = dict()
res_dict['R'], res_dict['L'] = 0, 0
res_count = 0
for el in s:
res_dict[el] += 1
if res_dict['R'] == res_dict['L']:
res_count += 1
res_dict['R'], res_dict['L'] = 0, 0
return res_count | split-a-string-in-balanced-strings | Python3 Simple | Faster than 97% | Sergei_Gusev | 0 | 32 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,450 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/2178685/Python-simple-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
ans = 0
p = 0
while s:
if s[:p].count('R') == s[:p].count('L') and s[:p].count('R') != 0 and s[:p].count('L') != 0:
ans += 1
s = s[p:]
p = 0
p += 1
return ans | split-a-string-in-balanced-strings | Python simple solution | StikS32 | 0 | 70 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,451 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1896062/python-3-oror-simple-solution-oror-O(n)O(1) | class Solution:
def balancedStringSplit(self, s: str) -> int:
left = right = res = 0
for c in s:
if c == 'L':
left += 1
else:
right += 1
if left and left == right:
left = right = 0
res += 1
return res | split-a-string-in-balanced-strings | python 3 || simple solution || O(n)/O(1) | dereky4 | 0 | 183 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,452 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1639753/Very-simple-python3-solution-(faster-than-95.62-and-memory-usage-less-than-99.77) | class Solution:
def balancedStringSplit(self, s: str) -> int:
count = 0
c = 0
for item in s:
if item == "R":
c += 1
if item == "L":
c -= 1
if c == 0:
count += 1
return count | split-a-string-in-balanced-strings | Very simple python3 solution (faster than 95.62% and memory usage less than 99.77%) | titanalpha | 0 | 41 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,453 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1308301/Python-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
ret, t = 0 , 0
for ch in s:
if ch == 'R':
t += 1
else:
t -= 1
if t == 0:
ret += 1
return ret | split-a-string-in-balanced-strings | Python Solution | 5tigerjelly | 0 | 71 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,454 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1299996/Easy-Python-Solution(99.20) | class Solution:
def balancedStringSplit(self, s: str) -> int:
c=0
g=0
x=''
for i in s:
if(c==0):
g+=1
x=i
c+=1
elif(i==x):
c+=1
else:
c-=1
return g | split-a-string-in-balanced-strings | Easy Python Solution(99.20%) | Sneh17029 | 0 | 506 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,455 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1238978/python3-easy-solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
x = list(s)
count = 0
k = 0
for i in x:
if i=='R':
count+=1
elif i=='L':
count-=1
if count==0:
k+=1
return k | split-a-string-in-balanced-strings | python3 easy solution | Sanyamx1x | 0 | 30 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,456 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1133523/Python-Simple-and-Easy-To-Understand-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
r=0
count=0
l=0
for i in s:
if i == 'R':
r+=1
else:
l+=1
if r==l:
count+=1
return count | split-a-string-in-balanced-strings | Python Simple & Easy To Understand Solution | saurabhkhurpe | 0 | 62 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,457 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/1025605/Python-code-using-data-structures | class Solution:
def balancedStringSplit(self, s: str) -> int:
top=-1
z=[]
c=0
for i in range(len(s)):
if len(z)==0:
z.append(s[i])
top+=1
elif z[top]==s[i] and len(z)!=0:
z.append(s[i])
top+=1
elif z[top]!=s[i]:
z.pop(top)
top-=1
if(len(z)==0):
c+=1
print(c)
return c | split-a-string-in-balanced-strings | Python code using data structures | coderash1998 | 0 | 50 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,458 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/836787/Python-3-28-ms-81.81-13.7-MB-90.47-Solution | class Solution:
def balancedStringSplit(self, s: str) -> int:
res = 0
subSum = 0
for i in s:
if i == 'L':
subSum += 1
else:
subSum -= 1
if subSum == 0:
res += 1
return res | split-a-string-in-balanced-strings | Python 3 28 ms 81.81% 13.7 MB 90.47% Solution | Skyfall2017 | 0 | 140 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,459 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/775032/Python3-Proof-of-O(N) | class Solution:
def balancedStringSplit(self, s: str) -> int:
ans = bal = 0
for c in s:
bal += 1 if c == 'R' else -1
if bal == 0:
ans += 1
return ans | split-a-string-in-balanced-strings | [Python3] Proof of O(N) | dsmyda | 0 | 65 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,460 |
https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403670/Python3-solution-with-stack-(28-ms-13.7-MB) | class Solution:
def balancedStringSplit(self, s: str) -> int:
stk = []
ret = 0
for ch in s:
if not stk: # begin
ret += 1 # in balance
stk.append(ch)
elif ch == stk[-1]: # continue
stk.append(ch)
else: # change direction
stk.pop()
return ret | split-a-string-in-balanced-strings | Python3 - solution with stack (28 ms, 13.7 MB) | coderr0r | 0 | 75 | split a string in balanced strings | 1,221 | 0.848 | Easy | 18,461 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/790679/Simple-Python-Solution | class Solution:
# Time: O(1)
# Space: O(1)
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
queen_set = {(i, j) for i, j in queens}
res = []
for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]]:
x, y = king[0], king[1]
while 0 <= x < 8 and 0 <= y < 8:
x += dx
y += dy
if (x, y) in queen_set:
res.append([x, y])
break
return res | queens-that-can-attack-the-king | Simple Python Solution | whissely | 5 | 397 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,462 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1090609/Python3-2-approaches | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
ans = []
x, y = king
queens = {(x, y) for x, y in queens}
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for k in range(1, 8):
xx, yy = x+k*dx, y+k*dy
if (xx, yy) in queens:
ans.append([xx, yy])
break
return ans | queens-that-can-attack-the-king | [Python3] 2 approaches | ye15 | 3 | 85 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,463 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1090609/Python3-2-approaches | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
ans = [[inf]*2 for _ in range(8)]
xx, yy = king
fn = lambda x: max(abs(x[0]-xx), abs(x[1]-yy))
for x, y in queens:
if x == xx: # same row
if y < yy: ans[0] = min(ans[0], (x, y), key=fn)
else: ans[1] = min(ans[1], (x, y), key=fn)
elif yy == y: # same column
if x < xx: ans[2] = min(ans[2], (x, y), key=fn)
else: ans[3] = min(ans[3], (x, y), key=fn)
elif xx-yy == x-y: # same diagonoal
if x < xx: ans[4] = min(ans[4], (x, y), key=fn)
else: ans[5] = min(ans[5], (x, y), key=fn)
elif xx+yy == x+y: # same anti-diagonal
if x < xx: ans[6] = min(ans[6], (x, y), key=fn)
else: ans[7] = min(ans[7], (x, y), key=fn)
return [[x, y] for x, y in ans if x < inf] | queens-that-can-attack-the-king | [Python3] 2 approaches | ye15 | 3 | 85 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,464 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1187262/python-3-solution-o(n)-time-2-loops | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
hashTable = {
"lu": [],
"uu": [],
"ru": [],
"rr": [],
"rb": [],
"bb": [],
"lb": [],
"ll": []
}
i,j = king
for qi, qj in queens:
#diagonal check
if abs(qi-i) == abs(qj-j):
# diagonal in upper half
if qi < i:
#diagonal in upper left quater
if qj < j:
#checking for minimum distance from king
if hashTable['lu']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['lu'])[0])+abs(j-(hashTable['lu'])[1])):
continue
else:
hashTable['lu'] = [qi,qj]
else:
hashTable['lu'] = [qi, qj]
continue
else:
if hashTable['ru']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['ru'])[0])+abs(j-(hashTable['ru'])[1])):
continue
else:
hashTable['ru'] = [qi,qj]
else:
hashTable['ru'] = [qi, qj]
continue
else:
if qj < j:
if hashTable['lb']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['lb'])[0])+abs(j-(hashTable['lb'])[1])):
continue
else:
hashTable['lb'] = [qi,qj]
else:
hashTable['lb'] = [qi, qj]
continue
else:
if hashTable['rb']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['rb'])[0])+abs(j-(hashTable['rb'])[1])):
continue
else:
hashTable['rb'] = [qi,qj]
else:
hashTable['rb'] = [qi, qj]
continue
# horizontal check
if qi == i:
if qj < j:
if hashTable['ll']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['ll'])[0])+abs(j-(hashTable['ll'])[1])):
continue
else:
hashTable['ll'] = [qi,qj]
else:
hashTable['ll'] = [qi, qj]
continue
else:
if hashTable['rr']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['rr'])[0])+abs(j-(hashTable['rr'])[1])):
continue
else:
hashTable['rr'] = [qi,qj]
else:
hashTable['rr'] = [qi, qj]
continue
# vertical check
if qj == j:
if qi < i:
if hashTable['uu']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['uu'])[0])+abs(j-(hashTable['uu'])[1])):
continue
else:
hashTable['uu'] = [qi,qj]
else:
hashTable['uu'] = [qi, qj]
continue
else:
if hashTable['bb']:
if (abs(i-qi)+abs(j-qj)) > (abs(i-(hashTable['bb'])[0])+abs(j-(hashTable['bb'])[1])):
continue
else:
hashTable['bb'] = [qi,qj]
else:
hashTable['bb'] = [qi, qj]
continue
ans= []
for value in hashTable.values():
if value:
ans.append(value)
return ans
``` | queens-that-can-attack-the-king | python 3 solution o(n) time, 2 loops | shubhbhardwaj | 1 | 101 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,465 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2835161/Python-easy-to-read-and-understanding-or-simulation | class Solution:
def move(self, matrix, row, col):
i, j = row-1, col
while i >= 0:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i -= 1
i, j = row-1, col-1
while i >= 0 and j >= 0:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i, j = i-1, j-1
i, j = row, col-1
while j >= 0:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
j -= 1
i, j = row+1, col-1
while i < 8 and j >= 0:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i, j = i+1, j-1
i, j = row+1, col
while i < 8:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i += 1
i, j = row+1, col+1
while i < 8 and j < 8:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i, j = i+1, j+1
i, j = row, col+1
while j < 8:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
j += 1
i, j = row-1, col+1
while i >= 0 and j < 8:
if matrix[i][j] == 'Q':
break
elif matrix[i][j] == 'K':
return True
else:
i, j = i-1, j+1
return False
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
res = []
matrix = [['0' for _ in range(8)] for _ in range(8)]
for i, j in queens:
matrix[i][j] = 'Q'
matrix[king[0]][king[1]] = 'K'
'''
for val in matrix:
print(val)
'''
for i, j in queens:
if self.move(matrix, i, j):
res.append([i, j])
return res | queens-that-can-attack-the-king | Python easy to read and understanding | simulation | sanial2001 | 0 | 2 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,466 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2801096/Python-3-10-lines-easy-to-understand | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
arr = []
drt = [[ 1, -1], [ 1, 0], [ 1, 1], \
[ 0, -1], [ 0, 1], \
[-1, -1], [-1, 0], [-1, 1]]
for dr_r, dr_c in drt:
r, c = king
while 0 <= r <= 7 and 0 <= c <= 7 :
if [r, c] in queens:
arr.append([r, c])
break
r, c = r + dr_r, c + dr_c
return arr | queens-that-can-attack-the-king | Python 3 - 10 lines - easy to understand | noob_in_prog | 0 | 4 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,467 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2575336/Python-or-Step-by-step-solution | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
queens = set((xq, yq) for xq, yq in queens)
xk, yk = king
res = deque()
for x in range(xk, 8): #move right
if (x, yk) in queens:
res.append([x,yk])
break
for x in range(xk, -1, -1): #move left
if (x, yk) in queens:
res.append([x,yk])
break
for y in range(yk, 8): #move up
if (xk, y) in queens:
res.append([xk, y])
break
for y in range(yk, -1, -1): #move down
if (xk, y) in queens:
res.append([xk, y])
break
for x, y in zip(range(xk, 8), range(yk, 8)): #move up right
if (x, y) in queens:
res.append([x, y])
break
for x, y in zip(range(xk, -1, -1), range(yk, 8)): #move up left
if (x, y) in queens:
res.append([x, y])
break
for x, y in zip(range(xk, 8), range(yk, -1, -1)): #move down right
if (x, y) in queens:
res.append([x, y])
break
for x, y in zip(range(xk, -1, -1), range(yk, -1, -1)): #move down left
if (x, y) in queens:
res.append([x, y])
break
return res | queens-that-can-attack-the-king | Python | Step by step solution | ahmadheshamzaki | 0 | 20 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,468 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2575336/Python-or-Step-by-step-solution | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
queens = set((xq, yq) for xq, yq in queens)
res = deque()
directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)]
for dx, dy in directions:
x, y = king
while 0 <= x < 8 and 0 <= y < 8:
x += dx
y += dy
if (x, y) in queens:
res.append([x, y])
break
return res | queens-that-can-attack-the-king | Python | Step by step solution | ahmadheshamzaki | 0 | 20 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,469 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2321215/PYTHON-or-O(1)-SOL-or-BEST-COMPLEXITY-or-ITERATIVE-or-CHECK-ALL-DIRECTION | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
ans = []
d = {(i[0],i[1]) : True for i in queens}
def goUp(r,c):
while r >=0:
if (r,c) in d:
ans.append([r,c])
break
r -= 1
def goDown(r,c):
while r < 8:
if (r,c) in d:
ans.append([r,c])
break
r += 1
def goLeft(r,c):
while c >= 0:
if (r,c) in d:
ans.append([r,c])
break
c -= 1
def goRight(r,c):
while c < 8:
if (r,c) in d:
ans.append([r,c])
break
c += 1
def goD1(r,c):
while r >=0 and c >= 0:
if (r,c) in d:
ans.append([r,c])
break
r -= 1
c -= 1
def goD2(r,c):
while r < 8 and c >= 0:
if (r,c) in d:
ans.append([r,c])
break
r += 1
c -= 1
def goD3(r,c):
while r < 8 and c < 8:
if (r,c) in d:
ans.append([r,c])
break
r += 1
c += 1
def goD4(r,c):
while r >= 0 and c < 8:
if (r,c) in d:
ans.append([r,c])
break
r -= 1
c += 1
goUp(king[0],king[1])
goDown(king[0],king[1])
goLeft(king[0],king[1])
goRight(king[0],king[1])
goD1(king[0],king[1])
goD2(king[0],king[1])
goD3(king[0],king[1])
goD4(king[0],king[1])
return ans | queens-that-can-attack-the-king | PYTHON | O(1) SOL | BEST COMPLEXITY | ITERATIVE | CHECK ALL DIRECTION | reaper_27 | 0 | 25 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,470 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/2128976/python-3-oror-build-the-board-and-check-each-direction | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
N = 8
board = [[''] * N for _ in range(N)]
for i, j in queens:
board[i][j] = 'Q'
res = []
ki, kj = king
directions = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1))
for di, dj in directions:
i, j = ki + di, kj + dj
while 0 <= i < N and 0 <= j < N:
if board[i][j] == 'Q':
res.append([i, j])
break
i += di
j += dj
return res | queens-that-can-attack-the-king | python 3 || build the board and check each direction | dereky4 | 0 | 35 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,471 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1430090/Python-Solution-2-Loops | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
setQueens = {(queen[0], queen[1]) for queen in queens}
attackQueens = []
directionMulti = [(-1,-1), (-1, 0), (0, -1), (0, 1), (1, 0), (-1, 1), (1, -1), (1, 1)]
for row_x, col_x in directionMulti:
for increment in range(1, 8):
row = king[0] + (row_x * increment)
col = king[1] + (col_x * increment)
if (row, col) in setQueens:
attackQueens.append([row, col])
break
return attackQueens | queens-that-can-attack-the-king | Python Solution 2 Loops | peatear-anthony | 0 | 108 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,472 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1204324/python-3-simple-solution-99-fast | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
i=king[0]
j=king[1]
p=i-1
l=[]
while(p>-1):
if([p,j] in queens):
l.append([p,j])
break
p=p-1
p=i+1
while(p<8):
if([p,j] in queens):
l.append([p,j])
break
p=p+1
p=j-1
while(p>-1):
if([i,p] in queens):
l.append([i,p])
break
p=p-1
p=j+1
while(p<8):
if([i,p] in queens):
l.append([i,p])
break
p=p+1
p=i-1
d=j-1
while(p>-1 and d>-1):
if([p,d] in queens):
l.append([p,d])
break
p=p-1
d=d-1
p=i-1
d=j+1
while(p>-1 and d<8):
if([p,d] in queens):
l.append([p,d])
break
p=p-1
d=d+1
p=i+1
d=j-1
while(p<8 and d>-1):
if([p,d] in queens):
l.append([p,d])
break
p=p+1
d=d-1
p=i+1
d=j+1
while(p<8 and d<8):
if([p,d] in queens):
l.append([p,d])
break
p=p+1
d=d+1
return l | queens-that-can-attack-the-king | python 3 simple solution 99% fast | Rajashekar_Booreddy | 0 | 122 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,473 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/1120865/Python-3-28-ms-faster-than-99.07 | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
queue = {"r":None,"l":None, "d":None,"u":None,"rd":None, "ld":None, "lu":None, "ru":None}
for v in queens:
if v[0] == king[0] and v[1] > king[1]:
if queue['r'] == None:
queue['r'] = v
elif v[1] < queue['r'][1]:
queue['r'] = v
elif "l" in queue and v[0] == king[0] and v[1] < king[1]:
if queue['l'] == None:
queue['l'] = v
elif v[1] > queue['l'][1]:
queue['l'] = v
elif "u" in queue and v[1] == king[1] and v[0] < king[0]:
if queue['u'] == None:
queue['u'] = v
elif v[0] > queue['u'][0]:
queue['u'] = v
elif "d" in queue and v[1] == king[1] and v[0] > king[0]:
if queue['d'] == None:
queue['d'] = v
elif v[0] < queue['d'][0]:
queue['d'] = v
elif "rd" in queue and v[0] - v[1] == king[0] - king[1] and v[0] > king[0]:
if queue['rd'] == None:
queue['rd'] = v
elif v[0] < queue['rd'][0]:
queue['rd'] = v
elif "ru" in queue and v[0] - v[1] == king[0] - king[1] and v[0] < king[0]:
if queue['ru'] == None:
queue['ru'] = v
elif v[0] > queue['ru'][0]:
queue['ru'] = v
elif "ld" in queue and v[0] + v[1] == king[0] + king[1] and v[0] > king[0]:
if queue['ld'] == None:
queue['ld'] = v
elif v[0] < queue['ld'][0]:
queue['ld'] = v
elif "lu" in queue and v[0] + v[1] == king[0] + king[1] and v[0] < king[0]:
if queue['lu'] == None:
queue['lu'] = v
elif v[0] > queue['lu'][0]:
queue['lu'] = v
return [queue[x] for x in queue if queue[x] != None] | queens-that-can-attack-the-king | Python 3 28 ms, faster than 99.07% | whoareyouimthanh | 0 | 79 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,474 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/972064/Python-Simple-Solution | class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
d=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]
queen={tuple(i) for i in queens}
res=[]
for i,j in d:
r,c=king
while 0<=r+i<8 and 0<=c+j<8:
r+=i
c+=j
if (r,c) in queen:
res.append([r,c])
break
return res | queens-that-can-attack-the-king | Python Simple Solution | Umadevi_R | 0 | 55 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,475 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/403742/Two-Solutions-in-Python-3-(four-lines)-(beats-100.00-) | class Solution:
def queensAttacktheKing(self, Q: List[List[int]], K: List[int]) -> List[List[int]]:
[I, J], A, S, T = K, [0]*9, set(itertools.product(range(8),range(8))), [(i,j) for i,j in itertools.product(range(-1,2),range(-1,2))]
for i,(j,(a,b)) in itertools.product(range(1,8),enumerate(T)):
if not A[j] and (I+i*a,J+i*b) in S and [I+i*a,J+i*b] in Q: A[j] = (I+i*a,J+i*b)
return [p for p in A if p != 0] | queens-that-can-attack-the-king | Two Solutions in Python 3 (four lines) (beats 100.00 %) | junaidmansuri | -1 | 159 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,476 |
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/403742/Two-Solutions-in-Python-3-(four-lines)-(beats-100.00-) | class Solution:
def queensAttacktheKing(self, Q: List[List[int]], K: List[int]) -> List[List[int]]:
[I, J], A = K, []
for e,d in enumerate([I,J]):
for a,b,c in (d-1,-1,-1),(d+1,8,1):
for i in range(a,b,c):
p = [i,J] if e == 0 else [I,i]
if p in Q:
A.append(p)
break
for d in [1,-1]:
for a,b,c in (J-1,-1,-1),(J+1,8,1):
for j in range(a,b,c):
if I+d*(J-j) < 8 and [I+d*(J-j),j] in Q:
A.append([I+d*(J-j),j])
break
return A
- Junaid Mansuri | queens-that-can-attack-the-king | Two Solutions in Python 3 (four lines) (beats 100.00 %) | junaidmansuri | -1 | 159 | queens that can attack the king | 1,222 | 0.718 | Medium | 18,477 |
https://leetcode.com/problems/dice-roll-simulation/discuss/1505338/Python-or-Intuitive-or-Recursion-%2B-Memo-or-Explanation | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
MOD = 10 ** 9 + 7
@lru_cache(None)
def func(idx, prevNum, prevNumFreq):
if idx == n:
return 1
ans = 0
for i in range(1, 7):
if i == prevNum:
if prevNumFreq < rollMax[i - 1]:
ans += func(idx + 1, i, prevNumFreq + 1)
else:
ans += func(idx + 1, i, 1)
return ans % MOD
return func(0, 0, 0) | dice-roll-simulation | Python | Intuitive | Recursion + Memo | Explanation | detective_dp | 2 | 267 | dice roll simulation | 1,223 | 0.484 | Hard | 18,478 |
https://leetcode.com/problems/dice-roll-simulation/discuss/1090568/Python3-top-down-dp | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
@cache
def fn(n, x, r):
"""Return number of sequences with n rolls left with r occurrences of x."""
if n == 0: return 1
ans = 0
for xx in range(6):
if xx != x: ans += fn(n-1, xx, 1)
elif xx == x and r < rollMax[x]: ans += fn(n-1, x, r+1)
return ans
return sum(fn(n-1, x, 1) for x in range(6)) % 1_000_000_007 | dice-roll-simulation | [Python3] top-down dp | ye15 | 1 | 165 | dice roll simulation | 1,223 | 0.484 | Hard | 18,479 |
https://leetcode.com/problems/dice-roll-simulation/discuss/833495/Python-3-or-DFS-%2B-Memoization-or-Explanation | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
@lru_cache(maxsize=None)
def dfs(n, i, k):
if not n: return 1
ans = 0
for j in range(6):
if i != j: ans += dfs(n-1, j, 1)
elif k+1 <= rollMax[j]: ans += dfs(n-1, j, k+1)
return ans
return sum(dfs(n-1, i, 1) for i in range(6)) % 1000000007 | dice-roll-simulation | Python 3 | DFS + Memoization | Explanation | idontknoooo | 1 | 385 | dice roll simulation | 1,223 | 0.484 | Hard | 18,480 |
https://leetcode.com/problems/dice-roll-simulation/discuss/2321446/PYTHON-or-RECURSION-%2B-MEMOIZATION-or-FULL-EXPLANATION-or-EASY-or-DP-or | class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
dp = {}
def solve(n,last,count):
if n == 0: return 1
if (n,last,count) in dp: return dp[(n,last,count)]
ans = 0
for i in range(6):
if last == i:
if count == rollMax[i]: continue
ans += solve(n-1,last,count + 1)
else:
ans += solve(n-1,i,1)
dp[(n,last,count)] = ans
return ans
return solve(n,None,0) % 1000000007 | dice-roll-simulation | PYTHON | RECURSION + MEMOIZATION | FULL EXPLANATION | EASY | DP | | reaper_27 | 0 | 76 | dice roll simulation | 1,223 | 0.484 | Hard | 18,481 |
https://leetcode.com/problems/dice-roll-simulation/discuss/403984/Two-Solutions-in-Python-3-(DP-and-DFS-w-Memo) | class Solution:
def dieSimulator(self, n: int, R: List[int]) -> int:
DP, S, m = [[1]+[0]*(i-1) for i in R], [0]*6, 10**9 + 7
for _ in range(1,n):
for j in range(6): S[j], _ = sum(DP[j]), DP[j].pop()
for j in range(6): DP[j] = [sum(S) - S[j]] + DP[j]
return sum(sum(DP,[])) % m | dice-roll-simulation | Two Solutions in Python 3 (DP and DFS w/ Memo) | junaidmansuri | 0 | 408 | dice roll simulation | 1,223 | 0.484 | Hard | 18,482 |
https://leetcode.com/problems/dice-roll-simulation/discuss/403984/Two-Solutions-in-Python-3-(DP-and-DFS-w-Memo) | class Solution:
def dieSimulator(self, n: int, R: List[int]) -> int:
D, R, S, m = [[0]*7 for _ in range(n)], [0]+R, set(range(1,7)), 10**9 + 7
def dfs(L, d):
if L >= n: return 1 if L == n else 0
c = 0
if D[L][d]: return D[L][d]
for i in S-{d}:
for j in range(1,R[i]+1): c += dfs(L+j,i)
D[L][d] = c
return c
return dfs(0,0) % m
- Junaid Mansuri | dice-roll-simulation | Two Solutions in Python 3 (DP and DFS w/ Memo) | junaidmansuri | 0 | 408 | dice roll simulation | 1,223 | 0.484 | Hard | 18,483 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/2448664/Python-easy-to-read-and-understand-or-hash-table | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
cnt, freq, maxfreq, ans = collections.defaultdict(int), collections.defaultdict(int), 0, 0
for i, num in enumerate(nums):
cnt[num] = cnt.get(num, 0) + 1
freq[cnt[num]] += 1
freq[cnt[num]-1] -= 1
maxfreq = max(maxfreq, cnt[num])
if maxfreq == 1:
ans = i+1
elif maxfreq*freq[maxfreq] == i:
ans = i+1
elif (maxfreq-1)*(freq[maxfreq-1]+1) == i:
ans = i+1
return ans | maximum-equal-frequency | Python easy to read and understand | hash table | sanial2001 | 1 | 73 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,484 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/2328039/PYTHON-or-HASHMAP-or-EXPLAINED-or-WELL-COMMENTED-or-EASY-or-DETAILED-EXPLANATION | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
ans = 0
n = len(nums)
countToFreq = defaultdict(int)
# key = count value = Freq ex 2 occured 3 times in nums so 2 : 3
freqToCount = defaultdict(int)
# key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3
for i,val in enumerate(nums):
x = countToFreq[val] + 1
freqToCount[x - 1] -= 1
if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)
freqToCount[x] += 1
countToFreq[val] = x
# if a single item is repeated for i + 1 times like [1,1,1]
if countToFreq[val] == i + 1 :ans = i + 1
# if all items are having same frequency like [2,2,1,1,3,3]
elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1
# if all items have same frequency except one having 1 freq like [2,2,3,3,1]
elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1
# if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]
elif len(freqToCount) == 2:
keys,values = [],[]
for j in freqToCount:keys.append(j) , values.append(freqToCount[j])
if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1
return ans | maximum-equal-frequency | PYTHON | HASHMAP | EXPLAINED | WELL COMMENTED | EASY | DETAILED EXPLANATION | reaper_27 | 0 | 62 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,485 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/1871711/Python-O(N)-Frequency-Count-with-explanation | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
longest = 0
charToFreq = defaultdict(int)
freqToChars = defaultdict(int)
for i, c in enumerate(nums):
freq = charToFreq[c]
if freq in freqToChars:
freqToChars[freq] -= 1
if freqToChars[freq] == 0:
del freqToChars[freq]
freqToChars[freq+1] += 1
charToFreq[c] += 1
if self.isValid(freqToChars):
longest = i+1
return longest
# Four valid cases:
# 1. All numbers have frequency of 1 => {1 : n}
# 2. There's only a single number k => {n : 1}
# 3. All but one numbers have the same frequency and the odd one is an singleton
# => {1 : 1, someFreq : k}
# 4. All but one numbers have the same frequency and the odd one has a frequency of exactly 1 higher
# => {maxFreq : 1, (maxFreq-1) : k}
def isValid(self, freqToChars):
numKeys = len(freqToChars.keys())
if numKeys == 1:
firstKey = list(freqToChars.keys())[0]
# all have freq of 1 or there's only a single char
return firstKey == 1 or freqToChars[firstKey] == 1
if numKeys > 2:
return False
entries = sorted(list(freqToChars.items()))
singleton = entries[0][0] == 1 and entries[0][1] == 1
freqDiffOne = entries[1][0] - entries[0][0] == 1
higherSingleton = entries[1][1] == 1
return singleton or (higherSingleton and freqDiffOne) | maximum-equal-frequency | Python O(N) - Frequency Count with explanation | oyqian | 0 | 95 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,486 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/1090614/Python3-freq-table-of-freq-table | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
ans = most = 0
cnt = defaultdict(int)
freq = defaultdict(int)
for i, x in enumerate(nums):
cnt[x] += 1
freq[cnt[x]-1] -= 1
freq[cnt[x]] += 1
most = max(most, cnt[x])
if most == 1 or most * freq[most] == i or (most-1)*freq[most-1] + most == i+1: ans = i+1
return ans | maximum-equal-frequency | [Python3] freq table of freq table | ye15 | 0 | 161 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,487 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/1090614/Python3-freq-table-of-freq-table | class Solution:
def maxEqualFreq(self, nums: List[int]) -> int:
ans = 0
cnt, freq = {}, {}
for i, x in enumerate(nums):
if x in cnt and cnt[x] in freq:
freq[cnt[x]] -= 1
if not freq[cnt[x]]: freq.pop(cnt[x])
cnt[x] = 1 + cnt.get(x, 0)
freq[cnt[x]] = 1 + freq.get(cnt[x], 0)
if len(freq) == 1 and (1 in freq or 1 in freq.values()): ans = i+1
elif len(freq) == 2 and (freq.get(1, 0) == 1 or freq.get(1+min(freq), 0) == 1): ans = i+1
return ans | maximum-equal-frequency | [Python3] freq table of freq table | ye15 | 0 | 161 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,488 |
https://leetcode.com/problems/maximum-equal-frequency/discuss/403834/Python-3-(ten-lines)-(beats-100.00-) | class Solution:
def maxEqualFreq(self, N: List[int]) -> int:
L, C = len(N), collections.Counter(N)
for i in range(L-1,-1,-1):
S = set(C.values())
if len(C.values()) == 1 or S == {1}: return i + 1
elif len(S) == 2:
if 1 in S and list(C.values()).count(1) == 1: return i + 1
if list(C.values()).count(max(S)) == 1 and max(S) - min(S) == 1: return i + 1
if C[N[i]] == 1: del C[N[i]]
else: C[N[i]] -= 1
return 0
- Junaid Mansuri | maximum-equal-frequency | Python 3 (ten lines) (beats 100.00 %) | junaidmansuri | 0 | 159 | maximum equal frequency | 1,224 | 0.371 | Hard | 18,489 |
https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/530102/Python3-symmetry | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 if n == 1 else 0.5 | airplane-seat-assignment-probability | [Python3] symmetry | ye15 | 1 | 139 | airplane seat assignment probability | 1,227 | 0.649 | Medium | 18,490 |
https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/530102/Python3-symmetry | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
s = 1
for i in range(2, n):
s += s/i
return s/n | airplane-seat-assignment-probability | [Python3] symmetry | ye15 | 1 | 139 | airplane seat assignment probability | 1,227 | 0.649 | Medium | 18,491 |
https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/2542437/easy-python-solution | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
return 1 if n == 1 else 1/2 | airplane-seat-assignment-probability | easy python solution | sghorai | 0 | 38 | airplane seat assignment probability | 1,227 | 0.649 | Medium | 18,492 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1247752/Python3-simple-solution | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for x, y in coordinates[2:]:
if (y2 - y1) * (x - x1) != (x2 - x1) * (y - y1):
return False
return True | check-if-it-is-a-straight-line | Python3 simple solution | EklavyaJoshi | 6 | 176 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,493 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2126422/Memory-Usage%3A-14.3-MB-less-than-98.84-of-Python3 | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x0, y0 = coordinates[0]
x1, y1 = coordinates[1]
dy = y1 - y0
dx = x1 - x0
for i in range(len(coordinates)):
x = coordinates[i][0]
y = coordinates[i][1]
if dx*(y - y1) != dy*(x - x1):
return False
else:
return True | check-if-it-is-a-straight-line | Memory Usage: 14.3 MB, less than 98.84% of Python3 | writemeom | 3 | 165 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,494 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2797413/lesspythongreater-Easy-Solution..!!! | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
slope =0
for i in range(len(coordinates)-1):
x1,y1=coordinates[i]
x2,y2=coordinates[i+1]
if x2-x1==0:
#vertical line #m=slope
m=float('inf')
else:
m=(y2-y1)/(x2-x1)
if slope==0:
slope=m
else :
if slope!=m:
return False
return True | check-if-it-is-a-straight-line | <python> Easy Solution..!!! | user9516zM | 2 | 181 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,495 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2182930/Python-Simple-Python-Solution-using-Slope-Concept | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
dy = (coordinates[1][1]-coordinates[0][1])
dx = (coordinates[1][0]-coordinates[0][0])
for i in range(1,len(coordinates)-1):
next_dy = (coordinates[i+1][1]-coordinates[i][1])
next_dx = (coordinates[i+1][0]-coordinates[i][0])
if dy * next_dx != dx * next_dy:
return False
return True | check-if-it-is-a-straight-line | [ Python ] ✅✅ Simple Python Solution using Slope Concept 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 2 | 145 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,496 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/621111/python-solution-O(n)-56ms-and-100less-memory | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
(x1, y1), (x2, y2) = coordinates[:2]
if len(coordinates)==2:
return True
for i in range(2, len(coordinates)):
(x, y) = coordinates[i]
if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)):
return False
return True | check-if-it-is-a-straight-line | python solution O(n) 56ms and 100%less memory | rajivjhon2 | 2 | 143 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,497 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/432076/Python-simple-solution-100-100 | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
try: # general case
return len(set([(coordinates[i+1][1] - coordinates[i][1]) / (coordinates[i+1][0] - coordinates[i][0]) for i in range(len(coordinates) - 1)])) == 1
except: # check vertical line
return len(set([(coordinates[i+1][0] - coordinates[i][0]) for i in range(len(coordinates) - 1)])) == 1 | check-if-it-is-a-straight-line | Python simple solution 100% 100% | tliu77 | 1 | 267 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,498 |
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2838419/Python3-solution-with-time-complexity-77ms-Beginner-friendly | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
slope = list()
for i in range(len(coordinates)-1):
if not (coordinates[i+1][0] == coordinates[i][0]):
slope.append((coordinates[i+1][1] - coordinates[i][1])/(coordinates[i+1][0] - coordinates[i][0]))
else:
slope.append(None)
if len(set(slope)) <= 1:
return True
else:
return False | check-if-it-is-a-straight-line | Python3 solution with time complexity 77ms - Beginner friendly | amal-being | 0 | 1 | check if it is a straight line | 1,232 | 0.41 | Easy | 18,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.