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/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/1124073/Python3-greedy-(and-binary-search) | class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fibo = [1]
f0 = f1 = 1
while f1 < k:
f0, f1 = f1, f0+f1
fibo.append(f1)
ans = 0
while k:
ans += 1
i = bisect_right(fibo, k) - 1
k -= fibo[i... | find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k | [Python3] greedy (& binary search) | ye15 | 0 | 110 | find the minimum number of fibonacci numbers whose sum is k | 1,414 | 0.654 | Medium | 21,200 |
https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/597237/Easy-Python-Solution-Runtime-32-ms-faster-than-91-submissions | class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
m= [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 2415781... | find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k | Easy Python Solution Runtime-32 ms faster than 91% submissions | Ayu-99 | 0 | 122 | find the minimum number of fibonacci numbers whose sum is k | 1,414 | 0.654 | Medium | 21,201 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1420200/Python3-or-Ez-for-loop-solves-ALL!-With-detailed-comments-and-graphical-examples | class Solution:
def getHappyString(self, n: int, k: int) -> str:
char = ["a", "b", "c"]
# Edge case, n = 1
if n == 1: return char[k - 1] if k <= 3 else ""
# There will be $part$ number of strings starting with each character (a, b, c)
part = 2 ** ... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python3 | Ez for loop solves ALL! With detailed comments and graphical examples | caffreyu | 2 | 73 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,202 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1528146/easy-to-understand | class Solution:
def helper(self,s , l , letters , n ):
if(len(s) == n):
l.append(s)
return 0
for i in letters :
if(s[-1] != i ):
self.helper(s + i , l , letters , n)
def getHappyString(self, n: int, k: int) ->... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | easy to understand | MB16biwas | 1 | 71 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,203 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1474243/Python-3-oror-backtracking-oror-Self-explanatory-oror-Easy-Understading | class Solution:
def getHappyString(self, n: int, k: int) -> str:
res=[]
inp_string=['a','b','c']
def happy_string(index,string):
if len(string)==n:
res.append(string)
return
for i in range(len(inp_string)):
if len(st... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python 3 || backtracking || Self-explanatory || Easy-Understading | bug_buster | 1 | 74 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,204 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/2823645/python-oror-math-oror-time-O(n) | class Solution:
def getHappyString(self, n: int, k: int) -> str:
total = 3 * 2 ** (n - 1)
if k > total:
return ""
k -= 1
ret = ""
for i in range(n):
if i:
total //= 2
d = k // total + ord("a")
... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | python || math || time O(n) | Aaron1991 | 0 | 2 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,205 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/2657738/Python-or-Backtracking-solution | class Solution:
def getHappyString(self, n: int, k: int) -> str:
answer = []
alphabets = ['a','b','c']
def dfs(alphabets,n,s):
if len(s) == n:
answer.append(s)
return
for x in alphabets:
if s and s[-1] == x:
... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python | Backtracking solution | wjs2063 | 0 | 3 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,206 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/2494412/Python-Solution-or-Recursive-BackTracking-Based-or-Two-Ways-Iterative-and-Manual | class Solution:
# manual hard work way
def getHappyString(self, n: int, k: int) -> str:
store = ['a','b','c']
def traverse(curr,ans):
if len(curr) == n:
ans.append(curr[:])
return
# empty string case
if curr =... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python Solution | Recursive - BackTracking Based | Two Ways - Iterative and Manual | Gautam_ProMax | 0 | 26 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,207 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/2492478/Python-(Simple-Solution-and-Beginner-Friendly) | class Solution:
def getHappyString(self, n: int, k: int) -> str:
letters = ["a", "b", "c"]
res = []
self.backtrack(res, letters, n, k, [])
if len(res) >= k:
return res[k-1]
else:
return""
def backtrack(self,res, letters, n, k, curr):
if n... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python (Simple Solution and Beginner-Friendly) | vishvavariya | 0 | 18 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,208 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/2459522/Python3-or-Recursion-%2B-Backtracking | class Solution:
def getHappyString(self, n: int, k: int) -> str:
#Approach: Utilize recursion + backtracking!
#Recursively generate all n happy strings and add that to answer!
#Once we generate all, sort the list and return kth string!
ans = []
#3 parameters: cur -> ... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python3 | Recursion + Backtracking | JOON1234 | 0 | 6 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,209 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1744863/Runtime%3A-39-ms-faster-than-88.65-of-Python3-Memory-Usage%3A-13.9-MB-less-than-99.46 | class Solution:
def getHappyString(self, n: int, k: int) -> str:
# s = "abc"
self.res = ""
self.count = 0
self.lock = False
def solve(com):
# print(com,self.count)
if(len(com) == n):
self.count = self.count + 1
if(self.count == k):
self.res = com
self.lock = True
return
for i i... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Runtime: 39 ms, faster than 88.65% of Python3 Memory Usage: 13.9 MB, less than 99.46% | jagdishpawar8105 | 0 | 25 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,210 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1698073/Python-3-Iterative-based-on-observation | class Solution:
def getHappyString(self, n: int, k: int) -> str:
a, b, c = ['a'], ['b'], ['c']
for i in range(n-1):
t_a, t_b, t_c = a[::], b[::], c[::]
a, b, c = [], [], []
help_a = t_b + t_c
for j in range(len(help_a)):
a.append('a'+he... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python 3] Iterative based on observation | sanial2001 | 0 | 35 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,211 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1581517/Python3-Backtracking-solution | class Solution:
def __init__(self):
self.number = 0
def backtracking(self, seq, cur_seq, n, k):
if len(cur_seq) == n:
self.number += 1
if self.number == k:
return cur_seq
return []
for c in seq:
... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python3] Backtracking solution | maosipov11 | 0 | 30 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,212 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1389407/Python-3-Backtracking-My-solution | class Solution:
def getHappyString(self, n: int, k: int) -> str:
res = []
self.happyHelper(n,"",["a","b","c"],res)
return res[k-1] if k-1 <len(res) else ""
def happyHelper(self,n,s,happy,res):
if n == len(s):
res.append(s)
else:
for i in ... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python 3 - Backtracking - My solution | anja_2299 | 0 | 57 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,213 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1289004/Python3-solution-using-recursion | class Solution:
def getHappyString(self, n: int, k: int) -> str:
def make(a,s,n,k,res):
a = ['a', 'b', 'c']
if len(res) == k:
return
if len(s) == n:
res.append(s)
return
for i in range(len(a)):
if... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python3 solution using recursion | EklavyaJoshi | 0 | 43 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,214 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1286275/Python-3-recursive-generator-by-dfs-or-memory-less-98.1 | class Solution:
def getHappyString(self, n: int, k: int) -> str:
alpha = ('a', 'b', 'c')
def dfs(string):
if len(string) == n:
yield string
else:
for ch in alpha:
if len(string) == 0 or ch != string[-1]:
... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python 3 recursive generator by dfs | memory less 98.1% | CiFFiRO | 0 | 33 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,215 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1124098/Python3-modulo | class Solution:
def getHappyString(self, n: int, k: int) -> str:
k -= 1
if 3*2**(n-1) <= k: return "" # impossible
mp = {"": "abc", "a": "bc", "b": "ac", "c": "ab"}
ans = [""]
for i in range(n):
q, k = divmod(k, 2**(n-i-1))
ans.append(mp[ans[... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python3] modulo | ye15 | 0 | 43 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,216 |
https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/639986/Intuitive-approach-by-using-generator-to-produce-happy-string | class Solution:
def getHappyString(self, n: int, k: int) -> str:
def get_hs(n):
''' get happy string for length=`n`'''
def _gen_of_hs(hs, n=n):
''' generator of happy string'''
if len(hs) == n:
yield hs
else:
... | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Intuitive approach by using generator to produce happy string | puremonkey2001 | 0 | 33 | the k th lexicographical string of all happy strings of length n | 1,415 | 0.721 | Medium | 21,217 |
https://leetcode.com/problems/restore-the-array/discuss/1165871/python-or-simple-dp | class Solution(object):
def numberOfArrays(self, s, k):
n=len(s)
new=[0]*n
new[0]=1
m=len(str(k))
for i in range(1,n):
for j in range(max(0,i-m+1),i+1):
if s[j]!="0" and int(s[j:i+1])<=k:
if j==0:
new[i]=... | restore-the-array | python | simple dp | heisenbarg | 1 | 185 | restore the array | 1,416 | 0.388 | Hard | 21,218 |
https://leetcode.com/problems/restore-the-array/discuss/1124168/Python3-bottom-up-dp-w-sliding-window | class Solution:
def numberOfArrays(self, s: str, k: int) -> int:
dp = [0]*(len(s)+1)
dp[-1] = sm = 1
ii = len(s)
for i in reversed(range(len(s))):
if s[i] != "0":
while ii - i - 1 > log10(k) or int(s[i:ii]) > k:
sm = (sm - ... | restore-the-array | [Python3] bottom-up dp w/ sliding window | ye15 | 1 | 107 | restore the array | 1,416 | 0.388 | Hard | 21,219 |
https://leetcode.com/problems/reformat-the-string/discuss/1863653/Python3-Solution | class Solution:
def reformat(self, s: str) -> str:
nums, chars = [], []
[(chars, nums)[char.isdigit()].append(str(char)) for char in s]
nums_len, chars_len = len(nums), len(chars)
if 2 > nums_len - chars_len > -2:
a, b = ((chars, nums), (nums, chars))[nums_len > chars_len... | reformat-the-string | Python3 Solution | hgalytoby | 1 | 62 | reformat the string | 1,417 | 0.556 | Easy | 21,220 |
https://leetcode.com/problems/reformat-the-string/discuss/1601659/Using-itertools.zip_longest-(Python-3) | class Solution:
def reformat(self, s: str) -> str:
nums = [c for c in s if c.isnumeric()]
alph = [c for c in s if c.isalpha()]
if abs(len(nums) - len(alph)) > 1:
return ''
a, b = (nums, alph) if len(nums) <= len(alph) else (alph, nums)
re... | reformat-the-string | Using itertools.zip_longest (Python 3) | emwalker | 1 | 23 | reformat the string | 1,417 | 0.556 | Easy | 21,221 |
https://leetcode.com/problems/reformat-the-string/discuss/2747417/Python-3-Solution | class Solution:
def reformat(self, s: str) -> str:
numbers = [c for c in s if c.isdigit()]
letters = [c for c in s if c.isalpha()]
diff = abs(len(numbers) - len(letters))
if diff > 1:
return ''
if diff == 0:
return ''.join([item for p... | reformat-the-string | Python 3 Solution | bettend | 0 | 4 | reformat the string | 1,417 | 0.556 | Easy | 21,222 |
https://leetcode.com/problems/reformat-the-string/discuss/2747290/Python3-One-Pass-No-Space-other-than-Solution | class Solution:
def reformat(self, s: str) -> str:
# make a solution
n = len(s)
sol = [""]*(n+1)
nr_pointer = 0
chr_pointer = 1
for char in s:
if char.isdigit():
if nr_pointer >= n:
return ""
sol[nr_poin... | reformat-the-string | [Python3] - One-Pass - No Space other than Solution | Lucew | 0 | 5 | reformat the string | 1,417 | 0.556 | Easy | 21,223 |
https://leetcode.com/problems/reformat-the-string/discuss/2523885/Short-python-zip_longest | class Solution:
def reformat(self, s: str) -> str:
x = [c for c in s if c.isalpha()]
y = [c for c in s if c.isdigit()]
if len(x) < len(y):
x, y = y, x
if len(x) == len(y) or len(y) + 1 == len(x):
return "".join(f"{x}{y}" for x, y in zip_longest(x, y, fillvalue... | reformat-the-string | Short python zip_longest | dima62 | 0 | 26 | reformat the string | 1,417 | 0.556 | Easy | 21,224 |
https://leetcode.com/problems/reformat-the-string/discuss/2468263/Python-for-beginners | class Solution:
def reformat(self, s: str) -> str:
#Simple Approach
#Lengthy code but faster than 99.03%
#Runtime: 36ms
num1,alp2=[],[]
output=""
for i in s:
if i.isdigit():
num1.append(i) #appending digits in num1
... | reformat-the-string | Python for beginners | mehtay037 | 0 | 37 | reformat the string | 1,417 | 0.556 | Easy | 21,225 |
https://leetcode.com/problems/reformat-the-string/discuss/2468263/Python-for-beginners | class Solution:
def reformat(self, s: str)->str:
a, b = [], []
for c in s:
if 'a' <= c <= 'z':
a.append(c)
else:
b.append(c)
if len(a) < len(b):
a, b = b, a
if len(a) - len(b) >= 2:
return ''
ans = '... | reformat-the-string | Python for beginners | mehtay037 | 0 | 37 | reformat the string | 1,417 | 0.556 | Easy | 21,226 |
https://leetcode.com/problems/reformat-the-string/discuss/2119629/Python-Solution | class Solution:
def reformat(self, s: str) -> str:
a = []
b = []
for i in s:
if i.isdigit():
a.append(i)
else:
b.append(i)
string = ""
if len(a) < len(b):
a, b = b , a
k,l = ... | reformat-the-string | Python Solution | prernaarora221 | 0 | 65 | reformat the string | 1,417 | 0.556 | Easy | 21,227 |
https://leetcode.com/problems/reformat-the-string/discuss/2112547/python-3-oror-simple-solution-without-extra-space | class Solution:
def reformat(self, s: str) -> str:
n = len(s)
letters = sum(c.isalpha() for c in s)
digits = n - letters
if abs(letters - digits) > 1:
return ''
res = [''] * n
i = 0 if letters >= digits else 1
j = 1 - i
fo... | reformat-the-string | python 3 || simple solution without extra space | dereky4 | 0 | 63 | reformat the string | 1,417 | 0.556 | Easy | 21,228 |
https://leetcode.com/problems/reformat-the-string/discuss/1872200/Python3-or-Intuitive-approach | class Solution:
def reformat(self, s: str) -> str:
count_letters = count_digits = 0
letters =digits = []
for ch in s:
if ch.isdigit():
count_digits += 1
digits.append(ch)
else:
count_letters += 1
... | reformat-the-string | Python3 | Intuitive approach | user0270as | 0 | 45 | reformat the string | 1,417 | 0.556 | Easy | 21,229 |
https://leetcode.com/problems/reformat-the-string/discuss/1844885/Python-Simple-and-Concise!-Multiple-Solutions | class Solution:
def reformat(self, s):
d, c = [], []
for x in s:
if x.isalpha() : c.append(x)
elif x.isnumeric(): d.append(x)
if abs(len(c) - len(d)) > 1: return ''
if len(d) > len(c): c, d = d, c
z = zip_longest(c, d, fil... | reformat-the-string | Python - Simple and Concise! Multiple Solutions | domthedeveloper | 0 | 54 | reformat the string | 1,417 | 0.556 | Easy | 21,230 |
https://leetcode.com/problems/reformat-the-string/discuss/1844885/Python-Simple-and-Concise!-Multiple-Solutions | class Solution:
def reformat(self, s):
d = list(filter(str.isdigit,s))
c = list(filter(str.isalpha,s))
if abs(len(c)-len(d))>1: return ''
if len(d)>len(c): c,d = d,c
return reduce(add,reduce(add,zip_longest(c,d,fillvalue=''))) | reformat-the-string | Python - Simple and Concise! Multiple Solutions | domthedeveloper | 0 | 54 | reformat the string | 1,417 | 0.556 | Easy | 21,231 |
https://leetcode.com/problems/reformat-the-string/discuss/1788576/3-Lines-Python-Solution-oror-Faster-than-80-(48ms)-oror-Memory-Less-Than-97 | class Solution:
def reformat(self, s: str) -> str:
D, A = [d for d in s if d.isdigit()], [a for a in s if a.isalpha()]
if abs(len(D) - len(A)) > 1: return ''
return [j for i in zip_longest(D,A) for j in i if j] if len(D)>len(A) else [j for i in zip_longest(A,D) for j in i if j] | reformat-the-string | 3-Lines Python Solution || Faster than 80% (48ms) || Memory Less Than 97% | Taha-C | 0 | 68 | reformat the string | 1,417 | 0.556 | Easy | 21,232 |
https://leetcode.com/problems/reformat-the-string/discuss/1788506/Simple-Python-Solution-or-96.25-lesser-memory-or | class Solution:
def reformat(self, s: str) -> str:
alpha = str()
num = str()
for i in s:
if i.isalpha():
alpha += i
else:
num += i
if len(s) == 1:
return s
ans = []
if abs(len(alpha)-len(num)) <= 1:
... | reformat-the-string | Simple Python Solution | 96.25% lesser memory | | Coding_Tan3 | 0 | 50 | reformat the string | 1,417 | 0.556 | Easy | 21,233 |
https://leetcode.com/problems/reformat-the-string/discuss/1744416/Python3-or-faster-than-92.47-of-Python3 | class Solution:
def reformat(self, s: str) -> str:
if len(s) == 1:
return s
letters = []
numbers = []
for i in s:
if i.isdigit():
numbers.append(i)
else:
letters.append(i)
len_letter = len(letters)
... | reformat-the-string | Python3 | faster than 92.47% of Python3 | khalidhassan3011 | 0 | 48 | reformat the string | 1,417 | 0.556 | Easy | 21,234 |
https://leetcode.com/problems/reformat-the-string/discuss/1419368/Python3-44ms-Memory-Less-Than-86.98-Detailed-Solution | class Solution:
def reformat(self, s: str) -> str:
l, n, letters, nums = 0, 0, "", ""
for i in s:
if i.isalpha():
l += 1
letters += i
else:
n += 1
nums += i
if abs(l - n) >= 2:
retu... | reformat-the-string | Python3 44ms, Memory Less Than 86.98% [Detailed Solution] | Hejita | 0 | 73 | reformat the string | 1,417 | 0.556 | Easy | 21,235 |
https://leetcode.com/problems/reformat-the-string/discuss/1114173/Python3-simple-solution-beginner-friendly | class Solution:
def reformat(self, s: str) -> str:
alpha = []
dig = []
for i in s:
if i.isalpha():
alpha.append(i)
if i.isdigit():
dig.append(i)
if abs(len(alpha)-len(dig)) not in [0,1]:
return ""
else:
... | reformat-the-string | Python3 simple solution beginner friendly | EklavyaJoshi | 0 | 200 | reformat the string | 1,417 | 0.556 | Easy | 21,236 |
https://leetcode.com/problems/reformat-the-string/discuss/1030704/Faster-than-90.27-of-Python3 | class Solution:
def reformat(self, s: str) -> str:
n = len( s )
if n == 1:
return s
nums = "" # string of digits
chars = "" # string of letters
num = 0 # number of digits in a string
for i in range( n ):
if s[i].isnumer... | reformat-the-string | Faster than 90.27% of Python3 | DavidHB | 0 | 78 | reformat the string | 1,417 | 0.556 | Easy | 21,237 |
https://leetcode.com/problems/reformat-the-string/discuss/859708/Python3-5-line | class Solution:
def reformat(self, s: str) -> str:
alpha, digit = [], []
for c in s:
if c.isalpha(): alpha.append(c)
else: digit.append(c)
if len(alpha) < len(digit): alpha, digit = digit, alpha
if len(alpha) - len(digit) > 1: return "" # impossible
re... | reformat-the-string | [Python3] 5-line | ye15 | 0 | 70 | reformat the string | 1,417 | 0.556 | Easy | 21,238 |
https://leetcode.com/problems/reformat-the-string/discuss/859708/Python3-5-line | class Solution:
def reformat(self, s: str) -> str:
alpha = [c for c in s if c.isalpha()] # stack of alphabets
digit = [c for c in s if c.isdigit()] # stack of digits
if abs(len(alpha) - len(digit)) > 1: return "" # impossible
if len(alpha) < len(digit): alpha, digit... | reformat-the-string | [Python3] 5-line | ye15 | 0 | 70 | reformat the string | 1,417 | 0.556 | Easy | 21,239 |
https://leetcode.com/problems/reformat-the-string/discuss/764374/Python3-O(n)-time-O(1)-space! | class Solution:
def reformat(self, s: str) -> str:
nextDigit, nextStr, res = 0, 0, ""
def helper(curr,fn):
#return first occurance str with function passed (digit, alpha)
while curr<len(s):
if fn(s[curr]):
break;
curr+=1
... | reformat-the-string | Python3 O(n) time O(1) space! | amrmahmoud96 | 0 | 57 | reformat the string | 1,417 | 0.556 | Easy | 21,240 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1236252/Python3-Brute-Force-Solution | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
order = defaultdict(lambda : {})
foods = set()
ids = []
for i , t , name in orders:
t = int(t)
if(name in order[t]):... | display-table-of-food-orders-in-a-restaurant | [Python3] Brute Force Solution | VoidCupboard | 3 | 163 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,241 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1114368/Python3-freq-table | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
freq = {}
foods = set()
for _, table, food in orders:
freq.setdefault(table, defaultdict(int))[food] += 1
foods.add(food)
foods = sorted(foods)
ans ... | display-table-of-food-orders-in-a-restaurant | [Python3] freq table | ye15 | 2 | 74 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,242 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/2565333/python3-using-hashmap-faster-than-91.6 | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
category={}
foods=['Table']
for order in orders:
if order[1] not in category.keys():
category[order[1]]={}
if order[2] not in category[order[1]].keys():
... | display-table-of-food-orders-in-a-restaurant | [python3] using hashmap, faster than 91.6% | hhlinwork | 0 | 12 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,243 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/2451823/python | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
dummy_cnts = [0]
unique_tbl_no = []
items = []
d = {}
for i in orders:
tbl_item = (i[1], i[2])
if int(i[1]) not in unique_tbl_no:
unique_tbl_no.append(i... | display-table-of-food-orders-in-a-restaurant | python | jayashrisathe | 0 | 13 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,244 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/2307020/structural-python-solution | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
column = ['Table']
dish = []
table_dict = {}
for order_row in orders :
if order_row[-1] not in dish :
dish.append(order_row[-1])
for order_row in orders :... | display-table-of-food-orders-in-a-restaurant | structural python solution | sghorai | 0 | 30 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,245 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1212082/Simple-python-Solution-using-nested-dictionary-(-hashmap-)-or-Faster-than-92 | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
orderDict = dict()
tableHeader = set()
"""
below we create a dictionary with table id as key and a dictionary
containing no of each items as value. we also create a tableHeader
set to store all unique it... | display-table-of-food-orders-in-a-restaurant | Simple python Solution using nested dictionary ( hashmap ) | Faster than 92% | thecoder_elite | 0 | 85 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,246 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1085526/clean-python-code | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
ans=[]
dishes=set()
table=collections.defaultdict(collections.Counter)
for x in orders:
dishes.add(x[2])
table[x[1]][x[2]]+=1
header=['Table']
for x in sorted(d... | display-table-of-food-orders-in-a-restaurant | clean python code | sarthakraheja | 0 | 56 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,247 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/952511/Python-readable-solution-hashmap-and-set | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
display, foods = {}, set()
for customer, table, item in orders:
table = int(table)
if table not in display:
display[table] = {}
... | display-table-of-food-orders-in-a-restaurant | Python readable solution hashmap and set | modusV | 0 | 66 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,248 |
https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/589840/python3-solution.-two-hash-maps | class Solution:
def displayTable(self, orders) :
#definitely needs improvement.
tables = {}
food = {}
for order in orders: #go thru orders to list all table and food items.
tables[order[1]] = None
food[order[2]] = None
food_kinds = len(food)
ta... | display-table-of-food-orders-in-a-restaurant | python3 solution. two hash maps | SunnyLeetCode | 0 | 49 | display table of food orders in a restaurant | 1,418 | 0.738 | Medium | 21,249 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/1200924/Python-3-or-Greedy-Simulation-Clean-code-or-Explanantion | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
cnt, s = collections.defaultdict(int), 'croak'
ans, cur, d = 0, 0, {c:i for i, c in enumerate(s)} # d: mapping for letter & its index
for letter in croakOfFrogs: # iterate over the string
... | minimum-number-of-frogs-croaking | Python 3 | Greedy, Simulation, Clean code | Explanantion | idontknoooo | 6 | 384 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,250 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/1114385/Python3-freq-array | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
ans = 0
freq = [0]*5 # freq array
for c in croakOfFrogs:
i = "croak".index(c)
freq[i] += 1
if i and freq[i-1] < freq[i]: return -1
if c == "k":
ans = max... | minimum-number-of-frogs-croaking | [Python3] freq array | ye15 | 2 | 92 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,251 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/2840421/Documented-reduction-to-simplified-calendar-scheduling-(interval-overlap)-problem-(Python) | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
"""Reduction to interval overlap algorithm."""
if not croakOfFrogs:
return 0
from collections import defaultdict
positions = defaultdict(list)
for i, c in enumerate(croakOfFrogs):
po... | minimum-number-of-frogs-croaking | Documented reduction to simplified calendar scheduling (interval overlap) problem (Python) | DrMario | 0 | 2 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,252 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/2825953/Most-easiest-understanding-solution | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
string = "croak"
cnt = [0] * len(string)
res, cur = 0, 0
for c in croakOfFrogs:
index = string.index(c)
cnt[index] += 1
# current char cnt should be greater than previous
... | minimum-number-of-frogs-croaking | Most easiest understanding solution | yguo-gcc | 0 | 4 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,253 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/2711470/Python-O(N)-O(1) | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
counter = defaultdict(int)
counter[''] = sys.maxsize
mapping = {'c': '', 'r': 'c', 'o': 'r', 'a': 'o', 'k': 'a'}
res = current = 0
for char in croakOfFrogs:
counter[char] += 1
if c... | minimum-number-of-frogs-croaking | Python - O(N), O(1) | Teecha13 | 0 | 19 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,254 |
https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/2112844/python-3-oror-simple-solution-oror-O(n)O(1) | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
vals = {'c': 0, 'r': 1, 'o': 2, 'a': 3, 'k': 4}
croaks = [0] * 4
frogs = 0
for c in croakOfFrogs:
val = vals[c]
if val:
if not croaks[val - 1]:
return -1... | minimum-number-of-frogs-croaking | python 3 || simple solution || O(n)/O(1) | dereky4 | 0 | 110 | minimum number of frogs croaking | 1,419 | 0.501 | Medium | 21,255 |
https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/2785539/Python-DP-cleaner-than-most-answers | class Solution:
def numOfArrays(self, n: int, m: int, K: int) -> int:
MOD = 10 ** 9 + 7
# f[i][j][k] cumulative sum, first i elements, current max less than or equal to j, k more maximum to fill
f = [[[0 for _ in range(K + 1)] for _ in range(m + 1)] for _ in range(n + 1)]
for j in ra... | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | [Python] DP cleaner than most answers | chaosrw | 0 | 4 | build array where you can find the maximum exactly k comparisons | 1,420 | 0.635 | Hard | 21,256 |
https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/2641867/Python3-or-Top-Down-Dp | class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
@lru_cache(None)
def solve(size,maxNum,lis):
val=0
if size==1:
return lis==1
for mx in range(1,m+1):
if mx<maxNum:
val+=solve(size-1,mx,lis-1)... | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | [Python3] | Top Down Dp | swapnilsingh421 | 0 | 12 | build array where you can find the maximum exactly k comparisons | 1,420 | 0.635 | Hard | 21,257 |
https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/1482441/Python3-or-Backtracking-with-memorization | class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
MOD = 10**9 + 7
dp = {}
def helper(curr_max, n,k):
if k==0:
return (curr_max ** n)%MOD
if n==0:
return 0
if (curr_max, ... | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | Python3 | Backtracking with memorization | Sanjaychandak95 | 0 | 76 | build array where you can find the maximum exactly k comparisons | 1,420 | 0.635 | Hard | 21,258 |
https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/1114398/Python3-top-down-dp | class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
@cache
def fn(i, x, k):
"""Return number of ways to build arr[i:] with current max at x and remaining cost at k."""
if n - i < k: return 0 # impossible
if m - x < k: return 0 # imposs... | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | [Python3] top-down dp | ye15 | 0 | 84 | build array where you can find the maximum exactly k comparisons | 1,420 | 0.635 | Hard | 21,259 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/597944/Python3-linear-scan | class Solution:
def maxScore(self, s: str) -> int:
zeros = ones = 0
ans = float("-inf")
for i in range(len(s)-1):
if s[i] == "0": zeros += 1
else: ones -= 1
ans = max(ans, zeros + ones)
return ans - ones + (1 if s[-1] == "1" else ... | maximum-score-after-splitting-a-string | [Python3] linear scan | ye15 | 5 | 482 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,260 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2198674/python-one-line-solution | class Solution:
def maxScore(self, s: str) -> int:
return max([s[:i].count('0')+s[i:].count('1') for i in range(1, len(s))]) | maximum-score-after-splitting-a-string | python one line solution | writemeom | 1 | 46 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,261 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2593691/Simple-and-understandable-code-using-count-function-in-Python | class Solution:
def maxScore(self, s: str) -> int:
s = list(s)
res = 0
a, b = 0, 0
for i in range(1, len(s)):
a = s[:i] # left side array
b = s[i:] # right side array
a = a.count('0') # count of 0 at left side
b = b.count('1') # count o... | maximum-score-after-splitting-a-string | Simple and understandable code using count function in Python | ankurbhambri | 0 | 12 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,262 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2391873/Easy-and-fast-python-solution | class Solution:
def maxScore(self, s: str) -> int:
m0=0
m1=0
for i in s:
if i=="0":
m0+=1
else:
m1+=1
if m0==0 or m1==0:
return max(m0-1,m1-1)
l=len(s)
i=0
max_=0
c0=0
c1=m1
... | maximum-score-after-splitting-a-string | Easy & fast python solution | sunakshi132 | 0 | 17 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,263 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2277394/Python-Time%3A-O(n)-and-Space%3A-O(1)-solution | class Solution:
def maxScore(self, s: str) -> int:
no1=0
rez=0
for i in s: #here we count the 1's like everything is on the left side
if i=="1":
no1+=1
cur=no1
for i in range(len(s)-1): #here we expand the right side
... | maximum-score-after-splitting-a-string | Python Time: O(n) and Space: O(1) solution | thunder34 | 0 | 27 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,264 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2186632/Python-Solution-One-Liner-O(N)-Time-Complexity | class Solution:
def maxScore(self, s: str) -> int:
return max([s[0:i].count("0")+s[i::].count("1") for i in range(1,len(s))]) | maximum-score-after-splitting-a-string | Python Solution One Liner O(N) Time Complexity | Kunalbmd | 0 | 11 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,265 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/2037061/Python-One-Line! | class Solution:
def maxScore(self, s):
return max(s[:i].count("0") + s[i:].count("1") for i in range(1,len(s))) | maximum-score-after-splitting-a-string | Python - One Line! | domthedeveloper | 0 | 44 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,266 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1915657/Python-one-line-solution | class Solution:
def maxScore(self, s: str) -> int:
return max([s[:i].count('0') + s[i:].count('1') for i in range(1, len(s))]) | maximum-score-after-splitting-a-string | Python one line solution | alishak1999 | 0 | 23 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,267 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1868300/Python3-or-straight-forward-solution | class Solution:
def maxScore(self, s: str) -> int:
size = len(s)
highest_score = 0
for index in range(size-1):
l = s[:index+1]
r = s[index+1:]
total_score = l.count("0") + r.count("1")
if total_score > highest_score:
highest_score = total_score
return highest_score | maximum-score-after-splitting-a-string | Python3 | straight forward solution | user0270as | 0 | 24 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,268 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1824447/Python-Prfix-sum-with-1-loop | class Solution:
def maxScore(self, s: str) -> int:
N = len(s)
# prefix sum holds the total_sum of 0's
# suffix sum holds the sum of 1's
# I have taken deque as we have to build the suffix from right to left
# extra 0's are added to handel the edge cases
prefix_sum_0, suffix_sum_1... | maximum-score-after-splitting-a-string | Python Prfix sum with 1 loop | shankha117 | 0 | 29 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,269 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1751168/Python-dollarolution | class Solution:
def maxScore(self, s: str) -> int:
sz, m = 0, 0
so = s.count('1')
for i in s[:-1]:
if i == '0':
sz += 1
else:
so -= 1
if m < sz+so:
m = sz+so
return m | maximum-score-after-splitting-a-string | Python $olution | AakRay | 0 | 25 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,270 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1642244/Python-easy-solution | class Solution:
def maxScore(self, s: str) -> int:
n = len(s)
ones = s.count('1')
zeros = 0
score = 0
for i in range(n-1):
if s[i] == '0':
zeros += 1
else:
ones -= 1
score = max(score, zeros+ones)
... | maximum-score-after-splitting-a-string | Python easy solution | byuns9334 | 0 | 56 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,271 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1601656/Python-3-faster-than-97 | class Solution:
def maxScore(self, s: str) -> int:
score = s.count('1')
res = -math.inf
for i in range(len(s) - 1):
if s[i] == '0':
score += 1
else:
score -= 1
res = max(res, score)
return res | maximum-score-after-splitting-a-string | Python 3 faster than 97% | dereky4 | 0 | 72 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,272 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1418100/Python3-Faster-Than-80.06-Memory-Less-Than-75.07 | class Solution:
def maxScore(self, s: str) -> int:
ones, zeros, i, mx, cut = s.count('1'), 0, 0, 0, -1
if s[0] == 1:
ones -= 1
while(i < len(s)):
if s[i] == '0':
zeros += 1
elif s[i] == '1':
ones -= 1
... | maximum-score-after-splitting-a-string | Python3 Faster Than 80.06%, Memory Less Than 75.07% | Hejita | 0 | 45 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,273 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1181828/Python3-faster-than-27.23 | class Solution:
def maxScore(self, s: str) -> int:
res = []
for i in range(len(s)-1):
left = s[0:i+1]
right = s[i+1:]
res.append(left.count('0') + right.count('1'))
return(max(res)) | maximum-score-after-splitting-a-string | Python3 faster than 27.23% | monishapatel | 0 | 28 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,274 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/1135928/Python3-simple-solution | class Solution:
def maxScore(self, s: str) -> int:
n = len(s)
score=0
for i in range(n-1):
new_score = s[0:i+1].count("0") + s[i+1:n].count("1")
if new_score > score:
score = new_score
return score | maximum-score-after-splitting-a-string | Python3 simple solution | EklavyaJoshi | 0 | 101 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,275 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/832288/Straight-Forward-4-line-Python | class Solution:
def maxScore(self, s: str) -> int:
stk = []
for i in range(1,len(s)):
stk.append(s[:i].count('0') + s[i:].count('1'))
return max(stk) | maximum-score-after-splitting-a-string | Straight Forward 4-line Python | Venezsia1573 | 0 | 52 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,276 |
https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/621947/Intuitive-approach-by-tentative-split-on-all-positive-as-0-and-look-for-maximum | class Solution:
def maxScore(self, s: str) -> int:
s_len = len(s)
''' Length of `s`'''
max_score = -1
''' Keep max score during searching'''
for i in range(s_len-2, -1, -1):
if s[i] != '0':
# Skip split on 1
continue ... | maximum-score-after-splitting-a-string | Intuitive approach by tentative split on all positive as 0 and look for maximum | puremonkey2001 | 0 | 47 | maximum score after splitting a string | 1,422 | 0.578 | Easy | 21,277 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2197728/Python3-O(n)-Clean-and-Simple-Sliding-Window-Solution | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
total = sum(cardPoints)
remaining_length = n - k
subarray_sum = sum(cardPoints[:remaining_length])
min_sum = subarray_sum
for i in range(remaining_length, n... | maximum-points-you-can-obtain-from-cards | [Python3] O(n) - Clean and Simple Sliding Window Solution | TLDRAlgos | 38 | 2,200 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,278 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2200825/Convert-into-maximum-sum-subarray-of-length-k-using-sliding-window | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
length = len(cardPoints)
s = sum(cardPoints[-k:])
maximum = s
j = length-k
i=0
while i!=j and j<length:
s+=cardPoints[i]
s-=cardPoints[j]
i+=1
j+=... | maximum-points-you-can-obtain-from-cards | 📌 Convert into maximum sum subarray of length k using sliding window | Dark_wolf_jss | 6 | 67 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,279 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2199113/Recursive-%2B-DP-Solution | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
if k == 1:
return max(cardPoints[0], cardPoints[-1])
maximumScore = max(cardPoints[0] + self.maxScore(cardPoints[1:], k - 1), cardPoints[n - 1] + self.maxScore(cardPoints[:n - 1... | maximum-points-you-can-obtain-from-cards | Recursive + DP Solution | Vaibhav7860 | 6 | 764 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,280 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2199113/Recursive-%2B-DP-Solution | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
dpArray = [0 for i in range(k + 1)]
dpArray[0] = sum(cardPoints[:k])
for i in range(1, k + 1):
dpArray[i] = dpArray[i - 1] - cardPoints[k - i] + cardPoints[-i]
return max(dpArray) | maximum-points-you-can-obtain-from-cards | Recursive + DP Solution | Vaibhav7860 | 6 | 764 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,281 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/711939/Python3-Space-Efficient-Sliding-Window(90) | class Solution:
def maxScore(self, arr: List[int], k: int) -> int:
pre, suf = [arr[i] for i in range(len(arr))], [arr[i] for i in range(len(arr))]
n = len(arr)
for i in range(1,n):
pre[i] += pre[i-1]
for i in range(n-2, -1, -1):
suf[i] += suf[i+1]
ans ... | maximum-points-you-can-obtain-from-cards | [Python3] Space Efficient Sliding Window(90%) | uds5501 | 3 | 222 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,282 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2641479/Python-Solution-or-Sliding-Window-Approach | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
if len(cardPoints) <= k:
return sum(cardPoints)
points = cardPoints[len(cardPoints) - k:] + cardPoints[:k]
temp_sum = sum(points[:k])
largest = temp_sum
for i in range(len(points) - k):
... | maximum-points-you-can-obtain-from-cards | Python Solution | Sliding Window Approach | cyber_kazakh | 1 | 56 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,283 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2626071/Python-Easy-and-Simple-Solution-Using-Sliding-Window | class Solution:
def maxScore(self, nums: List[int], k: int) -> int:
e = len(nums)-1
s = k-1
n = len(nums)
ms = 0
ts = 0
for i in range(k):
ms += nums[i]
ts = ms
while k:
ts -= nums[s]
ts += nums[e]
s -=... | maximum-points-you-can-obtain-from-cards | Python Easy and Simple Solution Using Sliding Window | hoo__mann | 1 | 39 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,284 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2220142/Python-solution-oror-95 | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
if len(cardPoints) == 0: 0
if len(cardPoints) <= k: return sum(cardPoints)
subArraySum = sum(cardPoints[0:len(cardPoints) - k])
subArraySumArray = [subArraySum]
for i in range(k):
... | maximum-points-you-can-obtain-from-cards | Python solution || 95% | lamricky11 | 1 | 58 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,285 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2198316/Python3-or-Very-Easy-or-Explained-or-Easy-to-Understand-or-Sliding-Window | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
tot_sum = sum(cardPoints) # get the total sum of cardPoints
n = len(cardPoints) # length of array
m = n-k # what will be the window size (m)
if m==0:
... | maximum-points-you-can-obtain-from-cards | Python3 | Very Easy | Explained | Easy to Understand | Sliding Window | H-R-S | 1 | 73 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,286 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/1845459/python-sliding-window | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
if k >= n:
return sum(cardPoints)
cardPoints = cardPoints * 2
l = n - k
limit = n + k
max_ = sum_ = sum(cardPoints[l:l+k])
for r in rang... | maximum-points-you-can-obtain-from-cards | python sliding window | yshawn | 1 | 69 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,287 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/1203523/Python3-Solution-Using-Soliding-Window-Approach | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
length = n-k
tempSum = sum(cardPoints[:length])
mini = tempSum
for i in range(length,len(cardPoints)):
tempSum -= cardPoints[i-length]
tempSum += cardPoints... | maximum-points-you-can-obtain-from-cards | Python3 Solution Using Soliding Window Approach | swap2001 | 1 | 54 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,288 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/965906/Python-Iterative-sliding-window-O(k)-and-two-recursive-solutions | class Solution:
# TLE, O(2^k)
def maxScore1(self, cardPoints: List[int], k: int) -> int:
def solve(left, right, k, curs):
if k == 0: return curs
return max(solve(left+1, right, k-1, curs+cardPoints[left+1]),
solve(left, right-1, k-1, curs+cardPoints[r... | maximum-points-you-can-obtain-from-cards | [Python] Iterative sliding window O(k) and two recursive solutions | modusV | 1 | 105 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,289 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/744958/Easy-Solution-Python3 | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
if not cardPoints or k == 0: return 0
if k >= len(cardPoints): return sum(cardPoints)
window = cardPoints[-k:]
ans = []
ans.append(sum(window))
for i in range(k):
w... | maximum-points-you-can-obtain-from-cards | Easy Solution Python3 | marzi_ash | 1 | 174 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,290 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2661728/Simple-and-Efficient-Python-Solution. | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
if k == len(cardPoints):
return sum(cardPoints)
l, r = 0, len(cardPoints) - k
total = sum(cardPoints[r:])
res = total
while r < len(cardPoints):
total += cardP... | maximum-points-you-can-obtain-from-cards | Simple and Efficient Python Solution. | MaverickEyedea | 0 | 18 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,291 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2583302/Sliding-window-clear-as-a-day-python3-solution | class Solution:
# O(n) time,
# O(1) space,
# Approach: sliding window, two pointers,
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
tot_sum = sum(cardPoints)
if k == n:
return tot_sum
l, r = 0, n-k
curr_score = ... | maximum-points-you-can-obtain-from-cards | Sliding window clear as a day python3 solution | destifo | 0 | 21 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,292 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2428623/Maximum-points-you-can-obtain-form-cards-oror-Python3-oror-Sliding-Window | class Solution:
def maxScore(self, card_points: List[int], k: int) -> int:
# Sliding window approach from K elements at start to K elements at end
# Sum of first k elements
sum = 0
for i in range(0, k):
sum += card_points[i]
ans = sum
... | maximum-points-you-can-obtain-from-cards | Maximum points you can obtain form cards || Python3 || Sliding-Window | vanshika_2507 | 0 | 28 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,293 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2337118/Python-2-Approach | class Solution(object):
def maxScore(self, cardPoints, k):
if len(cardPoints) == k:
return sum(cardPoints)
map = {-1:0}
win_size = len(cardPoints)-k
prefix = 0
min_sum = sys.maxsize
for i, val in enumerate(cardPoints):
prefix += val
... | maximum-points-you-can-obtain-from-cards | Python 2 Approach | Abhi_009 | 0 | 34 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,294 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2337118/Python-2-Approach | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
if k == len(cardPoints):
return sum(cardPoints)
score = 0
win_size = len(cardPoints)-k
i = 0
j = 0
min_sum = sys.maxsize
temp = 0
while j<len(cardPoints):
... | maximum-points-you-can-obtain-from-cards | Python 2 Approach | Abhi_009 | 0 | 34 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,295 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2203220/Python3-Sliding-Window-on-firstandlast-k-element | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
# Take [1,2,3,4,5,6,1], k = 3 as example
if k >= len(cardPoints):
return sum(cardPoints)
# [5,6,1,1,2,3]
comb = cardPoints[-k:] + cardPoints[:k]
# sum of first k elements
output = sum(comb[:k])
... | maximum-points-you-can-obtain-from-cards | [Python3] Sliding Window on first&last k element | zryao | 0 | 16 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,296 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2201998/Python-3-Sliding-Window-With-Comments | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
prefixSums = [ x for x in accumulate(cardPoints) ]
if k == n:
return prefixSums[n-1]
if k == 1:
return max(cardPoints[0], cardPoints[n-1])
... | maximum-points-you-can-obtain-from-cards | Python 3 / Sliding Window / With Comments | kodrevol | 0 | 17 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,297 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2201715/Python-Solution-using-Sliding-Window-oror-O(k)-Time-Complexity-oror-Faster-than-99.62 | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
ans=0
n=len(cardPoints)
if n==k: #return if cards needed is equal to length of the list
return sum(cardPoints)
s=sum(cardPoints)
sub=sum(cardPoints[:n-k])
... | maximum-points-you-can-obtain-from-cards | Python Solution using Sliding Window || O(k) Time Complexity || Faster than 99.62% | HimanshuGupta_p1 | 0 | 9 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,298 |
https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2201269/Python3-prefixsum | class Solution:
def maxScore(self, cp: List[int], k: int) -> int:
#if k=1 then req. card is either first or last one
if k==1: return max(cp[0],cp[-1])
# if k>=no. of cards select all just a case to reduce runtime
if k>=len(cp): return sum(cp)
#calculate c1, i.e prefix sum up... | maximum-points-you-can-obtain-from-cards | 🐍Python3 prefixsum🐍 | YaBhiThikHai | 0 | 20 | maximum points you can obtain from cards | 1,423 | 0.523 | Medium | 21,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.