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] return ans
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, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733 ] m.sort() m=m[::-1] x=0 count=0 print(m) i=0 y=k for i in range(len(m)): if m[i]>k: continue count+=1 x+=m[i] if x>k: x-=m[i] count-=1 if x==k: break return count
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 ** (n - 1) # If k is too large if k > part * 3: return "" res = [] # Edge case is k = n * i, where i is an integer in range [1, 3] res.append(char[k // part if k % part != 0 else k // part - 1]) k = k % part if k % part != 0 else part for i in range(n - 2, -1, -1): char = ["a", "b", "c"] char.remove(res[-1]) # Make sure the adjacent characters will be different if len(res) + 1 == n: # Edge case, assigning the last element if k == 1: res.append(char[0]) elif k == 2: res.append(char[-1]) elif k > 2 ** i: # Go to the right side res.append(char[-1]) k -= 2 ** i else: res.append(char[0]) # Go to the left side return "".join(res)
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) -> str: letters = ["a" , "b" , "c"] l = [] for i in letters : self.helper(i,l,letters , n) if(len(l) >= k): return l[k-1] return ""
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(string)==0: happy_string(i,string+inp_string[i]) else: if string[-1]==inp_string[i]: continue happy_string(i,string+inp_string[i]) happy_string(0,'') if k<=len(res): return res[k-1] else: return ''
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") if d >= ord(ret[-1]): d += 1 ret += chr(d) else: total //= 3 ret += chr(k // total + ord("a")) k %= total return ret
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: continue dfs(alphabets,n,s + x) dfs(alphabets,n,"") if k > 3 * ( 2 ** ( n - 1)): return "" return answer[k - 1]
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 == "": for ele in store: curr += ele traverse(curr,ans) curr = curr[:-1] # last ele a case elif curr[-1] == 'a': for ele in ['b','c']: curr += ele traverse(curr,ans) curr = curr[:-1] # last ele b case elif curr[-1] == 'b': for ele in ['a','c']: curr += ele traverse(curr,ans) curr = curr[:-1] # last ele c case elif curr[-1] == 'c': for ele in ['a','b']: curr += ele traverse(curr,ans) curr = curr[:-1] ans = [] curr = "" traverse(curr,ans) # print(ans) return ans[k-1] if k <= len(ans) else "" # iterative 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 # iterative condition checking for i in range(0,3): if len(curr) == 0 or curr[-1] != store[i]: curr += store[i] traverse(curr,ans) curr = curr[:-1] ans = [] curr = "" traverse(curr,ans) # print(ans) return ans[k-1] if k <= len(ans) else ""
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 == len(curr): res.append("".join(curr[:])) for i in range(0, len(letters)): if len(curr)>0 and letters[i] == curr[-1]: continue if n == len(curr): continue curr.append(letters[i]) self.backtrack(res, letters, n, k, curr) curr.pop()
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 -> current built up string! pre -> tell which char we added last to #get cur string! def helper(cur, pre): nonlocal n #base case if(len(cur) == n): #append deep copy of happy string of length n to ans array! ans.append(cur[::]) #return and don't recurse any further! return if(pre == ""): #we can add any chars! cur += "a" helper(cur, "a") cur = cur[:len(cur)-1] cur += "b" helper(cur, "b") cur = cur[:len(cur)-1] cur += "c" helper(cur, "c") cur = cur[:len(cur)-1] return elif(pre == "a"): cur += "b" helper(cur, "b") cur = cur[:len(cur)-1] cur += "c" helper(cur, "c") cur = cur[:len(cur)-1] return elif(pre == "b"): cur += "a" helper(cur, "a") cur = cur[:len(cur)-1] cur += "c" helper(cur, "c") cur = cur[:len(cur)-1] return else: cur += "a" helper(cur, "a") cur = cur[:len(cur)-1] cur += "b" helper(cur, "b") cur = cur[:len(cur)-1] return helper("", "") #we need to check if we want to return kth string that does not exist for given #list of happy strings of length n! if(k - 1 >= len(ans)): return "" return ans[k-1]
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 in "abc": if(self.lock): return if(not com): solve(com+i) else: if(com[-1] != i): solve(com+i) solve("") return self.res
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'+help_a[j]) help_b = t_a + t_c for j in range(len(help_b)): b.append('b'+help_b[j]) help_c = t_a + t_b for j in range(len(help_c)): c.append('c'+help_c[j]) ans = a+b+c return ans[k-1] if k <= len(ans) else ''
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: if not cur_seq or c != cur_seq[-1]: res = self.backtracking(seq, cur_seq + [c], n, k) if res: return res return [] def getHappyString(self, n: int, k: int) -> str: res = self.backtracking("abc", [], n, k) return ''.join(res)
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 range(len(happy)): if s and s[-1] == happy[i]: continue self.happyHelper(n,s + happy[i],happy,res)
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 s == "" or s[-1] != a[i]: make(a, s+a[i], n, k, res) else: continue res = [] make(['a', 'b', 'c'], "", n, k, res) if k > len(res): return "" return res[k-1]
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]: yield from dfs(string+ch) index = 1 for happy_string in dfs(''): if index == k: return happy_string index += 1 return ''
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[-1]][q]) return "".join(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: for c in ['a', 'b', 'c']: if hs and hs[-1] == c: continue yield from _gen_of_hs(hs+c) return _gen_of_hs('', n) num_of_hs = 0 ''' number of happy string generated''' # Algorithm: Keep generating happy string util the kth one generated. for hs in get_hs(n): num_of_hs += 1 if num_of_hs == k: return hs # Unable to retrieve the kth happy string return "" `
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]=1 else: new[i]+=new[j-1] #print(new) return new[-1]%(10**9+7)
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 - dp[ii]) % 1_000_000_007 ii -= 1 dp[i] = sm sm = (sm + dp[i]) % 1_000_000_007 return dp[0]
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] return reduce(lambda x, y: x + y[0] + y[1], itertools.zip_longest(a, b, fillvalue=''), '') return ''
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) return ''.join(c for pair in itertools.zip_longest(b, a) for c in pair if c)
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 pair in zip(numbers, letters) for item in pair]) longer = numbers if len(numbers) > len(letters) else letters shorter = numbers if len(numbers) < len(letters) else letters return ''.join([item for pair in zip(longer, shorter) for item in pair] + [longer[-1]])
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_pointer] = char nr_pointer += 2 else: if chr_pointer >= n+1: return "" sol[chr_pointer] = char chr_pointer += 2 # check the char pointer (whether there were) if chr_pointer == n+2: sol[-2] = sol[0] sol[0] = "" return "".join(sol)
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="")) else: return ""
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 else: alp2.append(i) #appending alphabets in alp2 if(len(alp2)-len(num1)>=-1 and len(alp2)-len(num1)<=1): #If difference b/w them is greater than 1 or less than 1 there will be no such string if(len(alp2)>len(num1)): #If alphabets are more for i in range(len(num1)): output+=alp2[i] #In output string first append alphabet output+=num1[i] output+=alp2[-1] #remaining last alphabet is append return output elif(len(num1)>len(alp2)): #Same as above explanation for i in range(len(alp2)): output+=num1[i] output+=alp2[i] output+=num1[-1] return output else: for i in range(len(alp2)): #If length of both are same output+=num1[i] output+=alp2[i] return output else: return ""
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 = '' for i in range(len(a)+len(b)): if i % 2 == 0: ans += a[i//2] else: ans += b[i//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 = 0,0 for i in range(len(s)): if i % 2==0: if k < len(a): string += str(a[k]) k += 1 else: return "" else: if l < len(b): string += str(b[l]) l += 1 else: return "" return string
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 for c in s: if c.isalpha(): res[i] = c i += 2 else: res[j] = c j += 2 return ''.join(res)
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 letters.append(ch) ans = "" if abs(count_letters - count_digits) >1: return "" else: if count_digits >= count_letters: for index, digit in enumerate(digits): if index < count_letters: ans = ans + digit + letters[index] else: ans += digit else: for index, letter in enumerate(letters): if index < count_digits: ans = ans + letter + digits[index] else: ans += letter return ans
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, fillvalue='') return reduce(add, reduce(add, z))
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: for i,j in zip(alpha, num): ans.extend([i,j]) if len(num) > len(alpha): ans = [num[-1]]+ans elif len(alpha)>len(num): ans = ans + [alpha[-1]] else: return "" return "".join(ans)
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) len_numbers = len(numbers) result = "" if not letters or not numbers or abs(len_letter - len_numbers > 1): return "" elif len_numbers > len_letter: for i in range(len_letter): result += numbers[i] result += letters[i] result += numbers[-1] else: for i in range(len_numbers): result += letters[i] result += numbers[i] if len_letter > len_numbers: result += letters[-1] return result
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: return "" s = "" if n == l: j = 0 for i in range(n): s += letters[i] s += nums[j] j += 1 elif n > l: s += nums[0] j = 1 for i in range(n - 1): s += letters[i] s += nums[j] j += 1 else: s += letters[0] j = 1 for i in range(l - 1): s += nums[i] s += letters[j] j += 1 return s
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: res = '' if len(alpha) > len(dig): x = alpha y = dig else: x = dig y = alpha for i in range(len(y)): res += x[i] + y[i] if len(alpha) == len(dig): return res else: res += x[-1] return res
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].isnumeric(): nums += s[i] num += 1 else: chars += s[i] numch = n - num # number of letters in a string s = "" if num == numch : for i in range( n // 2): s += nums[i] s+=chars[i] elif num == numch + 1: for i in range(n // 2): s += nums[i] s += chars[i] if i == numch - 1: s += nums[ i + 1 ] elif numch == num + 1: for i in range( n // 2 ): s += chars[i] s += nums[i] if i == num - 1: s += chars[i + 1] return s
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 return "".join(x+y for x, y in zip_longest(alpha, digit, fillvalue=""))
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 = digit, alpha # alpha >= digit ans = [] while alpha: ans.append(alpha.pop()) if digit: ans.append(digit.pop()) return "".join(ans)
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 return curr #append to res digit and str in that order while nextDigit<len(s) and nextStr<len(s): nextDigit = helper(nextDigit, str.isdigit) nextStr = helper(nextStr, str.isalpha) if nextDigit >= len(s): break res += s[nextDigit] if nextStr >= len(s): break res += s[nextStr] nextDigit += 1 nextStr += 1 #if there are digits remaining if helper(nextDigit + 1, str.isdigit) < len(s): return "" # if the current string is not accounted for, prepend it to the result if nextStr < len(s) and s[nextStr].isalpha(): res = s[nextStr] + res # if we can find more strings if helper(nextStr + 1, str.isalpha) < len(s): return "" return res
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]): order[t][name] += 1 else: order[t][name] = 1 if(int(t) not in ids): ids.append(int(t)) foods.add(name) ids.sort() foods = list(foods) foods.sort() tables = [['Table'] + foods] k = 0 order = dict(sorted(order.items() , key=lambda x: x[0])) for _ , j in order.items(): ans = [str(ids[k])] for i in foods: if(i in j): ans.append(str(j[i])) else: ans.append("0") tables.append(ans) k += 1 return tables
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 = [["Table"] + foods] for k in sorted(freq, key=int): row = [k] for food in foods: row.append(str(freq[k][food])) ans.append(row) return 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(): category[order[1]][order[2]]=1 else: category[order[1]][order[2]]+=1 if order[2] not in foods: foods.append(order[2]) tables = category.keys() foods = [foods[0]]+sorted(foods[1:]) ans=[foods] for k in sorted(category.keys(),key=int): table=[] table.append(str(k)) for i in range(1,len(foods)): if foods[i] in category[k].keys(): table.append(str(category[k][foods[i]])) else: table.append('0') ans+=[table] return ans
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(int(i[1])) if i[2] not in items: items.append(i[2]) dummy_cnts.append(0) if tbl_item not in d: d[tbl_item] = 1 else: d[tbl_item] += 1 items = sorted(items) final_list = [items] final_list[0].insert(0, "Table") for table_no in sorted(unique_tbl_no): table_no = str(table_no) nested_lst = dummy_cnts.copy() for item in items: index_for_cnts = items.index(item) nested_lst[0] = table_no nested_lst[index_for_cnts] = str(d.get((table_no, item), 0)) final_list.append(nested_lst) return final_list
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 : if order_row[1] not in table_dict.keys() : table_dict[order_row[1]] = {} for food in dish : table_dict[order_row[1]][food] = 0 table_dict[order_row[1]][order_row[-1]] += 1 else : table_dict[order_row[1]][order_row[-1]] += 1 dish.sort() column = column + dish ans = [column] table = [] childDict = {} for key in sorted(table_dict.keys()) : table.append(int(key)) childDict[key] = [] for value in column : if value != 'Table' : childDict[key].append(str(table_dict[key][value])) table.sort() output = [ans[0]] for table_num in table : childList = [str(table_num)] output.append(childList + childDict[str(table_num)]) return output
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 items ordered. """ for order in orders: if(order[1] not in orderDict): orderDict[order[1]] = dict() if(order[2] not in orderDict[order[1]]): orderDict[order[1]][order[2]] = 0 orderDict[order[1]][order[2]] += 1 tableHeader.add(order[2]) """ output after above steps: orderDict: { '3': { 'Ceviche': 2, 'Fried Chicken': 1 }, '10': { 'Beef Burrito': 1 }, '5': { 'Water': 1, 'Ceviche': 1 } } tableHeader: {'Ceviche', 'Water', 'Fried Chicken', 'Beef Burrito'} Then we convert our set to a list and sort it as required. and iterate over the dict and create an array for each table where first item is the table id and following that are the count of each item ordered by that table. """ tableHeader = list(tableHeader) tableHeader.sort() answer = list() for tableId in orderDict: temp = list() temp.append(tableId) for header in tableHeader: if(header in orderDict[tableId]): temp.append(str(orderDict[tableId][header])) else: temp.append("0") answer.append(temp) """ Finally we sort the answer array based on the first value of each sub array i.e. the table id and add our tableHeader list as required to the answer on the first index. """ answer.sort(key = lambda x: int(x[0])) tableHeader.insert(0, "Table") answer.insert(0, tableHeader) return answer
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(dishes): header.append(x) ans.append(header) for x in sorted(table.keys(),key=lambda x: int(x)): res=[x] for y in sorted(dishes): res.append(str(table[x][y])) ans.append(res) return ans
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] = {} foods.add(item) display[table][item] = display[table].get(item, 0) + 1 header = sorted(list(foods)) orders = [[0 for _ in range(len(foods)+1)] for _ in range(len(display.keys()))] for row, table in enumerate(sorted(display.keys())): orders[row][0] = str(table) for col, food in enumerate(header): orders[row][col+1] = str(display[table].get(food, 0)) return [['Table'] + header] + orders
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) tables_num = len(tables) display_table = [["0" for i in range(food_kinds+1)] for j in range(tables_num+1)] display_table[0][0] = "Table" row_table = 1 tables = dict(sorted(tables.items(),key = lambda x:int(x[0]))) #sort table in numeric order for table in tables: display_table[row_table][0]= table tables[table] = row_table #record which row is for this table. row_table+=1 column_table = 1 food = dict(sorted(food.items(),key = lambda x:x[0])) #sort food item in alphabetical order for food_item in food: display_table[0][column_table]= food_item food[food_item]= column_table #record which column is for this food item column_table +=1 for order in orders: if display_table[tables[order[1]]][food[order[2]]] == "0": display_table[tables[order[1]]][food[order[2]]]="1" else: display_table[tables[order[1]]][food[order[2]]]=str(int(display_table[tables[order[1]]][food[order[2]]])+1) return display_table
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 &amp; its index for letter in croakOfFrogs: # iterate over the string if letter not in s: return -1 # if any letter other than "croak" is met, then invalid cnt[letter] += 1 # increase cnt for letter if letter == 'c': cur += 1 # 'c' is met, increase current ongoing croak `cur` elif cnt[s[d[letter]-1]] <= 0: return -1 # if previous character fall below to 0, return -1 else: cnt[s[d[letter]-1]] -= 1 # otherwise, decrease cnt for previous character ans = max(ans, cur) # update answer using `cur` if letter == 'k': # when 'k' is met, decrease cnt and cur cnt[letter] -= 1 cur -= 1 return ans if not cur else -1 # return ans if current ongoing "croak" is 0
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(ans, freq[0]) for i in range(5): freq[i] -= 1 if max(freq) == 0: return ans return -1
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): positions[c].append(i) num_of_croaks = len(positions["c"]) # check length for c in "croak": if num_of_croaks != len(positions[c]): return -1 # check order to reduce to interval problem for i in range(num_of_croaks): if positions["c"][i] < positions["r"][i] < \ positions["o"][i] < positions["a"][i] < positions["k"][i]: continue else: return -1 # interval overlap algorithm on c and k without overlap handling max_num = 1 current_num = 1 # first entry is always a c and irrelevant positions["c"].pop(0) while positions["c"]: # get next interval start current = positions["c"].pop(0) # check if it frees any frogs while current > positions["k"][0]: positions["k"].pop(0) current_num -= 1 # account for new frog assignment to c current_num += 1 max_num = max(max_num, current_num) return max(max_num, current_num)
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 if index > 0 and cnt[index] > cnt[index-1]: return -1 # new singing, increasing cur cnt if c == "c": cur += 1 # singing finished, decreasing if c == "k": cur -= 1 # capture max concurrent singing frogs res = max(res, cur) # all element should be the same if max(cnt) != min(cnt): return -1 return res
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 counter[char] > counter[mapping[char]]: return -1 if char == 'c': current += 1 elif char == 'k': current -= 1 res = max(res, current) if counter['c'] != counter['k']: return -1 return res
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 croaks[val - 1] -= 1 if val != 4: croaks[val] += 1 frogs = max(frogs, sum(croaks)) return frogs if not sum(croaks) else -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 range(m + 1): f[0][j][K] = 1 for i in range(n + 1): for j in range(1, m + 1): for k in range(K): # prev value a[i] <= pref high a[i] = j refresh high f[i][j][k] = (f[i][j - 1][k] + j * (f[i - 1][j][k] - f[i - 1][j - 1][k]) + f[i - 1][j - 1][k + 1]) % MOD return f[n][m][0]
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) else: val+=solve(size-1,maxNum,lis) return val%1000000007 ans=0 ans=solve(n+1,m+1,k+1) return ans
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, n,k) in dp: return dp[(curr_max, n,k)] a = 0 for val in range(1,m+1): # 1 take it temp = k if curr_max < val: temp-=1 a = (a + helper(max(curr_max, val),n-1,temp))%MOD dp[(curr_max, n,k)] = a return dp[(curr_max, n,k)] return helper(0,n,k)%MOD
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 # impossible if k == 0: return x**(n-i) return x*fn(i+1, x, k) + fn(i+1, x+1, k-1) + fn(i, x+1, k) - (x+1)*fn(i+1, x+1, k) return fn(0, 0, k) % 1_000_000_007
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 0)
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 of 1 at right side res = max(res, a + b) return res
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 idx=-1 while i <l: if s[i]=="0": c0+=1 else: c1-=1 if max_<c1+c0: max_=c1+c0 idx=i max_=max(max_,c1+c0) i+=1 if idx==l-1: return max_-1 return max_
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 if s[i]=="0": #when we find a 0 we sum1 !len(s)-1 because the none parts can be empty cur+=1 else: #when we find a 1 we lower the current because it means the 1 isn't in the left side anymore cur-=1 if cur>rez: # we update the rez if needed rez=cur return rez
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 = [0], deque([0]) # In 1 pass build the sum arrays for i in range(len(s)): if s[i] == "0": prefix_sum_0.append( 1+ prefix_sum_0[-1]) else: prefix_sum_0.append(prefix_sum_0[-1]) if s[N-1-i] == "1": suffix_sum_1.appendleft(1+suffix_sum_1[0]) else: suffix_sum_1.appendleft(suffix_sum_1[0]) # take the everything except 1st and last element from the prefix and suffix array and get the max sum of every pair # becasue we can not consider the additional zeros return max((map(sum,zip(list(suffix_sum_1)[1:-1:], prefix_sum_0[1:-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) return score
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 if mx < ones + zeros: mx = ones + zeros cut = i i += 1 if cut == len(s) - 1 and s[-1] == '0': mx -= 1 return mx
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 split_left = s[:i+1] ''' Left part after split''' if split_left.count('0') >= split_left.count('1'): # print("{}: {} {}".format(s, split_left, s[i+1:])) cur_score = split_left.count('0') + s[i+1:].count('1') if cur_score > max_score: max_score = cur_score # If mas_score = -1, it means no split at all # So we have to split at least once by minimum cost: # s[:1] + s[1:] # which will lose one '1' and obtain score = s.count('1') - 1 return max_score if max_score > 0 else s.count('1') - 1 sol = Solution() for s, ans in [ ("01101", 4), ("110000", 3), ("1011011", 5), ("01001", 4), ("011101", 5), ("00111", 5), ("1111", 3), ("11100", 2), ("0000", 3), ("0100001", 6) ]: rel = sol.maxScore(s) print("{}: {}".format(s, rel)) assert ans == rel
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): # Update the sliding window sum to the subarray ending at index i subarray_sum += cardPoints[i] subarray_sum -= cardPoints[i - remaining_length] # Update min_sum to track the overall minimum sum so far min_sum = min(min_sum, subarray_sum) return total - min_sum
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+=1 maximum = max(s,maximum) return maximum
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], k - 1)) return maximumScore
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 = -1 for i in range(k+1): left = k-i-1 right = n-i curr = 0 if (right < n): curr += suf[right] if (left >= 0): curr += pre[left] ans = max(ans, curr) return 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): temp_sum -= (points[i] - points[i + k]) largest = max(largest, temp_sum) return largest
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 -= 1 e -= 1 ms = max(ms,ts) k-=1 return ms
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): subArraySum = subArraySum - cardPoints[i] + cardPoints[i + len(cardPoints) - k] subArraySumArray.append(subArraySum) return sum(cardPoints) - min(subArraySumArray)
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: return tot_sum # if every elements has to be taken window_sum = sum(cardPoints[:m]) # sum for first window (first m elements) min_window_sum = window_sum # initialize the minimum window sum j=0 for i in range(m, n): window_sum += cardPoints[i] - cardPoints[j] # getting the sum for each window min_window_sum = min(window_sum, min_window_sum) # setting the minimum window sum j+=1 return tot_sum - min_window_sum # return the maximum score can be obtained
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 range(l, n): sum_ -= cardPoints[r] - cardPoints[r + k] max_ = max(max_, sum_) return max_
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[i] mini = min(tempSum,mini) return sum(cardPoints)-mini
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[right-1])) return solve(-1, len(cardPoints), k, 0) # Another recursive solution O(2^k), with or without memoization gives TLE anyways def maxScore1(self, cardPoints: List[int], k: int) -> int: def solve(left, right, k): if k == 0: return 0 return max(cardPoints[left] + solve(left+1, right, k-1), cardPoints[right] + solve(left, right-1, k-1)) return solve(0, len(cardPoints)-1, k) # O(k) iterative sliding windows def maxScore(self, cp: List[int], k: int) -> int: sm = sum(cp[:k]) best = sm r = k-1 while r+1: sm = sm - cp[r] + cp[r-k] best = max(best, sm) r -= 1 return best
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): window.append(cardPoints[i]) ans.append(ans[-1] - window.pop(0) + window[-1]) return max(ans)
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 += cardPoints[l] - cardPoints[r] if total > res: res = total r += 1 l += 1 return res
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 = tot_sum - sum(cardPoints[l:r]) max_score = curr_score while r < n: curr_score += cardPoints[l] curr_score -= cardPoints[r] l +=1 r +=1 max_score = max(max_score, curr_score) return max_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 if(len(card_points) == k): return sum end = len(card_points) -1 for i in range(k-1, -1, -1): sum = sum - card_points[i] + card_points[end] end -= 1 ans = max(ans, sum) return ans
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 if (i-win_size) in map: min_sum = min(min_sum,prefix-map[(i-win_size)] ) map[i] = prefix return sum(cardPoints)-min_sum
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): temp+= cardPoints[j] if (j-i+1)<win_size: j+=1 elif (j-i+1) == win_size: min_sum = min(min_sum, temp) temp -= cardPoints[i] i+=1 j+=1 return sum(cardPoints)-min_sum
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]) # save the prev k elements to reduct computing time prev = output for i in range(1, k + 1): # remove one element at the left, and add next element target = prev - comb[i - 1] + comb[i + k - 1] # update the maximum output = max(output, target) prev = target return output
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]) """ n = 7 k = 3 ind: 0 1 2 3 4 5 6 val: 1 2 3 4 5 6 1 sum: 1 3 6 10 15 21 22 """ # we are interested in total of not selected items in the window # so, for the first step out window left and right indexes are 0 and 3 (n-k-1) # and sum we are looking for is total sum - sum of the current window # we return max of these values totalSum = prefixSums[n-1] ans = totalSum - prefixSums[n-k-1] l, r = 1, n-k # print(prefixSums) # print(ans) """ before iteration: 0, 3 ( n-k-1 = 7-3-1 = 3 ) iterations, if k==3 then iterations (1, k+1) = (1, 4) => i = [ 1, 2, 3 ]: 1, 4 2, 5 3, 6 """ for i in range(1, k+1): windowSum = prefixSums[r] - prefixSums[l-1] # l-1 is one index before the window ans = max(ans, totalSum - windowSum) # print(l, r, ans) l, r = l+1, r+1 return ans
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]) ans=s-sub for i in range(k): sub-=cardPoints[i] #eliminating previous card sub+=cardPoints[i+n-k] #adding card current+(n-k)th one ans=max(ans,s-sub) #updating answer ans=max(ans,s-sub) return ans
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 upto k cards c1=list(accumulate(cp[:k])) #calculate c2, i.e prefix sum of last k cards c2=list(accumulate(cp[::-1][:k])) #case1 : all cards from left #case2 : all cards from right #case3 : i cards from left and (k-i) cards from right #where i ranges b/w 0,k-1 #cal. all posible case and taking max of that. return max(c1[k-1],c2[k-1],max(c1[i]+c2[-i-2] for i in range(k-1)))
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