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/palindromic-substrings/discuss/1055894/Python-DP-solution-O(n2)
class Solution: def countSubstrings(self, s: str) -> int: dp = [[0 for j in range(len(s)+1)] for i in range(len(s)+1)] for l in range(1,len(s)+1): for i in range(len(s)-l+1): j = i+l if l == 1: dp[i][j] = 1 elif l == 2: dp[i][j] = 1 if s[i] == s[j-1] else 0 else: if dp[i+1][j-1] == 1 and s[i] == s[j-1]: dp[i][j] = 1 return sum(sum(t) for t in dp)
palindromic-substrings
Python DP solution O(n^2)
milton0825
1
285
palindromic substrings
647
0.664
Medium
10,800
https://leetcode.com/problems/palindromic-substrings/discuss/2837486/DP-center-seed-idea-for-odd-and-even-cases
class Solution: def countSubstrings(self, s: str) -> int: n=len(s) res=n if n==1: return res def getPalindromes(i,j): count=0 while s[i]==s[j]: count+=1 if i==0 or j==n-1: break i-=1 j+=1 return count for i in range(1,len(s)-1): res+= getPalindromes(i-1,i+1) + getPalindromes(i-1,i) res+=getPalindromes(n-2,n-1) return res
palindromic-substrings
[DP] center-seed idea for odd and even cases
romilvt
0
3
palindromic substrings
647
0.664
Medium
10,801
https://leetcode.com/problems/palindromic-substrings/discuss/2770231/Python-3-oror-Expand-Extend-palindrome-13-lines-of-code
class Solution: def countSubstrings(self, s: str) -> int: result = 0 def checker(left, right): palindrome = 0 while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 palindrome += 1 return palindrome for index in range(len(s)): result += checker(index, index) + checker(index, index + 1) return result
palindromic-substrings
Python 3 || Expand Extend palindrome 13 lines of code
Sefinehtesfa34
0
10
palindromic substrings
647
0.664
Medium
10,802
https://leetcode.com/problems/palindromic-substrings/discuss/2764114/PYTHON-oror-easy-solu-or-using-oror-DP-bottomup
class Solution: def countSubstrings(self, s: str) -> int: n=len(s) dp=[] for i in range (n): dp.append([0]*n) res=0 for gap in range (n): i=0 for j in range (gap,n): if gap==0: dp[i][j]=1 res+=1 elif gap==1: if s[i]==s[j]: dp[i][j]=1 res+=1 # else: # dp[i][j]=0 else: if s[i]==s[j]: if dp[i+1][j-1]==1: dp[i][j]=1 res+=1 # else: # dp[i][j]=0 i+=1 return res
palindromic-substrings
PYTHON || easy solu | using || DP bottomup
tush18
0
7
palindromic substrings
647
0.664
Medium
10,803
https://leetcode.com/problems/palindromic-substrings/discuss/2758441/Python-or-O(n)-two-pointers
class Solution: def countSubstrings(self, s: str) -> int: n = len(s) ans = n for i in range(n): l, r = i, i + 2 while l >= 0 and r < n and s[l] == s[r]: ans += 1 l -= 1 r += 1 l, r = i, i + 1 while l >= 0 and r < n and s[l] == s[r]: ans += 1 l -= 1 r += 1 return ans
palindromic-substrings
Python | O(n²) two pointers
on_danse_encore_on_rit_encore
0
6
palindromic substrings
647
0.664
Medium
10,804
https://leetcode.com/problems/palindromic-substrings/discuss/2747455/Python-Solution-78.6-with-simple-For-Loop
class Solution: def countSubstrings(self, s: str) -> int: l = len(s) count = 0 for i in range(len(s)-1): if s[i] == s[i+1]: left, right = i-1, i + 2 count += 1 while left >= 0 and right < l: if s[left] == s[right]: count += 1 left -=1 right +=1 else: break for i in range(len(s)): count += 1 left,right = i-1, i+1 while left >= 0 and right < l: if s[left] == s[right]: count += 1 left -=1 right += 1 else: break return count
palindromic-substrings
Python Solution 78.6 % with simple For Loop
vijay_2022
0
7
palindromic substrings
647
0.664
Medium
10,805
https://leetcode.com/problems/palindromic-substrings/discuss/2741404/Best-Explanataion-of-optimize-way-for-solving-this-question
class Solution: def countSubstrings(self, s: str) -> int: # if len(set(s))==1: # return (len(s)*(len(s)+1))//2 count = 0 for i in range(len(s)): left = i right = i while left >-1 and right<len(s) : if s[left]==s[right]: count+=1 else: break left = left - 1 right = right +1 left = i right = i+1 while left >-1 and right<len(s) : if s[left]==s[right]: count+=1 else: break left = left - 1 right = right +1 return count
palindromic-substrings
Best Explanataion of optimize way for solving this question
darkgod
0
5
palindromic substrings
647
0.664
Medium
10,806
https://leetcode.com/problems/palindromic-substrings/discuss/2706773/Without-DP-O(n2)-complexity
class Solution: def countSubstrings(self, s: str) -> int: def count(i,j,st): count = 0 while i>=0 and j<len(st) and st[i]==st[j]: #print(st) count+=1 i-=1 j+=1 return count counter=0 for i in range(len(s)): counter+=count(i,i,s) for i in range(len(s)): counter+=count(i,i+1,s) return counter
palindromic-substrings
Without DP O(n^2) complexity
Chirayu07
0
10
palindromic substrings
647
0.664
Medium
10,807
https://leetcode.com/problems/palindromic-substrings/discuss/2689603/10-line-easy-understand-python
class Solution: def count(self, s, left, right): ans = 0 while left>=0 and right<len(s) and s[left]==s[right]: ans+=1 left-=1 right+=1 return ans def countSubstrings(self, s: str) -> int: return sum(self.count(s,i,i)+self.count(s,i,i+1) for i in range(len(s)))
palindromic-substrings
10 line easy understand python
Ttanlog
0
7
palindromic substrings
647
0.664
Medium
10,808
https://leetcode.com/problems/palindromic-substrings/discuss/2671213/Pyrhon-Solution-EASY-oror-BEGINNER-FRIENDLY
class Solution: def countSubstrings(self, s: str) -> int: n=len(s) c=0 for i in range(n): for j in range(i+1,n+1): st="" if s[i:j]==st.join(reversed(s[i:j])): c+=1 return c
palindromic-substrings
Pyrhon Solution - EASY || BEGINNER FRIENDLY
T1n1_B0x1
0
84
palindromic substrings
647
0.664
Medium
10,809
https://leetcode.com/problems/palindromic-substrings/discuss/2647884/Python-or-DP-No-Memo-Easy-or-Fast
class Solution: def countSubstrings(self, s: str) -> int: res = 0 for i in range(len(s)): res += 1 #check odd l, r = i - 1, i + 1 while l >= 0 and r < len(s) and s[l] == s[r]: res += 1 l -= 1 r += 1 l, r = i - 1, i while l >= 0 and r < len(s) and s[l] == s[r]: res += 1 l -= 1 r += 1 return res
palindromic-substrings
Python | DP No Memo Easy | Fast
AlgosWithDylan
0
145
palindromic substrings
647
0.664
Medium
10,810
https://leetcode.com/problems/palindromic-substrings/discuss/2601256/Simple-python-code-with-explanation
class Solution: def countSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)): #odd case l,r = i,i while l >= 0 and r < len(s) and s[l] == s[r]: count = count + 1 l = l -1 r = r + 1 #even case l,r = i,i+1 while l >= 0 and r < len(s) and s[l] == s[r]: count = count + 1 l -=1 r +=1 return count
palindromic-substrings
Simple python code with explanation
thomanani
0
76
palindromic substrings
647
0.664
Medium
10,811
https://leetcode.com/problems/palindromic-substrings/discuss/2581299/Python-Easy-to-understand-solution
class Solution: def countSubstrings(self, s: str) -> int: res = 0 for i in range(len(s)): #This is for odd length palindromes left = i right = i while left>=0 and right<len(s) and s[left] == s[right]: res+=1 left-=1 right+=1 #This is for even length palindromes left = i right = i+1 while left>=0 and right<len(s) and s[left] == s[right]: res+=1 left-=1 right+=1 return res
palindromic-substrings
Python Easy to understand solution
Ron99
0
74
palindromic substrings
647
0.664
Medium
10,812
https://leetcode.com/problems/palindromic-substrings/discuss/2563896/Kenn
class Solution: def countSubstrings(self, s: str) -> int: n = len(s) count = 0 for i in range(n): for j in range(i+1,n+1): substring = s[i:j] if substring == substring[::-1]: count += 1 return count
palindromic-substrings
Kenn
KuangSu
0
19
palindromic substrings
647
0.664
Medium
10,813
https://leetcode.com/problems/palindromic-substrings/discuss/2496531/python3
class Solution: def countSubstrings(self, s: str) -> int: n = len(s) t = ['$', '#'] for i in range(n): t.append(s[i]) t.append('#') n = len(t) t.append('!') t = ''.join(t) f = [0] * n iMax = 0 rMax = 0 ans = 0 for i in range(1, n): f[i] = min(rMax - i + 1, f[(iMax << 1) - i]) if i <= rMax else 1 while t[i + f[i]] == t[i - f[i]]: f[i] += 1 if i + f[i] - 1 > rMax: iMax = i rMax = i + f[i] - 1 ans += f[i] >> 1 return ans
palindromic-substrings
python3
xy01
0
137
palindromic substrings
647
0.664
Medium
10,814
https://leetcode.com/problems/palindromic-substrings/discuss/2467697/Python-short-and-fastest-solution-beats-90-without-dynammic-programming.
class Solution(object): def countSubstrings(self, s): l=len(s) self.c=0 def helper(start,stop): while start>=0 and stop<l and s[start]==s[stop]: self.c+=1 start-=1 stop+=1 for i in range(l): helper(i,i) if i+1<l: helper(i,i+1) return self.c
palindromic-substrings
Python short and fastest solution beats 90% without dynammic programming.
babashankarsn
0
136
palindromic substrings
647
0.664
Medium
10,815
https://leetcode.com/problems/palindromic-substrings/discuss/2464543/Python-or-Simple-Solution
class Solution: def countSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)): # check if odd Palindromic substring with s[i] as middle element # it wil also add single element from string l = i r = i while l>=0 and r < len(s) and s[l]==s[r]: count += 1 l -=1 r += 1 # check if even Palindromic substring with s[i] and s[i+1] as middle elements l = i r = i+1 while l>=0 and r < len(s) and s[l]==s[r]: count += 1 l -=1 r += 1 return count
palindromic-substrings
Python | Simple Solution
AshishGohil
0
70
palindromic substrings
647
0.664
Medium
10,816
https://leetcode.com/problems/palindromic-substrings/discuss/2269401/Python-3-oror-Dynamic-Programming
class Solution: def countSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)): l, r = i, i while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 count += 1 l, r = i, i + 1 while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 count += 1 return count
palindromic-substrings
Python 3 || Dynamic Programming
sagarhasan273
0
104
palindromic substrings
647
0.664
Medium
10,817
https://leetcode.com/problems/palindromic-substrings/discuss/2233049/Python-Beats-95-with-full-working-explanation
class Solution: # same explanation as longest palindrome substring def countSubstrings(self, s: str) -> int: # Time: O(n*n) and Space:O(1) res = 0 for i in range(len(s)): # in this we will check both odd and even as a single odd char is a palindrome and even neighbours can be palindrome too res += self.palindrome(s, i, i) # checking self, then left and right for odd number of elements res += self.palindrome(s, i, i + 1) # current and next character when checking for even number of elements return res def palindrome(self, s, l, r): res = 0 while l >= 0 and r < len(s) and s[l] == s[r]: res += 1 l -= 1 r += 1 return res
palindromic-substrings
Python Beats 95% with full working explanation
DanishKhanbx
0
155
palindromic substrings
647
0.664
Medium
10,818
https://leetcode.com/problems/palindromic-substrings/discuss/2212385/Python3-or-Faster-than-90.16-or-Simple-or-Easy-to-Understand
class Solution: def countSubstrings(self, s: str) -> int: n = len(s) def count(l, r): count = 0 while l >= 0 and r < n and s[l] == s[r]: count += 1 l -= 1 r += 1 return count result = 0 for i in range(n): count_odd = count(i, i) count_even = count(i, i+1) result += (count_odd + count_even) return result
palindromic-substrings
✅Python3 | Faster than 90.16% | Simple | Easy to Understand
thesauravs
0
88
palindromic substrings
647
0.664
Medium
10,819
https://leetcode.com/problems/palindromic-substrings/discuss/2157148/python-3-or-expand-around-center-or-O(n2)O(1)
class Solution: def countSubstrings(self, s: str) -> int: n = len(s) count = 0 for center in range(2*n - 1): i = center // 2 j = i + center % 2 while i != -1 and j != n and s[i] == s[j]: count += 1 i -= 1 j += 1 return count
palindromic-substrings
python 3 | expand around center | O(n^2)/O(1)
dereky4
0
56
palindromic substrings
647
0.664
Medium
10,820
https://leetcode.com/problems/palindromic-substrings/discuss/2127565/Python3-oror-DPororO(n2)-time-oror-O(N2)-Space
class Solution: def countSubstrings(self, s: str) -> int: ans = 0 n = len(s) dp = [[False for c in range(n)]for r in range(n)] for r in range(n-1,-1,-1): for c in range(r,n): #length = 1 if r == c: dp[r][c] = True ans += 1 #length = 2 elif c == r + 1: if s[r] == s[c]: dp[r][c] = True ans += 1 #length > 2 else: if s[r] == s[c] and dp[r+1][c-1] == True: dp[r][c] = True ans += 1 return ans
palindromic-substrings
Python3 || DP||O(n^2) time || O(N^2) Space
s_m_d_29
0
100
palindromic substrings
647
0.664
Medium
10,821
https://leetcode.com/problems/palindromic-substrings/discuss/2077421/Python-3-solved-using-two-pointer-method-faster-than-DP
class Solution: def countSubstrings(self, s: str) -> int: str_len = len(s) if str_len == 1: return 1 max_number_of_substring = 0 for start in range(str_len): odd_f_pointer = start odd_s_pointer = start even_f_pointer = start even_s_pointer = start + 1 # if the length of the palindromic string is odd, then we start from middle and then go to the left and right while odd_f_pointer >= 0 and odd_s_pointer < str_len: if s[odd_f_pointer] == s[odd_s_pointer]: # print("odd, s[{}] = {}, s[{}] = {}".format(odd_f_pointer, s[odd_f_pointer], odd_s_pointer, s[odd_s_pointer])) max_number_of_substring += 1 odd_f_pointer -= 1 odd_s_pointer += 1 else: break # if the length of the palindromic string is even, then we place two pointers located side by side and then go to the left and right while even_f_pointer >= 0 and even_s_pointer < str_len: if s[even_f_pointer] == s[even_s_pointer]: # print("even, s[{}] = {}, s[{}] = {}".format(even_f_pointer, s[even_f_pointer], even_s_pointer, # s[even_s_pointer])) max_number_of_substring += 1 even_f_pointer -= 1 even_s_pointer += 1 else: break # print(max_number_of_substring) return max_number_of_substring
palindromic-substrings
Python 3 - solved using two pointer method - faster than DP
Shaurov05
0
91
palindromic substrings
647
0.664
Medium
10,822
https://leetcode.com/problems/palindromic-substrings/discuss/2066093/Python-3-Solution
class Solution: def countSubstrings(self, s: str) -> int: """ Description => Possibly there are 2 types of palindromic substring i.e., even and odd length. Approach => We'll be using 2 pointers for checking palindromic substring. ===> For even length strings we will keep our pointers as: left = value and right = left + 1 ===> For odd length strings we will keep our pointers as : left = right = value """ # For storing result result = 0 # Firstly we will loop over a string for i in range(len(s)): result += self.checkPalindrome(s,i,i) result += self.checkPalindrome(s,i,i+1) return result def checkPalindrome(self,s,left,right): result = 0 while left >=0 and right < len(s) and s[left] == s[right]: result += 1 left -= 1 right += 1 return result
palindromic-substrings
✅ Python 3 Solution
mitchell000
0
24
palindromic substrings
647
0.664
Medium
10,823
https://leetcode.com/problems/palindromic-substrings/discuss/2065025/Python-solution-using-Expanding-around-the-center-Technique
class Solution: def countSubstrings(self, s: str) -> int: res = 0 for i in range(len(s)): res += self.helper(s, i, i) res += self.helper(s, i, i+1) return res def helper(self, string, start, end): val = 0 while start >= 0 and end < len(string) and string[start] == string[end]: start -= 1 end += 1 val += 1 return val
palindromic-substrings
Python solution using Expanding around the center Technique
PythonicLava
0
84
palindromic substrings
647
0.664
Medium
10,824
https://leetcode.com/problems/palindromic-substrings/discuss/2063267/Python-Very-simple-O(n2)-solution-using-nested-for-loops
class Solution: def countSubstrings(self, s: str) -> int: ans=0 for i in range(len(s)): for j in range(i,len(s)): substring=s[i:j+1] if substring==substring[::-1]: ans+=1 return ans
palindromic-substrings
[Python] Very simple O(n^2) solution using nested for loops
franzgoerlich
0
31
palindromic substrings
647
0.664
Medium
10,825
https://leetcode.com/problems/palindromic-substrings/discuss/2063253/java-python-DFS-and-memoization
class Solution: def __init__(self): self.keys = dict() self.answer = 0 def countSubstrings(self, s: str) -> int: def DFS(s, l, r) : key = (l<<10) + r if key in self.keys: return if l == r : self.answer += 1 self.keys[key] = True else : DFS(s, l+1, r) DFS(s, l, r-1) if s[l] == s[r] and (r - l == 1 or self.keys[((l+1)<<10) + r - 1] == True ) : self.answer +=1 self.keys[key] = True else : self.keys[key] = False DFS(s, 0, len(s) - 1) return self.answer
palindromic-substrings
java, python - DFS & memoization
ZX007java
0
34
palindromic substrings
647
0.664
Medium
10,826
https://leetcode.com/problems/palindromic-substrings/discuss/2063250/Simple-Python-Code-%3A-Easy-to-understand
class Solution: def countSubstrings(self, s: str) -> int: c = 0 for i in range(0,len(s)): for j in range(0,len(s)-i+1): if (s[i:i+j] == s[i:i+j][::-1]) and s[i:i+j] !="": c=c+1 return(c) '''
palindromic-substrings
Simple Python Code : Easy to understand
user2066i
0
23
palindromic substrings
647
0.664
Medium
10,827
https://leetcode.com/problems/palindromic-substrings/discuss/2063195/Python3-Solution-with-using-dp
class Solution: def countSubstrings(self, s: str) -> int: dp = [[False for _ in range(len(s))] for _ in range(len(s))] pal_sub_cnt = 0 for i in range(len(s)): dp[i][i] = True # single char - it is substring and palindrome pal_sub_cnt += 1 for i in range(len(s) - 2, -1, -1): for j in range(i + 1, len(s)): if s[i] == s[j]: """ j - 1 == 1 - means such substr "aa". two equals adj symbols - its substr_pal dp[i + 1][j - 1] - show that subs betw two equals symbsl palindrome = > all substr - palindrome ("a????a") if ???? - palindrome = > a????a palidrome """ if j - i == 1 or dp[i + 1][j - 1]: dp[i][j] = True pal_sub_cnt += 1 return pal_sub_cnt
palindromic-substrings
[Python3] Solution with using dp
maosipov11
0
28
palindromic substrings
647
0.664
Medium
10,828
https://leetcode.com/problems/palindromic-substrings/discuss/2063031/Python-or-Two-Different-Solution-Using-Iterative-and-DP-approach
class Solution: def countSubstrings(self, s: str) -> int: # /////////// Solution 1 iterative ///////////// ''' The first approach is very easy to understand and even efficient then DP. Idea is very simple we will expand from middle of any ith element and will keep checking boundary and palindromic condition. Let say, a b a <- ^ -> expanding in this way from the ith element of the string. Hope got the idea else go through code it will be easy to understand. ''' def countPalindrome(s,l,r): res = 0 while l >= 0 and r <= len(s)-1 and s[l] == s[r]: res += 1 l -= 1 r += 1 return res res = 0 # //////// for odd length string //////// for i in range(len(s)): l = r = i res += countPalindrome(s,l,r) # ////// for even length string /////////// for i in range(len(s)): l = i r = i + 1 res += countPalindrome(s,l,r) return res # /////////// Solution 2 Using DP //////////// res = 0 slen = len(s) dp = [[False for _ in range(slen)] for _ in range(slen)] for i in range(slen-1,-1,-1): dp[i][i] = True res = res + 1 for j in range(i+1,slen): if j - i == 1 : if s[i] == s[j]: dp[i][j] = True else: dp[i][j] = False else: if s[i] == s[j] and dp[i+1][j-1] == True: dp[i][j] = True else: dp[i][j] = False if dp[i][j] == True: res = res + 1 return res
palindromic-substrings
Python | Two Different Solution Using Iterative and DP approach
__Asrar
0
27
palindromic substrings
647
0.664
Medium
10,829
https://leetcode.com/problems/palindromic-substrings/discuss/1936362/Python-Easy-to-Follow
class Solution: def countSubstrings(self, s: str) -> int: count = 0 length = len(s) for i in range(length): count += self.getNumPalindromes(s, i, i, length) # Single letter base count += self.getNumPalindromes(s, i, i + 1, length) # Double letter base return count def getNumPalindromes(self, s, left, right, length): count = 0 while left >= 0 and right < length and s[left] == s[right]: count += 1 left -= 1 right += 1 return count
palindromic-substrings
Python Easy to Follow
doubleimpostor
0
135
palindromic substrings
647
0.664
Medium
10,830
https://leetcode.com/problems/palindromic-substrings/discuss/1885540/Very-Easy-Simple-and-Fast-Python-Solution-Check-it-out-%3A)
class Solution: def countSubstrings(self, s: str) -> int: count = 0 for l in range(len(s)): count += Solution.check(l,l,s) count += Solution.check(l,l+1,s) return count @staticmethod def check(l, r, s): count = 0 while(l>=0 and r<len(s)): if s[l] == s[r]: count +=1 else: break l-=1 r+=1 return count
palindromic-substrings
Very Easy, Simple and Fast Python Solution [Check it out] :)
iamrobins
0
123
palindromic substrings
647
0.664
Medium
10,831
https://leetcode.com/problems/replace-words/discuss/1576514/Fast-solution-beats-97-submissions
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: d = {w:len(w) for w in dictionary} mini, maxi = min(d.values()), max(d.values()) wd = sentence.split() rt = [] for s in wd: c = s for k in range(mini,min(maxi,len(s))+1): ss = s[:k] if ss in d: c = ss break rt.append(c) return " ".join(rt)
replace-words
Fast solution beats 97% submissions
cyrille-k
3
118
replace words
648
0.627
Medium
10,832
https://leetcode.com/problems/replace-words/discuss/1324974/Python-or-Easy-to-understand
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: sentence = sentence.split() operated = [] for word in dictionary : k = len(word) for i in range(len(sentence)): if sentence[i][:k] == word : if i not in operated : sentence[i] = word operated.append(i) else: if len(word) < len(sentence[i]) : sentence[i] = word return " ".join(sentence)
replace-words
Python | Easy to understand
abhijeetgupto
2
138
replace words
648
0.627
Medium
10,833
https://leetcode.com/problems/replace-words/discuss/353533/Solution-in-Python-3-(beats-100)-(no-trie)
class Solution: def replaceWords(self, dict: List[str], sentence: str) -> str: D, s = {}, sentence.split() for d in dict: if d[0] in D: D[d[0]].append([d,len(d)]) else: D[d[0]] = [[d,len(d)]] for i in D: D[i].sort(key = lambda x: x[1]) for i,j in enumerate(s): f, t = j[0], len(j) if f not in D: continue for a,b in D[f]: if b > t: break if a == j[:b]: s[i] = a break return " ".join(s) - Junaid Mansuri (LeetCode ID)@hotmail.com
replace-words
Solution in Python 3 (beats 100%) (no trie)
junaidmansuri
2
271
replace words
648
0.627
Medium
10,834
https://leetcode.com/problems/replace-words/discuss/547589/Pythonic-Solution-Simple
class Solution: def replaceWords(self, roots: List[str], sentence: str) -> str: sentence = sentence.split() for root in roots: for i, word in list(enumerate(sentence)): if word.startswith(root): sentence[i] = root return " ".join(c for c in sentence)
replace-words
Pythonic Solution - Simple
cppygod
1
193
replace words
648
0.627
Medium
10,835
https://leetcode.com/problems/replace-words/discuss/2827776/Sorted-dictionary-or-Python3
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: sen = sentence.split(' ') dic = sorted(dictionary) for i, word in enumerate(sen): for root in dic: if word[:len(root)] == root: sen[i] = root break return ' '.join(sen)
replace-words
Sorted dictionary | Python3
joshua_mur
0
3
replace words
648
0.627
Medium
10,836
https://leetcode.com/problems/replace-words/discuss/2813499/Python-Easy-understand-Trie-Method
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: trie=Trie() out=[] words=sentence.split(" ") for word in dictionary: trie.insert(word) for word in words: out.append(trie.transfer(word)) return " ".join(out) class TrieNode(object): def __init__(self): self.children = {} self.isWord = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str) -> None: node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.isWord = True def transfer(self, successor: str) -> bool: node = self.root out="" for char in successor: if node.isWord: return out if char not in node.children: return successor out+=char node = node.children[char] return successor
replace-words
[Python] Easy understand Trie Method
Hikari-Tsai
0
3
replace words
648
0.627
Medium
10,837
https://leetcode.com/problems/replace-words/discuss/2788030/Python-Concise-Solution
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: split_sentence = sentence.split() s = set(dictionary) for i, word in enumerate(split_sentence): # This way can replace shortest dict for j in range(1, len(word)): if word[:j] in s: split_sentence[i] = word[:j] break return ' '.join(split_sentence)
replace-words
Python Concise Solution
namashin
0
2
replace words
648
0.627
Medium
10,838
https://leetcode.com/problems/replace-words/discuss/2779071/Replace-Words-easy-understanding
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: d=set(dictionary) #result ->store the output result=[] for word in sentence.split(' '): Found=False #this variable is used to append the other words for x in range(1,len(word)): if word[0:x] in d: Found=True result.append(word[0:x]) break if not Found: result.append(word) return " ".join(result)
replace-words
Replace Words-easy understanding
RaviShanker__Thadishetti
0
8
replace words
648
0.627
Medium
10,839
https://leetcode.com/problems/replace-words/discuss/2709833/Beat-96-or-Simple-and-Easy-to-Understand-or-Python
class Solution(object): def replaceWords(self, d, s): hashT = {} for word in d: hashT[word] = 1 word, ans, flag = '', '', False for ch in s: if ch == ' ': if ans == '': ans += word else: ans += ' ' + word flag, word = False, '' else: if not(flag): word += ch if word in hashT: flag = True return ans + ' ' + word
replace-words
Beat 96% | Simple and Easy to Understand | Python
its_krish_here
0
4
replace words
648
0.627
Medium
10,840
https://leetcode.com/problems/replace-words/discuss/2592260/Python-Trie-Solution
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: root = defaultdict(dict) output = '' for word in dictionary: word += '.' current = root for c in word: if c not in current: current[c] = defaultdict(dict) current = current[c] words = sentence.split() for i, word in enumerate(words): current = root s = '' for c in word: if c not in current: break if '.' in current: break current = current[c] s += c if '.' in current: output += s else: output += word if i < len(words) - 1: output += ' ' return output
replace-words
Python Trie Solution
mansoorafzal
0
14
replace words
648
0.627
Medium
10,841
https://leetcode.com/problems/replace-words/discuss/2576117/Trie-Implementation-Python-3
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: trie = {} for word in dictionary: ptr = trie for letter in word: if 'end' in ptr: break if letter not in ptr: ptr[letter] = {} ptr = ptr[letter] ptr['end'] = '' result = '' for word in sentence.split(" "): ptr = trie for i,letter in enumerate(word): if letter not in ptr or i == len(word)-1: result += word + ' ' break ptr = ptr[letter] if 'end' in ptr: result += word[:i+1] + " " break return result[:-1]
replace-words
Trie Implementation Python 3
Dio-Noob
0
6
replace words
648
0.627
Medium
10,842
https://leetcode.com/problems/replace-words/discuss/2523743/Python-or-Easy-to-read-solution
class Solution: def replaceWords(self, words: List[str], sentence: str) -> str: s_words = sentence.split() for word in words: shortest = None for i, s_word in enumerate(s_words): if word in s_word[:len(word)]: if not shortest: shortest = word s_words[i] = min(shortest, word, key=len) return(' '.join(s_words))
replace-words
Python | Easy to read solution
Wartem
0
22
replace words
648
0.627
Medium
10,843
https://leetcode.com/problems/replace-words/discuss/2493769/easy-python-solution
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: sorted_dict = [] for word in dictionary : sorted_dict.append([word, len(word)]) sorted_dict = sorted(sorted_dict, key = lambda x : x[1]) ans = "" split_sentence = sentence.split() for word in split_sentence : for root in sorted_dict : if root[0] == word[:len(root[0])] : ans += root[0] + ' ' break else : ans += word + " " return ans[:-1]
replace-words
easy python solution
sghorai
0
24
replace words
648
0.627
Medium
10,844
https://leetcode.com/problems/replace-words/discuss/2149878/Python-easy-solution-without-Trie
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: # Simple Brute-force solution using startswith function in python. # T(n)=O(n^2) dict=sorted(dictionary ,key=lambda x:x[0]) arr=[i for i in sentence.split(" ")] for i in range(len(arr)): for j in dictionary: if arr[i].startswith(j): arr[i]=j return " ".join(i for i in arr)
replace-words
Python easy solution without Trie
Aniket_liar07
0
39
replace words
648
0.627
Medium
10,845
https://leetcode.com/problems/replace-words/discuss/2032366/Python-oror-Very-Easy-Solution
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: dictionary , sentence, new_sentence = set(dictionary), sentence.split(' '), [] n = len(sentence) for word in sentence: search, signal = '', 0 for letter in word: search += letter if search in dictionary: new_sentence.append(search) signal = 1 break if not signal: new_sentence.append(word) return ' '.join(new_sentence)
replace-words
Python || Very Easy Solution
morpheusdurden
0
67
replace words
648
0.627
Medium
10,846
https://leetcode.com/problems/replace-words/discuss/1725705/Hashmap-simple-solution-easy-to-undestand
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: res = [] for word in sentence.split(" "): n = len(word) spare = word for i in range(1,n): if word[:i] in dictionary: res.append(word[:i]) break else: res.append(word) return " ".join(res)
replace-words
Hashmap, simple solution, easy to undestand
aaronat
0
46
replace words
648
0.627
Medium
10,847
https://leetcode.com/problems/replace-words/discuss/1601506/Python3-solution-hash-map
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: d_table = dict.fromkeys(dictionary) s_l = sentence.split() for i,v in enumerate(s_l): r = 1 while r < len(v): subs = v[:r] if subs in d_table: s_l[i] = subs break r += 1 return ' '.join(s_l)
replace-words
Python3 solution hash map
x0jellio
0
45
replace words
648
0.627
Medium
10,848
https://leetcode.com/problems/replace-words/discuss/1582158/Python-3-faster-than-95-without-trie
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: lens = list(map(len, dictionary)) short, long = min(lens), max(lens) dictionary = set(dictionary) res = '' for word in sentence.split(): n = len(word) if n < short: res += word + ' ' continue cur = '' for i in range(min(n, long)): cur += word[i] if cur in dictionary: res += cur + ' ' break else: res += word + ' ' return res.strip()
replace-words
Python 3 faster than 95% without trie
dereky4
0
78
replace words
648
0.627
Medium
10,849
https://leetcode.com/problems/replace-words/discuss/1454498/Replace-Words-in-Python3-Simple-Code
class Solution(object): def replaceWords(self, dictionary, sentence): dictionary.sort() sentence = sentence.split() for d in dictionary: for idx,item in enumerate(sentence): if item.startswith(d): sentence[idx] = d return " ".join(sentence) ```
replace-words
Replace Words in Python3 Simple Code
Mukesh6877
0
47
replace words
648
0.627
Medium
10,850
https://leetcode.com/problems/replace-words/discuss/1422602/Python3-simple-solution
class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: s = sentence.split() dictionary.sort(key=lambda x:len(x)) for i,j in enumerate(s): for v in dictionary: if j.startswith(v): s[i] = v break return ' '.join(s)
replace-words
Python3 simple solution
EklavyaJoshi
0
45
replace words
648
0.627
Medium
10,851
https://leetcode.com/problems/dota2-senate/discuss/845912/Python-3-or-Greedy-Simulation-or-Explanantion
class Solution: def predictPartyVictory(self, senate: str) -> str: n = len(senate) s, banned = set(), [False] * n ban_d = ban_r = 0 while len(s) != 1: s = set() for i, p in enumerate(senate): if banned[i]: continue if p == 'R': if ban_r > 0: # current R being banned ban_r -= 1 banned[i] = True else: # if current R is valid, it will ban D ban_d += 1 s.add('R') else: if ban_d > 0: # current D being banned ban_d -= 1 banned[i] = True else: # if current D is valid, it will ban R ban_r += 1 s.add('D') return 'Radiant' if s.pop() == 'R' else 'Dire'
dota2-senate
Python 3 | Greedy, Simulation | Explanantion
idontknoooo
8
690
dota2 senate
649
0.404
Medium
10,852
https://leetcode.com/problems/dota2-senate/discuss/888702/Python3-simulation-via-two-deques
class Solution: def predictPartyVictory(self, senate: str) -> str: radiant, dire = deque(), deque() for i, x in enumerate(senate): if x == "R": radiant.append(i) else: dire.append(i) while radiant and dire: if radiant[0] < dire[0]: radiant.append(radiant.popleft()+len(senate)) dire.popleft() else: radiant.popleft() dire.append(dire.popleft()+len(senate)) return "Radiant" if radiant else "Dire"
dota2-senate
[Python3] simulation via two deques
ye15
1
113
dota2 senate
649
0.404
Medium
10,853
https://leetcode.com/problems/dota2-senate/discuss/2577142/python-short-solution-using-greedy-and-queue
class Solution: def predictPartyVictory(self, senate: str) -> str: R_idx = deque([i for i in range(len(senate)) if senate[i]=='R']) D_idx = deque([j for j in range(len(senate)) if senate[j]=='D']) n = len(senate) while R_idx and D_idx: r = R_idx.popleft() d = D_idx.popleft() if r < d: R_idx.append(n + r) else: D_idx.append(n + d) return 'Radiant' if R_idx else 'Dire'
dota2-senate
python short solution using greedy and queue
benon
0
38
dota2 senate
649
0.404
Medium
10,854
https://leetcode.com/problems/dota2-senate/discuss/2499530/Hashset-python3-solution
class Solution: # O(n) time, # O(n) space, # Approach: greedy, hashset def predictPartyVictory(self, senate: str) -> str: n = len(senate) count = Counter(senate) skip_r = 0 skip_d = 0 removed_r = set() removed_d = set() while count['D'] > 0 and count['R'] > 0: for i in range(n): s = senate[i] if s == 'R': if skip_r <= 0 and i not in removed_r: count['D'] -=1 skip_d +=1 else: if i not in removed_r: skip_r -=1 removed_r.add(i) else: if skip_d <= 0 and i not in removed_d: count['R'] -=1 skip_r +=1 else: if i not in removed_d: skip_d -=1 removed_d.add(i) if count['D'] > 0: return 'Dire' else: return 'Radiant'
dota2-senate
Hashset python3 solution
destifo
0
27
dota2 senate
649
0.404
Medium
10,855
https://leetcode.com/problems/dota2-senate/discuss/2477900/Python-oror-easy-to-understand-simulation
class Solution: def predictPartyVictory(self, senate: str) -> str: d, r = senate.count("D"), senate.count("R") killedR, killedD = 0, 0 deleted = set() while d and r: for idx,letter in enumerate(senate): if idx in deleted: continue if letter == "R" and killedR == 0: killedD += 1 d -= 1 elif letter == "D" and killedD == 0: killedR += 1 r -= 1 elif letter == "R" and killedR > 0: deleted.add(idx) killedR -= 1 else: deleted.add(idx) killedD -= 1 return "Dire" if d else "Radiant"
dota2-senate
Python || easy to understand simulation
Damurulife
0
27
dota2 senate
649
0.404
Medium
10,856
https://leetcode.com/problems/2-keys-keyboard/discuss/727856/Python3-Dynamic-Programming-Beginners
class Solution: def minSteps(self, n: int) -> int: dp = [float('inf')] * (n+1) ## Intialize a dp array to store the solutions of sub problems i.e. number of steps needed dp[1] = 0 ## Intially first element of dp array with 0 as 'A' is already present and we haven't consumed any steps yet. ## As the value of n is from [1,3000] and initally 'A' is already present so we don't need to bother about the dp[0] divisors = [] ## This is to store the divisors of N for i in range(1, n//2 + 1): if n % i == 0: divisors.append(i) ## We have stored all the divisors. For n = 10, divisors = [1,2,5] for j in divisors: dp[j] += 1 ##To copy the current number of A's, we add one step for i in range(j+1, n+1): if i % j == 0: ## We can only form the string length which is divisible by j dp[i] = min(dp[i], dp[i-j] + 1) ## Compare with previous number of steps and update with the minimum return dp[-1] #Return last value of dp i.e. N
2-keys-keyboard
Python3 Dynamic Programming - Beginners
ayushjain94
12
1,000
2 keys keyboard
650
0.532
Medium
10,857
https://leetcode.com/problems/2-keys-keyboard/discuss/1587647/Python-Simple-Recursion-%2B-Memoization-Solution-with-Explanation
class Solution: def minSteps(self, n: int) -> int: cache = {} def helper(screen, clipboard): if (screen, clipboard) in cache: return cache[(screen, clipboard)] if screen == n: return 0 if screen > n: return float("Inf") copy_paste = helper(screen+screen, screen) + 2 paste = float("Inf") if clipboard: paste = helper(screen + clipboard, clipboard) + 1 cache[(screen, clipboard)] = min(copy_paste, paste) return cache[(screen, clipboard)] return helper(1, 0)
2-keys-keyboard
[Python] Simple Recursion + Memoization Solution with Explanation
Saksham003
10
351
2 keys keyboard
650
0.532
Medium
10,858
https://leetcode.com/problems/2-keys-keyboard/discuss/833225/simple-python3-or-dynamic-programic-or-memoization
class Solution: def Util(self, cur, stored, n, mem): if cur > n or stored > n: return sys.maxsize if cur == n: return 0 if (cur, stored) in mem: return mem[(cur, stored)] if stored == 0: return 1 + self.Util(cur, 1, n, mem) if cur != stored: ans = 1 + min(self.Util(cur + stored, stored, n, mem), self.Util(cur, cur, n, mem)) else: ans = 1 + self.Util(cur + stored, stored, n, mem) mem[(cur, stored)] = ans return ans def minSteps(self, n: int) -> int: if n == 0 or n == 1: return 0 mem = dict() return self.Util(1, 0, n, mem) # initially, we have 1'A' and 0 number of 'A's copied
2-keys-keyboard
simple python3 | dynamic programic | memoization
_YASH_
2
298
2 keys keyboard
650
0.532
Medium
10,859
https://leetcode.com/problems/2-keys-keyboard/discuss/2261926/Python-Simple-Python-Solution-or100-Optimal-Solution
class Solution: def minSteps(self, n: int) -> int: ans = 0 i = 2 while i*i<=n: if n%i == 0: ans+=i n/=i else: i+=1 if n!=1: ans+=n return(int(ans))
2-keys-keyboard
[ Python ] ✅ Simple Python Solution ✅✅|✅100% Optimal Solution
vaibhav0077
1
59
2 keys keyboard
650
0.532
Medium
10,860
https://leetcode.com/problems/2-keys-keyboard/discuss/931339/Simple-recursion-with-memorization-though-slower-than-the-math-solution
class Solution: def minSteps(self, n: int) -> int: def do(currSteps: int, currChars: int, copiedChars: int) -> int: if currChars > n: # Exceed. return float('inf') if currChars == n: # Done. return currSteps if (currChars, copiedChars) not in memo: # Either copy all and paste or paste only. memo[(currChars, copiedChars)] = min( do(currSteps + 2, currChars << 1, currChars), do(currSteps + 1, currChars + copiedChars, copiedChars)) return memo[(currChars, copiedChars)] if n == 1: return 0 if n == 2: return 2 memo = {} # {(currChars, copiedChars): minSteps}. return do(2, 2, 1)
2-keys-keyboard
Simple recursion with memorization, though slower than the math solution
eroneko
1
170
2 keys keyboard
650
0.532
Medium
10,861
https://leetcode.com/problems/2-keys-keyboard/discuss/515282/Easy-understand-solution-with-DP
class Solution: def minSteps(self, n: int) -> int: dp = [float('inf')]*(n) dp[0] = 0 for i in range(1, n): for j in range(i // 2 + 1): if (i + 1) % (j + 1) == 0: dp[i] = min(dp[i], dp[j] + (i + 1) // (j + 1)) return dp[-1]
2-keys-keyboard
Easy understand solution with DP
alanzhu_xiaozhi
1
254
2 keys keyboard
650
0.532
Medium
10,862
https://leetcode.com/problems/2-keys-keyboard/discuss/515282/Easy-understand-solution-with-DP
class Solution: def minSteps(self, n: int) -> int: dp = [float('inf')]*(n) dp[0] = 0 return self.helper(dp, n) def helper(self, dp, n): if dp[n - 1] != float('inf'): return dp[n - 1] for i in range(n // 2 + 1): if n % (i + 1) == 0: dp[n - 1] = min(dp[n - 1], self.helper(dp, i + 1) + n // (i + 1)) return dp[n - 1]
2-keys-keyboard
Easy understand solution with DP
alanzhu_xiaozhi
1
254
2 keys keyboard
650
0.532
Medium
10,863
https://leetcode.com/problems/2-keys-keyboard/discuss/2833025/Bottom-up-DP-Copy-or-Paste-python-simple-solution
class Solution: def minSteps(self, n: int) -> int: # either use original copy # or use new derived as copy # 0 1 2 3 4 5 6 7 # Null 1 2 3 4 5 6 7 8 # 0 1 1 0 0 0 0 0 0 0 # 1 2 2 3 0 0 0 0 0 0 # 2 3 3 0 4 0 0 0 0 0 # 3 4 4 4 0 5 0 0 0 0 # 4 5 5 0 0 0 6 0 0 0 # 5 6 6 5 5 0 0 6 0 0 # 6 7 7 0 0 0 0 0 8 0 # 7 8 8 6 0 6 0 0 0 7 if n == 1: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][0] = i + 1 for i in range(1, n): for j in range(1, i): k = i - j - 1 if dp[k][j] > 0: dp[i][j] = dp[k][j] + 1 dp[i][i] = min([x for x in dp[i] if x > 0]) + 1 return min([y for y in dp[n - 1] if y > 0])
2-keys-keyboard
Bottom-up DP / Copy or Paste / python simple solution
Lara_Craft
0
4
2 keys keyboard
650
0.532
Medium
10,864
https://leetcode.com/problems/2-keys-keyboard/discuss/2693489/naive-python-recursive-solution
class Solution: def minSteps(self, n: int) -> int: @functools.cache def f(i: int, clipboard: int) -> int: if i > n: return math.inf elif i == n: return 0 paste = f(i + clipboard, clipboard) if clipboard > 0 else math.inf copy = f(i, i) if i != clipboard else math.inf return 1 + min(copy, paste) return f(1, 0)
2-keys-keyboard
naive python recursive solution
jshin47
0
6
2 keys keyboard
650
0.532
Medium
10,865
https://leetcode.com/problems/2-keys-keyboard/discuss/2597444/(Without-DP-%2B-2-methods)-Self-Understandable-%3A%3A
class Solution: def minSteps(self, x: int) -> int: ans=0 while x>1: if x%2==0: ans+=2 x=x//2 else: a=True for i in reversed(range(3,(x//2)+1,2)): if x%i==0: a=False ans+=(x//i) x=i break if a: ans+=x break return ans
2-keys-keyboard
(Without DP + 2 methods) Self Understandable ::
goxy_coder
0
27
2 keys keyboard
650
0.532
Medium
10,866
https://leetcode.com/problems/2-keys-keyboard/discuss/2597444/(Without-DP-%2B-2-methods)-Self-Understandable-%3A%3A
class Solution: def minSteps(self, n: int) -> int: ans=0 for i in range(2,n+1): while n%i==0: ans+=i n=n//i return ans
2-keys-keyboard
(Without DP + 2 methods) Self Understandable ::
goxy_coder
0
27
2 keys keyboard
650
0.532
Medium
10,867
https://leetcode.com/problems/2-keys-keyboard/discuss/2359437/Python3-Solution-with-using-dp
class Solution: def minSteps(self, n: int) -> int: dp = [0] * (n + 1) dp[0], dp[1] = 0, 0 for i in range(2, n + 1): dp[i] = i for j in range(i - 1, 1, -1): if i % j == 0: """ + 1 - copy i // j - 1 paste (-1 because dp[j] num of op to getting of dp[j] => one j exist yet) n = 4 dp[2] = 2 4 // 2 = 2, but one "2" already exist (we collect this "2" early) = > 4 // 2 - 1 """ dp[i] = dp[j] + (i // j - 1) + 1 break return dp[-1]
2-keys-keyboard
[Python3] Solution with using dp
maosipov11
0
31
2 keys keyboard
650
0.532
Medium
10,868
https://leetcode.com/problems/2-keys-keyboard/discuss/2338684/Python3-EZ-SOLUTION
class Solution: def minSteps(self, n: int) -> int: i = 2 ans = 0 while i * i <= n: if n % i: i += 1 else: n //= i ans += i ans += n if n > 1 else 0 return ans
2-keys-keyboard
Python3 EZ SOLUTION
syji
0
15
2 keys keyboard
650
0.532
Medium
10,869
https://leetcode.com/problems/2-keys-keyboard/discuss/1999334/Python3-or-DP
class Solution: def minSteps(self, n: int) -> int: """ dp[4] = dp[2] * (4/ 2 - 1) dp[6] = dp[2] * (6 / 2 - 1) dp[6] = dp[3] * (6 / 3 - 1) """ # first 'A' can be copy with 1 operation # then paste n - 1 times # total 1 + n - 1 = n operation dp = [i for i in range(n + 1)] # 1 is already there, no operation needed dp[1] = 0 for i in range(2, n + 1): for j in range(2, i // 2 + 1): if i % j == 0: dp[i] = min( dp[i], dp[j] + (i // j) # copy all and paste ) #print(dp) # sanity check return dp[-1]
2-keys-keyboard
Python3 | DP
showing_up_each_day
0
77
2 keys keyboard
650
0.532
Medium
10,870
https://leetcode.com/problems/2-keys-keyboard/discuss/1983258/python-oror-recursion-%2B-memoization
class Solution: def minSteps(self, n: int) -> int: def stepsHelper(n, s, cop,dp): if len(s) == n: return 0 if len(s) > n: return float('inf') if (s,cop) in dp: return dp[s,cop] copy = float('inf') if cop != s: copy = 1 + stepsHelper(n,s,s,dp) paste = 1 + stepsHelper(n, s + cop, cop,dp) dp[s,cop] = min(copy, paste) return dp[s,cop] if n == 1: return 0 dp = {} return 1 + stepsHelper(n, "A", "A",dp)
2-keys-keyboard
python || recursion + memoization
Jashwanthk
0
45
2 keys keyboard
650
0.532
Medium
10,871
https://leetcode.com/problems/2-keys-keyboard/discuss/1858647/Python-or-Recursion
class Solution: def minSteps(self, n: int) -> int: ans=0 def dfs(ch,ops,lastcopy): nonlocal ans if len(ch)==n: ans=ops return True elif len(ch)>n: return False return dfs(ch+ch,ops+2,ch) or dfs(ch+lastcopy,ops+1,lastcopy) dfs('A',0,'') return ans
2-keys-keyboard
Python | Recursion
heckt27
0
28
2 keys keyboard
650
0.532
Medium
10,872
https://leetcode.com/problems/2-keys-keyboard/discuss/1815784/Easy-python-solution-using-dynamic-programming-with-comment
class Solution: def minSteps(self, n: int) -> int: if n == 1: return 0 # Let "0" at idx: 0 and "n" at idx: n, # cause in the worst case, we use "1" as template, so the ans for "n" is n dp = [i for i in range(n+1)] # Use diffent template to update each dp place. As the template grows bigger, it always maintain the smallest number we need to make this template. for i in range(2, n+1): # When we use "2" as template, for j in range(2, n // i + 1): # we update dp[4], dp[6], dp[8], etc. dp[i*j] = dp[i] + j return dp[-1]
2-keys-keyboard
Easy python solution using dynamic programming with comment
byroncharly3
0
61
2 keys keyboard
650
0.532
Medium
10,873
https://leetcode.com/problems/2-keys-keyboard/discuss/1161593/Using-Prime-Numbers-Fast-Solution-32-ms-(No-Dynammic-Programming)-No-Recursion
class Solution: def primeNumbers(self): prime = [True for i in range(1000 + 1)] p = 2 while (p * p <= 1000): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, 1000 + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False return prime def minSteps(self,n:int)->int: if n == 1: return 0 prime = self.primeNumbers() res = 0 for i in range(2,n+1): if n != 0: if prime[i]: while n%i == 0: res += i n = n//i else: break return res
2-keys-keyboard
Using Prime Numbers Fast Solution 32 ms - (No Dynammic Programming) - No Recursion
tgoel219
0
82
2 keys keyboard
650
0.532
Medium
10,874
https://leetcode.com/problems/2-keys-keyboard/discuss/1073549/While-Loop-with-CopyPaste-Methods
class Solution: def copy(self): self.copyVal = self.numA self.numMoves += 1 def paste(self): self.numA += self.copyVal self.numMoves += 1 def minSteps(self, n: int) -> int: self.numA = 1 self.copyVal = 0 self.numMoves = 0 if(self.numA != n): self.copy() self.paste() while(self.numA < n): if( (n % 2 == 0 and self.numA < (n/2) and (n/self.numA) % 2 == 0) or n % self.numA == 0): self.copy() self.paste() else: self.paste() return self.numMoves
2-keys-keyboard
While Loop with Copy/Paste Methods
Cybergear
0
63
2 keys keyboard
650
0.532
Medium
10,875
https://leetcode.com/problems/2-keys-keyboard/discuss/894930/Python3-prime-factorization
class Solution: def minSteps(self, n: int) -> int: @lru_cache(None) def fn(n): """Return the minimum number of steps to get n 'A's.""" if n == 1: return 0 return min(fn(i) + n//i for i in range(1, n//2+1) if n%i == 0) return fn(n)
2-keys-keyboard
[Python3] prime factorization
ye15
0
131
2 keys keyboard
650
0.532
Medium
10,876
https://leetcode.com/problems/2-keys-keyboard/discuss/894930/Python3-prime-factorization
class Solution: def minSteps(self, n: int) -> int: ans = 0 for i in range(2, n+1): while n and n%i == 0: ans += i n //= i return ans
2-keys-keyboard
[Python3] prime factorization
ye15
0
131
2 keys keyboard
650
0.532
Medium
10,877
https://leetcode.com/problems/2-keys-keyboard/discuss/894930/Python3-prime-factorization
class Solution: def minSteps(self, n: int) -> int: for i in range(2, int(sqrt(n)+1)): if n%i == 0: return i + self.minSteps(n//i) return 0 if n == 1 else n
2-keys-keyboard
[Python3] prime factorization
ye15
0
131
2 keys keyboard
650
0.532
Medium
10,878
https://leetcode.com/problems/2-keys-keyboard/discuss/833784/Python3-(97-faster)
class Solution: def minSteps(self, n: int) -> int: ans=0 for d in range(2,n+1): while n%d==0: ans+=d n/=d if n<d: break return ans
2-keys-keyboard
Python3 (97% faster)
harshitCode13
0
139
2 keys keyboard
650
0.532
Medium
10,879
https://leetcode.com/problems/find-duplicate-subtrees/discuss/1178526/Easy-%2B-Clean-%2B-Straightforward-Python-Recursive
class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: seen = collections.defaultdict(int) res = [] def helper(node): if not node: return sub = tuple([helper(node.left), node.val, helper(node.right)]) if sub in seen and seen[sub] == 1: res.append(node) seen[sub] += 1 return sub helper(root) return res
find-duplicate-subtrees
Easy + Clean + Straightforward Python Recursive
Pythagoras_the_3rd
15
1,100
find duplicate subtrees
652
0.565
Medium
10,880
https://leetcode.com/problems/find-duplicate-subtrees/discuss/2510900/Python-99-Faster
class Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: mapped = {} ans = set() def duplicated(node): if not node: return '#' s = '' if not node.left and not node.right: s += str(node.val) mapped[s] = mapped.get(s,0)+1 if mapped[s]==2: ans.add(node) return s s = s + str(node.val) s = s + "," + duplicated(node.left) s = s+ "," + duplicated(node.right) mapped[s] = mapped.get(s,0)+1 if mapped[s]==2: ans.add(node) return s duplicated(root) return ans
find-duplicate-subtrees
Python 99% Faster
Abhi_009
1
135
find duplicate subtrees
652
0.565
Medium
10,881
https://leetcode.com/problems/find-duplicate-subtrees/discuss/1467842/Python-Clean-Recursive-DFS
class Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: def dfs(node = root): if not node: return '.' subtree = dfs(node.left) + '-' + dfs(node.right) + '-' + str(node.val) if count[subtree] == 1: duplicates.append(node) count[subtree] += 1 return subtree count, duplicates = defaultdict(int), [] dfs() return duplicates
find-duplicate-subtrees
[Python] Clean Recursive DFS
soma28
1
540
find duplicate subtrees
652
0.565
Medium
10,882
https://leetcode.com/problems/find-duplicate-subtrees/discuss/1467842/Python-Clean-Recursive-DFS
class Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: def dfs(node = root): if not node: return '.' subtree = str(node.val) + '-' + dfs(node.left) + '-' + dfs(node.right) if count[subtree] == 1: duplicates.append(node) count[subtree] += 1 return subtree count, duplicates = defaultdict(int), [] dfs() return duplicates
find-duplicate-subtrees
[Python] Clean Recursive DFS
soma28
1
540
find duplicate subtrees
652
0.565
Medium
10,883
https://leetcode.com/problems/find-duplicate-subtrees/discuss/1208429/Python-Hashable-Class!
class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: counts = collections.Counter() def dfs(node): if not node: return dfs(node.left) counts[Wrapper(node)] += 1 dfs(node.right) dfs(root) return [i.node for i, count in counts.items() if count > 1]
find-duplicate-subtrees
Python, Hashable Class!
dev-josh
0
368
find duplicate subtrees
652
0.565
Medium
10,884
https://leetcode.com/problems/find-duplicate-subtrees/discuss/1090398/Python3-post-order-dfs
class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: def fn(node): """Return serialized sub-tree rooted at node.""" if not node: return " " left, right = fn(node.left), fn(node.right) srl = ",".join((str(node.val), left, right)) if seen.get(srl, 0) == 1: ans.append(node) seen[srl] = 1 + seen.get(srl, 0) return srl ans, seen = [], {} fn(root) return ans
find-duplicate-subtrees
[Python3] post-order dfs
ye15
0
141
find duplicate subtrees
652
0.565
Medium
10,885
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1011974/BFS-two-pointers-and-recursive
class Solution: def findTarget(self, root: TreeNode, k: int) -> bool: queue = [root] unique_set = set() while len(queue) > 0: current = queue.pop() if k - current.val in unique_set: return True unique_set.add(current.val) if current.left: queue.append(current.left) if current.right: queue.append(current.right) return False
two-sum-iv-input-is-a-bst
BFS, two pointers and recursive
borodayev
2
213
two sum iv input is a bst
653
0.61
Easy
10,886
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1011974/BFS-two-pointers-and-recursive
class Solution: def findTarget(self, root: TreeNode, k: int) -> bool: def inorder(node: TreeNode): if node: yield from inorder(node.left) yield node.val yield from inorder(node.right) arr = [x for x in inorder(root)] i = 0 j = len(arr) - 1 while i < j: if arr[i] + arr[j] == k: return True if arr[i] + arr[j] < k: i += 1 if arr[i] + arr[j] > k: j -= 1 return False
two-sum-iv-input-is-a-bst
BFS, two pointers and recursive
borodayev
2
213
two sum iv input is a bst
653
0.61
Easy
10,887
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1011974/BFS-two-pointers-and-recursive
class Solution: def findTarget(self, root: TreeNode, k: int) -> bool: def inorder(node: TreeNode, numbers): if node: if k - node.val in numbers: return True numbers.add(node.val) return inorder(node.right, numbers) or inorder(node.left, numbers) return inorder(root, set())
two-sum-iv-input-is-a-bst
BFS, two pointers and recursive
borodayev
2
213
two sum iv input is a bst
653
0.61
Easy
10,888
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2678410/Python-DFS
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: def dfs(node, seen): if not node: return False if k - node.val in seen: return True seen.add(node.val) return dfs(node.left, seen) or dfs(node.right, seen) return dfs(root, set())
two-sum-iv-input-is-a-bst
Python, DFS
blue_sky5
1
46
two sum iv input is a bst
653
0.61
Easy
10,889
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2264011/Python3-or-O(n)-Solution-or-Using-Generator
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: # isReverse: traversing in descending order. def BSTsearch(node, isReverse): l, r = node.left, node.right if isReverse: l, r = node.right, node.left if l: yield from BSTsearch(l, isReverse) yield node.val if r: yield from BSTsearch(r, isReverse) # Generator in ascending order leftGen = BSTsearch(root, False) # Generator in descending order. rightGen = BSTsearch(root, True) left = leftGen.__next__() right = rightGen.__next__() while left < right: if left + right == k: return True if left + right > k: right = rightGen.__next__() else: left = leftGen.__next__() return False
two-sum-iv-input-is-a-bst
Python3 | O(n) Solution | Using Generator
shugokra
1
113
two sum iv input is a bst
653
0.61
Easy
10,890
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1956312/Using-inorder-traversal-and-Two-sum-2-technique
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: self.arr = [] def helper(node): # first take inorder of tree create array of value if node: helper(node.left) self.arr.append(node.val) helper(node.right) helper(root) l, r = 0, len(self.arr) - 1 # Then simple Two sum 2 technique is used to find a pair. while l < r: if self.arr[l] + self.arr[r] > k: r -= 1 elif self.arr[l] + self.arr[r] < k: l += 1 else: return True return False
two-sum-iv-input-is-a-bst
Using inorder traversal and Two sum 2 technique
ankurbhambri
1
87
two sum iv input is a bst
653
0.61
Easy
10,891
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2748415/Python-solution
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: nums = {} def dfs(node): if node: nums[node.val] = True dfs(node.left) dfs(node.right) dfs(root) for key in nums.keys(): diff = k - key if diff in nums and key != diff: return True return False
two-sum-iv-input-is-a-bst
Python solution
maomao1010
0
7
two sum iv input is a bst
653
0.61
Easy
10,892
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2738818/BSTiterator-in-Constant-Space
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: if not root: return False l_obj = BSTiterator(root, False) r_obj = BSTiterator(root, True) l, r = 0, 0 if l_obj.hasNext(): l = l_obj.next() if r_obj.hasNext(): r = r_obj.next() while l != r: if l + r == k: return True if l + r < k: l = l_obj.next() else: r = r_obj.next() return False class BSTiterator: def __init__(self, root, reverse): self.st = [] self.reverse = reverse if self.reverse: while root: self.st.append(root) root = root.right else: while root: self.st.append(root) root = root.left def next(self): temp = self.st.pop() if self.reverse: l = temp.left while(l): self.st.append(l) l = l.right else: r = temp.right while(r): self.st.append(r) r = r.left return temp.val def hasNext(self): return len(self.st) != 0
two-sum-iv-input-is-a-bst
BSTiterator in Constant Space
hacktheirlives
0
7
two sum iv input is a bst
653
0.61
Easy
10,893
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2683437/Python!-5-Lines-solution.-O(N).
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: def rec(node: TreeNode) -> list: return [] if node == None else rec(node.left) + [node.val] + rec(node.right) nums = rec(root) exist = {key:True for key in nums} return any(k -a in exist for a in nums if a != k - a)
two-sum-iv-input-is-a-bst
😎Python! 5 Lines solution. O(N).
aminjun
0
104
two sum iv input is a bst
653
0.61
Easy
10,894
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2682916/Easy-solution-with-in-order-DFS-in-Python
class Solution: def dfs(self, v): if v.left and self.dfs(v.left): return True if self.k - v.val in self.visited: return True self.visited.add(v.val) return v.right is not None and self.dfs(v.right) def findTarget(self, root: Optional[TreeNode], k: int) -> bool: self.k = k self.visited = set() return self.dfs(root)
two-sum-iv-input-is-a-bst
Easy solution with in-order DFS in Python
metaphysicalist
0
88
two sum iv input is a bst
653
0.61
Easy
10,895
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2682484/Python-simple-newbie-BFS-O(n)
class Solution: def __init__(self): self.hash = {} def findTarget(self, root: Optional[TreeNode], k: int) -> bool: nodes = [root] newNodes = [] while(nodes): for x in range(len(nodes)): if nodes[x].val in self.hash: return True else: self.hash[k-nodes[x].val] = nodes[x].val if nodes[x].left: newNodes.append(nodes[x].left) if nodes[x].right: newNodes.append(nodes[x].right) nodes = newNodes newNodes = [] return False
two-sum-iv-input-is-a-bst
Python - simple, newbie, BFS, O(n)
MacPatil23
0
106
two sum iv input is a bst
653
0.61
Easy
10,896
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2682084/Python-Solution
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: dic = {} def traversal(node): if not node: return False if node.val in dic.keys(): return True else: dic[k-node.val] = node.val return traversal(node.left) or traversal(node.right) return traversal(root)
two-sum-iv-input-is-a-bst
Python Solution
AxelDovskog
0
9
two sum iv input is a bst
653
0.61
Easy
10,897
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2681987/10-lines-of-Simple-to-understand-DFS-approach-using-list-only-One-of-the-easiest-solution
class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: self.lis = [] def bfs(root,target): if not root: return if target-root.val in self.lis: return True self.lis.append(root.val) x = bfs(root.left,target) or bfs(root.right,target) return x return bfs(root,k)
two-sum-iv-input-is-a-bst
10 lines of Simple to understand DFS approach using list only ,One of the easiest solution
vastavpundir
0
33
two sum iv input is a bst
653
0.61
Easy
10,898
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/2680760/C%2B%2BPython-4-Approaches-or100-Fast-or-Super-Clear-or
class Solution: def helper(self,currNode,selectedNode,target): if not currNode: #This helper function search second element from the remaining elements return False return ((currNode != selectedNode) and (currNode.val == target)) or self.helper(currNode.left,selectedNode,target) or self.helper(currNode.right,selectedNode,target) def solve(self,currNode,root,k): if not currNode: #This function selects first element return False return self.helper(root,currNode,k-currNode.val) or self.solve(currNode.left,root,k) or self.solve(currNode.right,root,k) def findTarget(self, root: Optional[TreeNode], k: int) -> bool: return self.solve(root,root,k)
two-sum-iv-input-is-a-bst
[C++/Python] 4 Approaches |100% Fast | Super Clear |🔥🔥🔥
ram_kishan1998
0
28
two sum iv input is a bst
653
0.61
Easy
10,899