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/longest-string-chain/discuss/2392590/Python3-or-Sorting%2BDP-or-Bottom-up-approach | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=lambda x:len(x))
hmap=defaultdict(int)
n=len(words)
dp=[1 for i in range(n)]
hmap[words[0]]=0
for i in range(1,n):
for j in range(len(words[i])):
newWord=words[i][:j]+words[i][j+1:]
if newWord in hmap:
dp[i]=max(dp[i],dp[hmap[newWord]]+1)
hmap[words[i]]=i
return max(dp) | longest-string-chain | [Python3] | Sorting+DP | Bottom-up approach | swapnilsingh421 | 0 | 53 | longest string chain | 1,048 | 0.591 | Medium | 17,100 |
https://leetcode.com/problems/longest-string-chain/discuss/2303842/top-bottom-memoization-or-python3 | class Solution:
def longestStrChain(self, words: List[str]) -> int:
retval = -inf
dp = {}
if len(words) == 1:
return 1
def dfs(w):
nonlocal retval
if w in dp:
return dp[w]
if len(w) == 1 and w in words:
dp[w] = 1
return 1
if w not in words:
return -1
dp[w] = 1
for i in range(len(w)):
temp = w[:i] + w[i+1:]
val = dfs(temp) + 1
dp[w] = max(dp[w], val)
retval = max(retval, dp[w])
return dp[w]
for word in words:
dfs(word)
return retval | longest-string-chain | top-bottom memoization | python3 | skrrtttt | 0 | 18 | longest string chain | 1,048 | 0.591 | Medium | 17,101 |
https://leetcode.com/problems/longest-string-chain/discuss/2301339/Python3-Easy-Recursive-Solution | class Solution:
def longestStrChain(self, words: List[str]) -> int:
n = len(words)
# use set to have O(1) lookup
lookup = set(words)
@cache
def dfs(word):
# base case: can not continue if it is not in our list
if word not in lookup:
return 0
m = len(word)
return max([1 + dfs(word[:i]+word[i+1:]) for i in range(m)])
# sort it according to its length
words.sort(key = lambda x: -len(x))
return max([dfs(words[i]) for i in range(n)]) | longest-string-chain | [Python3] Easy Recursive Solution | Che4pSc1ent1st | 0 | 102 | longest string chain | 1,048 | 0.591 | Medium | 17,102 |
https://leetcode.com/problems/longest-string-chain/discuss/2236253/Longest-increasing-subsequence-same-code-just-1-change-easy-to-understand | class Solution:
def longestStrChain(self, words: List[str]) -> int:
# T(c)=O(n*n)
# Purpose of checkPossible function is to check if any
# possible subsequence of s1 occurs in index less then
# s1 in words, by diff. of max 1 character.
def checkPossible(s1,s2):
if len(s1)!=1+len(s2):
return False
for k in range(len(s1)):
if s1[:k]+s1[k+1:]==s2:
return True
return False
# Little bit Variation of LIS, instead of increasing the no.
# , here 1 character increases each time.
dp=[1]*len(words)
maxi=1
words=sorted(words,key=len)
dict={}
for i in range(len(words)):
for j in range(i):
if checkPossible(words[i],words[j]) and 1+dp[j]>dp[i]:
dp[i]=dp[j]+1
maxi=max(maxi,dp[i])
return maxi | longest-string-chain | Longest increasing subsequence , same code ,just 1 change, easy to understand | Aniket_liar07 | 0 | 53 | longest string chain | 1,048 | 0.591 | Medium | 17,103 |
https://leetcode.com/problems/longest-string-chain/discuss/2197277/Intuitive-Iterative-Solution | class Solution(object):
def longestStrChain(self, words):
words.sort(key=len, reverse=True)
wordSet = set(words)
wordDict = defaultdict(int)
for word in words:
if word not in wordDict:
wordDict[word] = 1
for i in range(len(word)):
predecessor = word[:i]+word[i+1:]
if predecessor in wordSet:
wordDict[predecessor] = max(1 + wordDict[word],wordDict[predecessor])
return max(wordDict.values()) | longest-string-chain | Intuitive Iterative Solution | tohbaino | 0 | 38 | longest string chain | 1,048 | 0.591 | Medium | 17,104 |
https://leetcode.com/problems/longest-string-chain/discuss/2165182/Python-DFS-DP-Solution-with-manual-caching | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key = lambda x:len(x))
memo = {}
word_set = set(words)
def dfs(word):
if word in memo:
return memo[word]
curr_max = 1
for i in range(len(word)):
predecessor = word[:i] + word[i+1:]
if predecessor in word_set:
curr_max = max(curr_max, dfs(predecessor) + 1)
memo[word] = curr_max
return 1
for w in words:
dfs(w)
return max(memo.values()) | longest-string-chain | Python DFS DP Solution with manual caching | clipper21 | 0 | 49 | longest string chain | 1,048 | 0.591 | Medium | 17,105 |
https://leetcode.com/problems/longest-string-chain/discuss/2154992/Python3-Solution-with-using-dynamic-programming | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len)
res = 0
dp = collections.defaultdict(int)
for word in words:
for i in range(len(word)):
dp[word] = max(dp[word], dp[word[:i] + word[i + 1:]] + 1)
res = max(res, dp[word])
return res | longest-string-chain | [Python3] Solution with using dynamic programming | maosipov11 | 0 | 27 | longest string chain | 1,048 | 0.591 | Medium | 17,106 |
https://leetcode.com/problems/longest-string-chain/discuss/2154238/python-97-time-98-space | class Solution:
def longestStrChain(self, words: List[str]) -> int:
memo = {}
for i in words:
memo[i] = 1
words = sorted(words, key=len)
for i in words:
length =len(i)
if length > 1:
for j in range(length):
if (i[:j] + i[j+1:]) in memo:
memo[i] = max(memo[i], memo[i[:j] + i[j+1:]] +1)
return max(memo.values()) | longest-string-chain | python, 97% time, 98% space | pjy953 | 0 | 5 | longest string chain | 1,048 | 0.591 | Medium | 17,107 |
https://leetcode.com/problems/longest-string-chain/discuss/2154143/Python-or-DP-or-Hash-Table-or-Beat-99-runtime-and-memory | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=lambda x: len(x)) # Sort by word length
d = {} # Dict for chain length up to word w
for w in words:
d[w] = 1
for j in range(len(w)):
c = w[:j] + w[j+1:] # Word with the j-th character cut
if c in d:
d[w] = max(d[w], d[c] + 1)
return max(d.values()) | longest-string-chain | Python | DP | Hash Table | Beat 99% runtime and memory | slbteam08 | 0 | 14 | longest string chain | 1,048 | 0.591 | Medium | 17,108 |
https://leetcode.com/problems/longest-string-chain/discuss/2154122/Modification-Of-LIS-Approach-oror-Dynamic-Programming-oror-Fastest-Optimal-Solution | class Solution:
def compareStrings(self, word1, word2):
word1Length = len(word1)
word2Length = len(word2)
if word1Length != 1 + word2Length:
return False
pointer1 = 0
pointer2 = 0
while pointer1 < word1Length:
if pointer2 < word2Length and word1[pointer1] == word2[pointer2]:
pointer1 += 1
pointer2 += 1
else:
pointer1 += 1
if pointer1 == word1Length and pointer2 == word2Length:
return True
else:
return False
def longestStrChain(self, words: List[str]) -> int:
words = sorted(words, key=len)
length = len(words)
dpArray = [1]*length
longestPossibleLength = 1
for i in range(0, length):
for j in range(0,i):
if self.compareStrings(words[i],words[j]) and 1 + dpArray[j] > dpArray[i]:
dpArray[i] = 1 + dpArray[j]
longestPossibleLength = max(longestPossibleLength, dpArray[i])
return longestPossibleLength | longest-string-chain | Modification Of LIS Approach || Dynamic Programming || Fastest Optimal Solution | Vaibhav7860 | 0 | 22 | longest string chain | 1,048 | 0.591 | Medium | 17,109 |
https://leetcode.com/problems/longest-string-chain/discuss/2153845/My-python-solution | class Solution:
def fun(self,words,idx,mp,dp):
val = 1 # intialising the val = 1 as each word is itself a word chain of length 1
if dp.get(idx,-1) != -1: # this part handles simple memoization
return dp[idx]
for i in range(len(words[idx])):
word = words[idx][:i] + words[idx][i+1:] # deleting the ith character of the word
if mp.get(word,-1) != -1: # checking whether the new word formed after deleting the ith character is present in our words list or not
val = max(val,1 + self.fun(words,mp[word],mp,dp)) #The new word formed is present so i am going to that word and i will form word chain from that word.
#Please note the word 'word' is the predecssor for the word[idx].
#The max function stores the maximum of all the length in which word[idx] is the part of the word chain
dp[idx]=val
return dp[idx]
def longestStrChain(self, words: List[str]) -> int:
mp = { words[i] : i for i in range(len(words)) } # mapping each word to its index in the array
n = len(words)
ans = 1 # initial minimum ans will be 1 because each word is itself a word chain of length 1
dp = {} #creating a dictionary for memoization
# Here I am going backwards instead of taking a word and forming the chain by adding tha characters here I am choosing a word and forming the chain by deleting the characters
for i in range(len(words)):
ans = max(ans,self.fun(words,i,mp,dp)) # Recursion function for calculating the word chain
return ans | longest-string-chain | My python solution | arpit92_8 | 0 | 18 | longest string chain | 1,048 | 0.591 | Medium | 17,110 |
https://leetcode.com/problems/longest-string-chain/discuss/2153233/Longest-String-Chain-oror-Explained-with-Print-Statements | class Solution:
def longestStrChain(self, words: List[str]) -> int:
dp = {}
res = 1
x = sorted(words, key=len)
# print(" x :", x)
for word in x:
dp[word] = 1
# print("dp :", dp)
for i in range(len(word)):
prev = word[:i] + word[i + 1 :]
# print("prev :", prev)
if prev in dp:
dp[word] = dp[prev] + 1
res = max(res, dp[word])
# print("res :", res)
# print("DDPP :", dp)
return res | longest-string-chain | Longest String Chain || Explained with Print Statements | vaibhav0077 | 0 | 15 | longest string chain | 1,048 | 0.591 | Medium | 17,111 |
https://leetcode.com/problems/longest-string-chain/discuss/2152919/Python-DFS-traversal-with-memoization | class Solution:
def longestStrChain(self, words: List[str]) -> int:
def dfs(w):
if w in memo:
return memo[w]
max_chain = 0
for i in range(len(w)):
next_w = w[:i] + w[i+1:]
if next_w in words_set:
max_chain = max(max_chain, dfs(next_w))
memo[w] = max_chain + 1
return max_chain + 1
memo = {}
words_set = set(words)
result = 0
for w in words:
result = max(result, dfs(w))
return result | longest-string-chain | Python, DFS traversal with memoization | blue_sky5 | 0 | 12 | longest string chain | 1,048 | 0.591 | Medium | 17,112 |
https://leetcode.com/problems/longest-string-chain/discuss/2152861/python-3-oror-memoization | class Solution:
def longestStrChain(self, words: List[str]) -> int:
def isChain(word1, word2):
offset = False
for i in range(len(word1)):
if not offset and word1[i] != word2[i]:
offset = True
if offset and word1[i] != word2[i + 1]:
return False
return True
lengthMap = collections.defaultdict(list)
for word in words:
lengthMap[len(word)].append(word)
@lru_cache(None)
def helper(word):
res = 1
for predecessor in lengthMap[len(word) - 1]:
if isChain(predecessor, word):
res = max(res, 1 + helper(predecessor))
return res
return max(helper(word) for word in words) | longest-string-chain | python 3 || memoization | dereky4 | 0 | 49 | longest string chain | 1,048 | 0.591 | Medium | 17,113 |
https://leetcode.com/problems/longest-string-chain/discuss/2075952/PYTHON-SOL-or-DP-%2B-HASHTABLE-or-EASY-or-EXPLAINED-WELL-or | class Solution:
def check(self,main,side):
m = len(main)
for i in range(m):
if main[:i] + main[i+1:] == side:
return True
return False
def recursion(self,index):
best = 1
self.visited[index] = True
if self.dp[index] != -1: return self.dp[index]
for i in range(index+1,self.n):
if len(self.words[index]) + 1 < len(self.words[i]):
break
if len(self.words[index]) == len(self.words[i]):
continue
if self.check(self.words[i],self.words[index]) == True:
tmp = self.recursion(i) + 1
if tmp > best:
best = tmp
self.dp[index] = best
return best
def longestStrChain(self, words: List[str]) -> int:
ans = 1
self.n = len(words)
self.visited = [False]*self.n
self.dp = [-1]*self.n
words.sort(key = lambda x: len(x))
self.words = words
best = 1
for i in range(self.n):
if self.visited[i] == True:continue
tmp = self.recursion(i)
if tmp > best: best = tmp
return best | longest-string-chain | PYTHON SOL | DP + HASHTABLE | EASY | EXPLAINED WELL | | reaper_27 | 0 | 58 | longest string chain | 1,048 | 0.591 | Medium | 17,114 |
https://leetcode.com/problems/longest-string-chain/discuss/1947852/python-oror-top-down-dfs | class Solution:
def longestStrChain(self, words: List[str]) -> int:
n = len(words)
pos_map = {w: i for i, w in enumerate(words)}
graph = [[] for _ in range(n)]
score = [0 for _ in range(n)]
for i, w in enumerate(words):
for j, c in enumerate(w):
sub_word = w[0:j] + w[j+1:]
if sub_word in pos_map:
graph[pos_map[sub_word]].append(i)
res = 0
for i in range(n):
res = max(res, self.longest(i, graph, score))
return res
def longest(self, i, graph, score):
if score[i] > 0:
return score[i]
score[i] = 1
for b in graph[i]:
score[i] = max(score[i], self.longest(b, graph, score) + 1)
return score[i] | longest-string-chain | python || top-down dfs | Chen_Song | 0 | 65 | longest string chain | 1,048 | 0.591 | Medium | 17,115 |
https://leetcode.com/problems/longest-string-chain/discuss/1572799/Top-down-with-dictionary | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=lambda x:len(x))
#Sort the list according to the length of each word,
#could be done in O(n) with counting sort in this case
#since we know the length of word should an integer be between 1 and 16.
wordsByLen = {}
prev = 0
prevlen = len(words[0])
for i in range(len(words)):
if(len(words[i]) > prevlen):
wordsByLen[prevlen] = dict(zip(words[prev:i],[1]*(i-prev)))
prevlen = len(words[i])
prev = i
wordsByLen[prevlen] = dict(zip(words[prev:],[1]*len(words[prev:])))
#The goal here is to package the words with the same length into one entry
#in the dictionary wordsByLen with key = length of word and
#value a dictionary which has all the words we are packaging as keys,
#and value the maximum length of the chain if the chain end at this word.
#The maximum length of the chain we give 1 as default value
for i in range(16,1,-1):
if(i in wordsByLen and i-1 in wordsByLen):
words = list(wordsByLen[i].keys())
confirmed = {}
for word in words:
for d in range(i):
newword = word[0:d]+word[d+1:]
if(newword in wordsByLen[i-1]):
if(newword in confirmed):
confirmed[newword] = max(wordsByLen[i][word]+1,confirmed[newword])
else:
confirmed[newword] = wordsByLen[i][word]+1
for conf in confirmed:
wordsByLen[i-1][conf] = confirmed[conf]
#Iterate through all the possible length of word from longest to shortest.
#At each length, check if there is any word of this length and length-1,
#since if there are no possible word to chain to, we can simply skip checking this length.
#At each length, iterate through each word, at each word iterate through all the permutation of that word
#by removing one of the letter, check if the permutation exists in length-1, if so the word with length-1
#inherits the chain length, and add 1 to it, if multiple words chain to one word, only keep the longest chain
best = 1
for i in range(1,17):
if(i in wordsByLen):
best = max(max(wordsByLen[i].values()),best)
return best
#Find the longest chain of all the chains, the value of each entry represent the longest chain
#if we end at that word. | longest-string-chain | Top down with dictionary | renewrr | 0 | 129 | longest string chain | 1,048 | 0.591 | Medium | 17,116 |
https://leetcode.com/problems/longest-string-chain/discuss/1541185/Python-or-DP-%2B-Dictionary-%2B-Set-or-Solution | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key=len, reverse=False)
wordSet = set(words)
wordDict = {words[-1]:1}
res = 0
def dfs(word):
if word in wordDict:
curLen = wordDict[word]
else:
curLen, wordDict[word] = 1,1
for i,w in enumerate(word):
newWord = word[:i]+word[i+1:]
if newWord in wordSet and newWord not in wordDict:
wordDict[newWord] = curLen + 1
dfs(newWord)
while len(words) > 0:
dfs(words.pop())
for v in wordDict.values():
res = max(res, v)
return res | longest-string-chain | Python | DP + Dictionary + Set | Solution | tohbaino | 0 | 174 | longest string chain | 1,048 | 0.591 | Medium | 17,117 |
https://leetcode.com/problems/longest-string-chain/discuss/1512958/Python3-DP-Solution-similar-to-Longest-Increasing-Subsequence | class Solution:
def isPredecessor(self, word1:str, word2:str) -> bool:
"""
Determine if word1 is a predecessor of word2
"""
if len(word1) != (len(word2) - 1): return False
count = 0
i = 0
while (i - count) < len(word1):
w1_idx = i - count
w2_idx = i
if word1[w1_idx] != word2[w2_idx]:
count += 1
if count > 1:
return False
i += 1
return True
def longestStrChain(self, words: List[str]) -> int:
# sort the string based on length
words = sorted(words, key=lambda x:len(x))
# using dp, init dp table
dp = [1] * len(words)
for j in range(1, len(words)):
for i in range(j):
if self.isPredecessor(words[i], words[j]) and dp[j] <= dp[i]:
dp[j] = dp[i] + 1
return max(dp) | longest-string-chain | [Python3] DP Solution, similar to Longest Increasing Subsequence | nick19981122 | 0 | 103 | longest string chain | 1,048 | 0.591 | Medium | 17,118 |
https://leetcode.com/problems/longest-string-chain/discuss/1213620/Simple-solution-using-a-bottom-up-DP-in-Python | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words = sorted(words, key = lambda x: len(x))
ans = 1
hashmap = dict()
for w in words:
hashmap[w] = 1
for w in words:
x = 1
for i in range(len(w)):
temp = w[:i] + w[i + 1:]
prev = hashmap.get(temp, 0)
x = max(x, prev + 1)
hashmap[w] = x
ans = max(ans, x)
return ans | longest-string-chain | Simple solution using a bottom up DP in Python | amoghrajesh1999 | 0 | 45 | longest string chain | 1,048 | 0.591 | Medium | 17,119 |
https://leetcode.com/problems/longest-string-chain/discuss/1213605/Python-or-DP-or-Bucket-Sort-or-96ms | class Solution:
def longestStrChain(self, words: List[str]) -> int:
len_map = dict()
for word in words:
len_map.setdefault(len(word), set()).add(word)
len_map = sorted(len_map.items())
dp = dict()
for i, (length, words) in enumerate(len_map):
if i == 0 or length - len_map[i - 1][0] != 1:
for word in words:
dp[word] = 1
else:
for word in words:
dp[word] = 1 + max(dp.get(word[:i] + word[i + 1:], 0) for i in range(length))
# print(dp)
return max(dp.values()) | longest-string-chain | Python | DP | Bucket Sort | 96ms | PuneethaPai | 0 | 55 | longest string chain | 1,048 | 0.591 | Medium | 17,120 |
https://leetcode.com/problems/longest-string-chain/discuss/1213605/Python-or-DP-or-Bucket-Sort-or-96ms | class Solution:
def longestStrChain(self, words: List[str]) -> int:
len_map = defaultdict(set)
for word in words:
len_map[len(word)].add(word)
len_map = sorted(len_map.items())
N = len(len_map)
adj = defaultdict(list)
for i in range(1, N):
(p, prev), (c, cur) = len_map[i - 1], len_map[i]
if c - p != 1:
continue
for word in cur:
for i in range(c):
temp = word[:i] + word[i + 1:]
if temp in prev:
adj[word].append(temp)
# print(adj)
@lru_cache(maxsize=None)
def dfs(word: str) -> int:
return 1 + max((dfs(neigh) for neigh in adj[word]), default=0)
res = 0
for length, words in len_map:
res = max(res, max(dfs(word) for word in words))
return res | longest-string-chain | Python | DP | Bucket Sort | 96ms | PuneethaPai | 0 | 55 | longest string chain | 1,048 | 0.591 | Medium | 17,121 |
https://leetcode.com/problems/longest-string-chain/discuss/1213583/python3-Recursion-memoization-sol-for-reference | class Solution:
def longestStrChain(self, words: List[str]) -> int:
T = [0] * len(words)
wi = {}
cache = {}
for index, w in enumerate(words):
wi[w] = index
def onelesschar(s):
o = deque([])
for p in range(len(s)):
o.append(s[:p]+s[p+1:])
return o
ans = 0
def Tupdate(T, inputs, wi):
if inputs in cache:
return cache[inputs]
l = 0
for z in onelesschar(inputs):
if z in wi:
cs = Tupdate(T, z, wi)
l = max(l, 1+cs)
cache[inputs] = l
return l
for w in range(len(words)-1, -1, -1):
if T[w] == 0:
T[w] = 1+Tupdate(T, words[w], wi)
return max(T) | longest-string-chain | [python3] Recursion, memoization sol for reference | vadhri_venkat | 0 | 89 | longest string chain | 1,048 | 0.591 | Medium | 17,122 |
https://leetcode.com/problems/longest-string-chain/discuss/920314/Python-short-DP-solution-without-Sorting-O(N)-Time-and-O(N)-Space | class Solution:
def longestStrChain(self, words: List[str]) -> int:
levels = collections.defaultdict(list)
for word in words:
levels[len(word)].append(word)
res = {w:1 for w in words}
for size in range(2, 17):
for w1 in levels[size]:
for i in range(len(w1)):
w0 = w1[:i] + w1[i+1:]
if w0 in res:
res[w1] = max(res[w1], res[w0] + 1)
return max(res.values()) | longest-string-chain | [Python] short DP solution without Sorting; O(N) Time and O(N) Space | licpotis | 0 | 306 | longest string chain | 1,048 | 0.591 | Medium | 17,123 |
https://leetcode.com/problems/longest-string-chain/discuss/481880/Python-100-memory-easy-20-lines-recursion | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words = sorted(words, key=lambda x:len(x))
wordset = set(words)
maxlen = 0
while words:
word = words.pop()
maxlen = max(self.testword(word,words,wordset),maxlen)
return maxlen
def testword(self,word,words, wordset,depth=1):
if len(word) == 1:
return depth
for rempos in range(len(word)):
newword = word[:rempos]+word[rempos+1:]
if newword in wordset:
# remove redundant tests
words.remove(newword)
wordset.remove(newword)
return self.testword(newword, words, wordset, depth+1)
return depth | longest-string-chain | Python 100% memory easy 20 lines recursion | adls371 | 0 | 191 | longest string chain | 1,048 | 0.591 | Medium | 17,124 |
https://leetcode.com/problems/longest-string-chain/discuss/2002756/Python3-HashMap-simple-and-if-you-can't-understand-you-can-blame-me | class Solution:
def longestStrChain(self, words: List[str]) -> int:
words.sort(key = lambda x : len(x))
dis_map = collections.defaultdict(int)
for w in words:
maybe = [w[:i] + w[i + 1:] for i in range(len(w))]
for m in maybe:
dis_map[w] = max(dis_map[m] + 1, dis_map[w])
return max(dis_map.values()) | longest-string-chain | Python3 HashMap simple and if you can't understand you can blame me | Nathaniscoding | -1 | 101 | longest string chain | 1,048 | 0.591 | Medium | 17,125 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/1013873/Python3-top-down-dp | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
@lru_cache(None)
def fn(i, v):
"""Return minimum weight of stones[i:] given existing weight."""
if i == len(stones): return abs(v)
return min(fn(i+1, v - stones[i]), fn(i+1, v + stones[i]))
return fn(0, 0) | last-stone-weight-ii | [Python3] top-down dp | ye15 | 2 | 153 | last stone weight ii | 1,049 | 0.526 | Medium | 17,126 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/461955/Python3-All-possible-sums | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
s = {0}
for st in stones:
tmp = set()
for i in s:
tmp.add(abs(i + st))
tmp.add(abs(i - st))
s = tmp
return min(s) if len(s) > 0 else 0 | last-stone-weight-ii | Python3 All possible sums | tp99 | 2 | 488 | last stone weight ii | 1,049 | 0.526 | Medium | 17,127 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/2794878/Python-(Simple-Dynamic-Programming) | class Solution:
def lastStoneWeightII(self, stones):
total = sum(stones)
max_weight = int(total/2)
dp = [0]*(max_weight+1)
for stone in stones:
for weight in range(max_weight,-1,-1):
if weight - stone >= 0:
dp[weight] = max(dp[weight], stone + dp[weight-stone])
return total - 2*dp[-1] | last-stone-weight-ii | Python (Simple Dynamic Programming) | rnotappl | 0 | 6 | last stone weight ii | 1,049 | 0.526 | Medium | 17,128 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/2397470/Python-Top-Down-DP | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
# Divide the stones into two subsets
# Find the min of the difference of two subsets
total = sum(stones)
max_subset_size = total / 2
# _sum: the sum of the subsetA
# cur_idx: current stone index
@lru_cache(None)
def helper(cur_idx, _sum):
# diff = abs(subsetA - subsetB)
# = abs(_sum, total - _sum)
# = total - _sum - _sum
# = total - _sum * 2
if cur_idx == len(stones):
return total - _sum * 2
# We can not put the stone to this subset. Therefore, we bypass this stone.
# In other word, this stone is placed to another subset.
if _sum + stones[cur_idx] > max_subset_size:
return helper(cur_idx+1, _sum)
# put the stone to current subset v.s bypass the stone
return min(helper(cur_idx+1, _sum), helper(cur_idx+1, _sum + stones[cur_idx]))
return helper(0, 0) | last-stone-weight-ii | Python Top Down DP | TerryHung | 0 | 125 | last stone weight ii | 1,049 | 0.526 | Medium | 17,129 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/1591753/Easy-Solution-using-01-Knapsack-with-Python | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
total = sum(stones)
dp = [[0 for i in range(total//2+1)] for j in range(len(stones))]
for i in range(len(stones)):
for w in range(1,total//2+1):
dp[i][w] = max(dp[i-1][w], ((stones[i] + dp[i-1][w-stones[i]]) if w>=stones[i] else 0))
return total - dp[-1][-1]*2 | last-stone-weight-ii | Easy Solution using 0/1 Knapsack with Python | abrarjahin | 0 | 200 | last stone weight ii | 1,049 | 0.526 | Medium | 17,130 |
https://leetcode.com/problems/last-stone-weight-ii/discuss/1119134/Python-Comprehensive-and-concise-python-solution-with-DP. | class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
if len(stones) == 1:
return stones[0]
S = sum(stones)
half = sum(stones) // 2
mat = [False for _ in range(half+1)]
for i in stones:
arr = []
for j in range(len(mat)):
if j == i:
arr.append(i)
elif i < j and not mat[j] and mat[j-i]:
arr.append(j)
for x in arr: # simultaneous update
mat[x] = True
s2 = max([i for i in range(len(mat)) if mat[i]])
return abs(S-2*s2) | last-stone-weight-ii | [Python] Comprehensive and concise python solution with DP. | granwit | 0 | 204 | last stone weight ii | 1,049 | 0.526 | Medium | 17,131 |
https://leetcode.com/problems/height-checker/discuss/429670/Python-3-O(n)-Faster-than-100-Memory-usage-less-than-100 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
max_val = max(heights)
# Create frequency table
freq = [0] * (max_val + 1)
for num in heights: freq[num] += 1
for num in range(1, len(freq)): freq[num] += freq[num-1]
# Create places table
places = [0] * len(heights)
for num in heights:
places[freq[num]-1] = num
freq[num] -= 1
return sum([a!=b for a, b in zip(heights, places)]) | height-checker | Python 3 - O(n) - Faster than 100%, Memory usage less than 100% | mmbhatk | 24 | 4,800 | height checker | 1,051 | 0.751 | Easy | 17,132 |
https://leetcode.com/problems/height-checker/discuss/1060217/Python-2-Solutions-Easy-to-understand | class Solution:
def heightChecker(self, heights: List[int]) -> int:
k = sorted(heights)
count = 0
for i in range(len(heights)):
if k[i] != heights[i]:
count += 1
return count | height-checker | [Python] 2 Solutions / Easy to understand | ayushi7rawat | 7 | 559 | height checker | 1,051 | 0.751 | Easy | 17,133 |
https://leetcode.com/problems/height-checker/discuss/1060217/Python-2-Solutions-Easy-to-understand | class Solution:
def heightChecker(self, heights: List[int]) -> int:
return sum(sorted(heights)[i] != heights[i] for i in range(len(heights))) | height-checker | [Python] 2 Solutions / Easy to understand | ayushi7rawat | 7 | 559 | height checker | 1,051 | 0.751 | Easy | 17,134 |
https://leetcode.com/problems/height-checker/discuss/2598963/Python-or-Sort-or-Faster-than-98.86 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
sort_heights = sorted(heights)
return sum([0 if heights[i] == sort_heights[i] else 1 for i in range(len(heights))]) | height-checker | Python | Sort | Faster than 98.86% | prithuls | 4 | 516 | height checker | 1,051 | 0.751 | Easy | 17,135 |
https://leetcode.com/problems/height-checker/discuss/1939750/Python-O(n)-solution-using-bucket-list.-Fully-commented-and-straight-forward | class Solution:
def heightChecker(self, heights: List[int]) -> int:
#determine max height in list
maxHeight = max(heights)
#make a bucket list with maxHeight + 1 as range
bucket = [0 for x in range(maxHeight + 1)]
#fill the bucket
for n in heights:
bucket[n] += 1
i = 0
counter = 0
#iterate through heights
for n in heights:
#make sure we're always on a non-zero element in the bucket
while bucket[i] == 0: i += 1
#if bucket index is not equal to element value of heights,
#then increment counter
if i != n: counter += 1
#decrement the count in the bucket on every iteration
bucket[i] -= 1
return counter | height-checker | Python O(n) solution using bucket list. Fully commented and straight forward | gugliamo | 2 | 177 | height checker | 1,051 | 0.751 | Easy | 17,136 |
https://leetcode.com/problems/height-checker/discuss/2339034/Height-Checker | class Solution:
def heightChecker(self, heights: List[int]) -> int:
x = [x for x in heights]
n = len(heights)
for i in range(n-1):
swapped= False
for j in range(n-i-1):
if heights[j]>heights[j+1]:
y = heights[j]
heights[j]=heights[j+1]
heights[j+1]=y
swapped= True
if not swapped:
break
count = 0
for i in range(n):
if heights[i]!=x[i]:
count+=1
return count | height-checker | Height Checker | dhananjayaduttmishra | 1 | 40 | height checker | 1,051 | 0.751 | Easy | 17,137 |
https://leetcode.com/problems/height-checker/discuss/982558/Python-O(N)-and-O(NlogN)-easy-programs. | class Solution:
def heightChecker(self, heights: List[int]) -> int:
# O(N)
sortedList = []
count = 0
# initialize 1 to 100 count dictionary
oneToHundredDict = dict((k, 0) for k in range(1,101))
# count the repeatations and updating the dictionary
for i in range(0, len(heights)):
oneToHundredDict[heights[i]] = oneToHundredDict[heights[i]] + 1
# sorting the list
for key,value in oneToHundredDict.items():
if value > 0:
# Reapting key by value times thereby sorting the list
sortedList.extend(repeat(key, value))
# compare
for i in range(0,len(heights)):
if sortedList[i] != heights[i]:
count = count + 1
return count | height-checker | Python O(N) and O(NlogN) easy programs. | bindhushreehr | 1 | 380 | height checker | 1,051 | 0.751 | Easy | 17,138 |
https://leetcode.com/problems/height-checker/discuss/982558/Python-O(N)-and-O(NlogN)-easy-programs. | class Solution:
def heightChecker(self, heights: List[int]) -> int:
count=0
sorte=[]
# extend appends heights to sorte
sorte.extend(heights)
sorte.sort()
for i,v in enumerate(sorte):
if sorte[i]!=heights[i]:
count+=1
return count | height-checker | Python O(N) and O(NlogN) easy programs. | bindhushreehr | 1 | 380 | height checker | 1,051 | 0.751 | Easy | 17,139 |
https://leetcode.com/problems/height-checker/discuss/2835137/Python-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
k = sorted(heights)
count = 0
for index in range(0, len(heights)):
if k[index] != heights[index]:
count += 1
return count | height-checker | Python Solution | Antoine703 | 0 | 0 | height checker | 1,051 | 0.751 | Easy | 17,140 |
https://leetcode.com/problems/height-checker/discuss/2835136/Python-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
k = sorted(heights)
count = 0
for index in range(0, len(heights)):
if k[index] != heights[index]:
count += 1
return count | height-checker | Python Solution | Antoine703 | 0 | 0 | height checker | 1,051 | 0.751 | Easy | 17,141 |
https://leetcode.com/problems/height-checker/discuss/2832132/Python-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = 0
sorted_heights = sorted(heights)
for idx, height in enumerate(sorted_heights):
if height != heights[idx]:
count += 1
return count | height-checker | Python solution | corylynn | 0 | 2 | height checker | 1,051 | 0.751 | Easy | 17,142 |
https://leetcode.com/problems/height-checker/discuss/2814191/simple-python-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = [x for x in heights]
expected.sort()
counter=0
for x in range(len(heights)):
if heights[x]!=expected[x]:
counter+=1
return counter | height-checker | simple python solution | sahityasetu1996 | 0 | 4 | height checker | 1,051 | 0.751 | Easy | 17,143 |
https://leetcode.com/problems/height-checker/discuss/2787719/Simple-Python-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i,j in zip(heights,new_heights):
if i != j:
count += 1
return count`` | height-checker | Simple Python Solution | danishs | 0 | 10 | height checker | 1,051 | 0.751 | Easy | 17,144 |
https://leetcode.com/problems/height-checker/discuss/2779314/Python3-or-Simple-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
rst = 0
for h,e in zip(heights, expected):
if h != e:
rst += 1
return rst | height-checker | Python3 | Simple solution | YLW_SE | 0 | 4 | height checker | 1,051 | 0.751 | Easy | 17,145 |
https://leetcode.com/problems/height-checker/discuss/2769882/Simple-Python-Solution-Without-Using-Counter | class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = 0
for x,y in zip(heights, sorted(heights)):
if x!=y:
count += 1
return count | height-checker | Simple Python Solution Without Using Counter | dnvavinash | 0 | 4 | height checker | 1,051 | 0.751 | Easy | 17,146 |
https://leetcode.com/problems/height-checker/discuss/2476399/Easy-solution-using-zip-in-order-to-iterate-through-two-lists-at-the-same-time | class Solution:
def heightChecker(self, heights: List[int]) -> int:
not_in_order = 0
sorted_height = sorted(heights)
for i, j in zip(heights, sorted_height):
if i != j:
not_in_order += 1
return not_in_order | height-checker | Easy solution using zip in order to iterate through two lists at the same time | samanehghafouri | 0 | 8 | height checker | 1,051 | 0.751 | Easy | 17,147 |
https://leetcode.com/problems/height-checker/discuss/2390167/Python3-or-Simple-Sorting-Solution-O(nlgn)-Time | class Solution:
#T.C = O(n + nlgn) -> O(nlgn)
#S.C = O(n)
def heightChecker(self, heights: List[int]) -> int:
#currently, heights array represents the height of every ith person in some order
#could already be sorted or not sorted!
#Approach: Sort heights array and compare for every index!
ans = 0
sort = sorted(heights)
for i in range(len(heights)):
if(heights[i] != sort[i]):
ans += 1
return ans | height-checker | Python3 | Simple Sorting Solution O(nlgn) Time | JOON1234 | 0 | 30 | height checker | 1,051 | 0.751 | Easy | 17,148 |
https://leetcode.com/problems/height-checker/discuss/2337805/Simple-Python3-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
sort_h = sorted(heights)
return sum(sort_h[i] != heights[i] for i in range(len(heights))) | height-checker | Simple Python3 Solution | vem5688 | 0 | 25 | height checker | 1,051 | 0.751 | Easy | 17,149 |
https://leetcode.com/problems/height-checker/discuss/2202185/SIMPLE-Python-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
sorted_list=sorted(heights)
output=0
for i in range(len(heights)):
if heights[i]!=sorted_list[i]:
output+=1
return output | height-checker | SIMPLE Python solution | lyubol | 0 | 48 | height checker | 1,051 | 0.751 | Easy | 17,150 |
https://leetcode.com/problems/height-checker/discuss/2183812/99.94-Faster-code-in-5-lines | class Solution:
def heightChecker(self, heights: List[int]) -> int:
a = heights.copy()
a.sort()
res = 0
for i, j in zip(a, heights):
if j != i:
res += 1
return res | height-checker | 99.94% Faster code in 5 lines | ankurbhambri | 0 | 73 | height checker | 1,051 | 0.751 | Easy | 17,151 |
https://leetcode.com/problems/height-checker/discuss/2179986/Python-simple-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
srt = sorted(heights)
ans = 0
for i in range(len(heights)):
if heights[i] != srt[i]:
ans += 1
return ans | height-checker | Python simple solution | StikS32 | 0 | 36 | height checker | 1,051 | 0.751 | Easy | 17,152 |
https://leetcode.com/problems/height-checker/discuss/2159736/Python-or-Easiest-approach-using-zip-method-with-explanation | class Solution:
def heightChecker(self, heights: List[int]) -> int:
'''
Using simple idea, we will zip original heights with sorted heights and then will count
where positions are not matching.
for instance:
[1,1,(4),2,(1),(3)]
^ ^ ^
[1,1,(1),2,(3),(4)]
These elements which are enclosed in pranthesis are the miss matched elements
'''
return sum( x != y for x,y in zip(heights,sorted(heights))) | height-checker | Python | Easiest approach using zip method with explanation | __Asrar | 0 | 22 | height checker | 1,051 | 0.751 | Easy | 17,153 |
https://leetcode.com/problems/height-checker/discuss/2073473/easy-python-solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = 0
for i in range(len(heights)):
if heights[i] != sorted(heights)[i]:
count += 1
return count | height-checker | easy python solution | SivanShl | 0 | 71 | height checker | 1,051 | 0.751 | Easy | 17,154 |
https://leetcode.com/problems/height-checker/discuss/1991065/Python-Easiest-Solution-With-explanation-or-Sorting-or-Beg-to-adv | class Solution:
def heightChecker(self, heights: List[int]) -> int:
indices = 0 # declaring this variable to count conflicting indices.
expected = sorted(heights) # sorting provided list to get the expected list, as its in non-decreasing order(ascending order).
for i in range(len(heights)): # travering through the elemnts in provided list.
if expected[i] != heights[i]: # as stated in the problem statement
indices += 1 # as per the above comdition we have to count the how many indices are not matching.
return indices # returning the count of unmatched indices. | height-checker | Python Easiest Solution With explanation | Sorting | Beg to adv | rlakshay14 | 0 | 79 | height checker | 1,051 | 0.751 | Easy | 17,155 |
https://leetcode.com/problems/height-checker/discuss/1946136/height-checker-python | class Solution:
def heightChecker(self, heights: List[int]) -> int:
c=0
expected=sorted(heights)
for i in range(len(heights)):
if heights[i]!=expected[i]:
c+=1
return c | height-checker | height checker python | anil5829354 | 0 | 32 | height checker | 1,051 | 0.751 | Easy | 17,156 |
https://leetcode.com/problems/height-checker/discuss/1887248/Python-easy-solution-using-sort | class Solution:
def heightChecker(self, heights: List[int]) -> int:
heights_sort = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != heights_sort[i]:
count += 1
return count | height-checker | Python easy solution using sort | alishak1999 | 0 | 32 | height checker | 1,051 | 0.751 | Easy | 17,157 |
https://leetcode.com/problems/height-checker/discuss/1803905/2-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-60 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
return sum([1 for i in range(len(heights)) if heights[i]!=expected[i]]) | height-checker | 2-Lines Python Solution || 90% Faster || Memory less than 60% | Taha-C | 0 | 57 | height checker | 1,051 | 0.751 | Easy | 17,158 |
https://leetcode.com/problems/height-checker/discuss/1791234/Python-simple-solution-beats-86.17 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
count = 0
expected = sorted(heights)
for i in range(len(heights)):
if heights[i] != expected[i]:
count += 1
return count
# Runtime: 36 ms, faster than 86.17% of Python3 online submissions for Height Checker.
# Memory Usage: 13.9 MB, less than 66.21% of Python3 online submissions for Height Checker. | height-checker | Python simple solution beats 86.17% | KueharX | 0 | 50 | height checker | 1,051 | 0.751 | Easy | 17,159 |
https://leetcode.com/problems/height-checker/discuss/1322103/Python3-Simple-solution-faster-than-96-submissions | class Solution:
def heightChecker(self, heights: list) -> int:
op = 0
for index, height in enumerate(sorted(heights)):
if height != heights[index]:
op+=1
return op | height-checker | [Python3] Simple solution, faster than 96% submissions | GauravKK08 | 0 | 139 | height checker | 1,051 | 0.751 | Easy | 17,160 |
https://leetcode.com/problems/height-checker/discuss/1174317/python-sol-faster-than-95 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
tot = 0
ex = []
for j in heights:
ex.append(j)
ex.sort()
for i in range(len(ex)):
if (ex[i] != heights[i]):
tot += 1
return tot | height-checker | python sol faster than 95% | elayan | 0 | 362 | height checker | 1,051 | 0.751 | Easy | 17,161 |
https://leetcode.com/problems/height-checker/discuss/1158006/Python3-Simple-And-Fast-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
height = list(sorted(heights))
count = 0
for i , j in zip(height , heights):
if(i != j): count += 1
return count | height-checker | [Python3] Simple And Fast Solution | Lolopola | 0 | 67 | height checker | 1,051 | 0.751 | Easy | 17,162 |
https://leetcode.com/problems/height-checker/discuss/1155221/Easy-Python-Solution | class Solution:
def heightChecker(self, heights: List[int]) -> int:
#sort list
sortedList= sorted(heights)
count=0
for i in range(len(sortedList)):
#compare sorted list with original to check how many positions are being changes
if heights[i] != sortedList[i]:
count=count+1
return(count) | height-checker | Easy Python Solution | YashashriShiral | 0 | 80 | height checker | 1,051 | 0.751 | Easy | 17,163 |
https://leetcode.com/problems/height-checker/discuss/473261/Python-fast-one-liner-with-explanation | class Solution:
def heightChecker(self, heights: List[int]) -> int:
return sum([i != j for i, j in zip(heights, sorted(heights))]) | height-checker | Python fast one-liner with explanation | denisrasulev | 0 | 216 | height checker | 1,051 | 0.751 | Easy | 17,164 |
https://leetcode.com/problems/height-checker/discuss/395105/python3-1-line-81.31-time-and-100-space | class Solution(object):
def heightChecker(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
return sum(map(lambda x, y: x!=y, sorted(heights), heights)) | height-checker | python3 1-line 81.31 time and 100 space | ddoudle | 0 | 96 | height checker | 1,051 | 0.751 | Easy | 17,165 |
https://leetcode.com/problems/height-checker/discuss/300984/runtime-20ms-python3 | class Solution(object):
def heightChecker(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
count =0
k =heights[:]
heights.sort()
for i in range(len(heights)):
if heights[i] != k[i]:
count +=1
return count | height-checker | runtime 20ms python3 | aidpl2019 | 0 | 100 | height checker | 1,051 | 0.751 | Easy | 17,166 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/441491/Python-(97)-Easy-to-understand-Sliding-Window-with-comments | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
# a sliding window approach
currsum = 0
# first store the sum as if the owner has no super power
for i in range(len(grumpy)):
if not grumpy[i]:
currsum += customers[i]
# now assuming he has the power, take the first window
# and add to the previous sum
for i in range(X):
if grumpy[i]:
currsum += customers[i]
maxsum = currsum
# Now the sliding window starts
# i and j are the two opposite ends of the window
i = 0
j = X
while j < len(customers):
if grumpy[j]:
currsum += customers[j]
if grumpy[i]:
currsum -= customers[i]
# we subtract above as the window has already passed over that customer
if currsum > maxsum:
maxsum = currsum
i += 1
j += 1
return maxsum | grumpy-bookstore-owner | Python (97%) - Easy to understand Sliding Window with comments | vdhyani96 | 3 | 315 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,167 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/1712076/Sliding-Window-Rolling-sum-Python-3 | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
satisfied=0
n=len(grumpy)
satisfied=sum([customers[i]*(1-grumpy[i]) for i in range(n)])
max_satisfied=satisfied
for i in range(n):
if grumpy[i]==1: satisfied+=customers[i]
if i>=minutes:
if grumpy[i-minutes]==1: satisfied-=customers[i-minutes]
max_satisfied=max(satisfied,max_satisfied)
return max_satisfied
``` | grumpy-bookstore-owner | Sliding Window Rolling sum Python 3 | shandilayasujay | 2 | 119 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,168 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/1580210/Easy-for-beginers%3A-Sliding-window-problem-Faster-than-94 | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
n = len(customers)
res = 0
for i in range(n):
if grumpy[i] == 0:
res += customers[i]
sum1 = 0
for i in range(minutes):
if grumpy[i] == 1:
sum1 += customers[i]
result = sum1
for r in range(minutes, n):
if grumpy[r] == 1:
sum1 += customers[r]
if grumpy[r - minutes] == 1:
sum1 -= customers[r - minutes]
result = max(sum1, result)
return res + result | grumpy-bookstore-owner | Easy for beginers: Sliding window problem Faster than 94% | zixin123 | 2 | 129 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,169 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2309669/Python3-O(n)-Time-O(1)-Space-Solution | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
#sliding window technique!
#first, linearly traverse customers array and see number of customers that are
#gauranteed to be satisfied regardless of store owner's powerup!
#then, use sliding window and maximize the number of customers that can be converted
#to satisfied by using minutes amount of power up !
#If we let len(customers)=n and len(grumpy) = m,
#Time: O(2n) -> O(n)
#Space: O(1)
#add these 2 results and that is the answer!
#Step 1
ans = 0
for a in range(len(customers)):
if(grumpy[a] == 0):
ans += customers[a]
#step 2: sliding window!
L, R = 0, 0
converted = 0
maximum = 0
length = 0
while R < len(customers):
#process right element
if(grumpy[R] == 1):
converted += customers[R]
length += 1
#stopping condition: if length ever reaches minutes
while length == minutes:
#process current sliding window!
maximum = max(maximum, converted)
#shrink the sliding window!
#check if left minute is the minutes store owner is grumpy!
if(grumpy[L] == 1):
converted -= customers[L]
length -= 1
L += 1
#keep expanding sliding window
R += 1
return maximum + ans | grumpy-bookstore-owner | Python3 O(n) Time O(1) Space Solution | JOON1234 | 1 | 44 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,170 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/1277151/Fixed-size-sliding-window(while-loop) | class Solution:
def maxSatisfied(self, c: List[int], g: List[int], k: int) -> int:
s = 0 ; res = 0
n = len(c)
for i in range(n):
if g[i]==0:
s += c[i]
i,j = 0,0
while j<n:
if g[j]==1:
s += c[j]
if j-i+1<k:
j+=1
elif j-i+1==k:
res = max(res,s)
if g[i]==1:
s-=c[i]
i+=1
j+=1
return res | grumpy-bookstore-owner | Fixed size sliding window(while loop) | Abheet | 1 | 89 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,171 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/1013811/Python3-2-pointer | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
ans = val = ii = mx = 0
for i in range(len(customers)):
if not grumpy[i]: ans += customers[i]
else:
val += customers[i]
while ii <= i-X:
if grumpy[ii]: val -= customers[ii]
ii += 1
mx = max(mx, val)
return ans + mx | grumpy-bookstore-owner | [Python3] 2-pointer | ye15 | 1 | 51 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,172 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2767143/sliding-window-solution-O(n) | class Solution:
def maxSatisfied(self, customers, grumpy, minutes):
ans=0
for c,e in enumerate(customers):
if grumpy[c]!=1:
ans+=e
customers[c]=0
currmax,maxi=0,0
for c,e in enumerate(customers):
currmax+=e
if (c-minutes)>=0:
currmax-=customers[c-minutes]
maxi=max(currmax,maxi)
return ans+maxi | grumpy-bookstore-owner | sliding window solution O(n) | pjvkumar999 | 0 | 2 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,173 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2335472/Python-sliding-window-with-Dry-Run | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
"""
customers = [1,0,1,2,1,1,7,5]
grumpy = [0,1,0,1,0,1,0,1]
we will try to find the sum of unsatisfied customers in a window
of size minutes
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 0
j
i max = 0
[0,1,0,1,0,1,0,1]
j
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 2
j
i max = 2
[0,1,0,1,0,1,0,1]
j
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 2
j
i max = 2
[0,1,0,1,0,1,0,1]
j
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 3
j
i max = 3
[0,1,0,1,0,1,0,1]
j
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 1
j
i max = 3
[0,1,0,1,0,1,0,1]
j
i
[1,0,1,2,1,1,7,5] number of unsatisfied customers = 6
j
i max = 6
[0,1,0,1,0,1,0,1]
j
total sum of satisfied customers begore the change is made = 10
we will be including the window with max value customers when the book
store woner was grumpy to the number of satisfied cutromers
ans = 10 + 6 = 16
"""
# sumLocal = number of customers when book store owner is Grumpy in a window
# sumGlobal = max number of customers when book store owner is Grumpy in a window
# i : start of the window
# j : end of the window
i = 0
j = 0
n = len(customers)
sumLocal = 0
sumGlobal = 0
while j < minutes:
if grumpy[j] == 1: sumLocal += customers[j]
j += 1
sumGlobal = max(sumLocal, sumGlobal)
while j < n:
if grumpy[j] == 1: sumLocal += customers[j]
if grumpy[i] == 1: sumLocal -= customers[i]
sumGlobal = max(sumLocal, sumGlobal)
i += 1
j += 1
return sum([customers[i] for i in range(n) if grumpy[i] == 0 ]) + sumGlobal | grumpy-bookstore-owner | Python sliding window with Dry Run | Pratyush_Priyam_Kuanr | 0 | 22 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,174 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2079636/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-DP-oror-PREFIX-SUM-oror-WELL-EXPLAINED-oror-COMMENTED-oror | class Solution:
def recursion(self,index,used):
# base case
if index == self.n: return 0
#check in dp
if (index,used) in self.dp: return self.dp[(index,used)]
#choice1 is using the secret technique
choice1 = -float('inf')
# we can only use secret technique once and consecutively
if used == True :
# use the secret technique
end = index + self.minutes if index + self.minutes < self.n else self.n
to_substract = self.prefix_sum[index - 1] if index != 0 else 0
val = self.prefix_sum[end - 1] - to_substract
choice1 = self.recursion(end,False) + val
# Do not use the secret tehcnique and play simple
choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)
ans = choice1 if choice1 > choice2 else choice2
# Memoization is done here
self.dp[(index,used)] = ans
return ans
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
self.n = len(customers)
self.customers = customers
self.grumpy = grumpy
self.minutes = minutes
self.dp = {}
self.prefix_sum = [x for x in customers]
for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]
return self.recursion(0,True) | grumpy-bookstore-owner | PYTHON SOL || RECURSION + MEMO || DP || PREFIX SUM || WELL EXPLAINED || COMMENTED || | reaper_27 | 0 | 43 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,175 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2079636/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-DP-oror-PREFIX-SUM-oror-WELL-EXPLAINED-oror-COMMENTED-oror | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
n = len(grumpy)
ans = 0
grumpy_sum = [ 0 for i in range(n)]
for i in range(n):
grumpy_sum[i] = customers[i] + grumpy_sum[i-1] if grumpy[i] == 0 else grumpy_sum[i-1]
summ = sum(customers[:minutes])
for i in range(n - minutes + 1):
to_add = grumpy_sum[i-1] if i != 0 else 0
to_sub = grumpy_sum[i + minutes - 1]
tmp = grumpy_sum[-1] - to_sub + to_add + summ
if tmp > ans : ans = tmp
if i == n - minutes: break
summ = summ + customers[i+minutes] - customers[i]
return ans | grumpy-bookstore-owner | PYTHON SOL || RECURSION + MEMO || DP || PREFIX SUM || WELL EXPLAINED || COMMENTED || | reaper_27 | 0 | 43 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,176 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/2077519/python-3-oror-sliding-window-oror-O(n)O(1) | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
maxSatisfied = satisfied = sum(c for i, (c, g) in enumerate(zip(customers, grumpy))
if i < minutes or g == 0)
for i in range(minutes, len(customers)):
satisfied += customers[i]*grumpy[i] - customers[i - minutes]*grumpy[i - minutes]
maxSatisfied = max(maxSatisfied, satisfied)
return maxSatisfied | grumpy-bookstore-owner | python 3 || sliding window || O(n)/O(1) | dereky4 | 0 | 89 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,177 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/716383/Java-and-python3-O(n)-easy-solution | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
no_at_grumpy=0
start=1
if not customers:return 0
if len(customers)<=X:return sum(customers)
curr=0
for i in range(X):
if grumpy[i]==1:curr+=customers[i]
temp=curr
while start+X<=len(customers):
#print(curr)
if grumpy[start-1]==1:temp-=customers[start-1]
if grumpy[start+X-1]==1:temp+=customers[start+X-1]
curr=max(curr,temp)
start+=1
for i,j in enumerate(grumpy):
if j==1:no_at_grumpy+=customers[i]
return sum(customers)-no_at_grumpy+curr
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
if(customers==null){return 0;}
if(customers.length<=X){
int temp=0;
for(int i:customers){temp+=i;}
return temp;
}
int curr=0,start=1;
for(int i=0;i<X;i++){
if(grumpy[i]==1){
curr+=customers[i];
}
}
int temp=curr;
while(start+X<=customers.length){
if(grumpy[start-1]==1){temp-=customers[start-1];}
if(grumpy[start+X-1]==1){temp+=customers[start+X-1];}
curr=(curr<temp)?temp:curr;
start++;
}
int sum=0,no_at_grumpy=0;
for(int i=0;i<grumpy.length;i++){
sum+=customers[i];
if(grumpy[i]==1){no_at_grumpy+=customers[i];}
}
return sum-no_at_grumpy+curr;
}
} | grumpy-bookstore-owner | Java and python3 O(n) easy solution | 752937603 | 0 | 79 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,178 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/387893/Simon's-Note-Python3-easy | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
temp=0
for i in range(len(customers)):
if grumpy[i]==0:
temp+=customers[i]
customers[i]=0
ma=-float('inf')
for j in range(len(customers)-X+1):
ma=max(ma,sum(customers[j:j+X]))
return temp+ma | grumpy-bookstore-owner | [🎈Simon's Note🎈] Python3 easy | SunTX | 0 | 59 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,179 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/299812/Python-code-248-ms-beats-100 | class Solution(object):
def maxSatisfied(self, customers, grumpy, X):
customers1 = [customers[i] if grumpy[i] == 0 else 0 for i in range(len(customers))]
i = 0
diff = sum(customers[i:i+X]) - sum(customers1[i:i+X])
max_diff = diff
non_grump_ind = 0
for i in range(1, len(customers) - X + 1):
diff += customers[i+X-1] - customers1[i+X-1] - customers[i-1] + customers1[i-1]
if diff > max_diff:
max_diff = diff
non_grump_ind = i
return sum(customers1[:non_grump_ind]) + sum(customers[non_grump_ind:non_grump_ind + X]) + sum(customers1[non_grump_ind + X:]) | grumpy-bookstore-owner | Python code 248 ms beats 100% | ciphur | 0 | 80 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,180 |
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/299367/python3-clean-and-short-code | class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
accC = [0]
n = len(customers)
for x in customers:
accC.append(x + accC[-1])
for i, x in enumerate(grumpy):
if x == 1: customers[i] = 0
accCG = [0]
for x in customers:
accCG.append(x + accCG[-1])
return max(accC[min(i+X-1, n)]-accC[i-1] + accCG[-1] - (accCG[min(i+X-1, n)]-accCG[i-1]) for i in range(1, n+1)) | grumpy-bookstore-owner | python3 clean and short code | dengl11 | 0 | 38 | grumpy bookstore owner | 1,052 | 0.571 | Medium | 17,181 |
https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/1646525/python-O(n)-time-O(1)-space-with-explanation | class Solution:
def prevPermOpt1(self, nums: List[int]) -> List[int]:
n = len(nums)-1
left = n
// find first non-decreasing number
while left >= 0 and nums[left] >= nums[left-1]:
left -= 1
// if this hits, it means we have the smallest possible perm
if left <= 0:
return nums
// the while loop above lands us at +1, so k is the actual value
k = left - 1
// find the largest number that's smaller than k
// while skipping duplicates
right = n
while right >= left:
if nums[right] < nums[k] and nums[right] != nums[right-1]:
nums[k], nums[right] = nums[right], nums[k]
return nums
right -= 1
return nums | previous-permutation-with-one-swap | python O(n) time, O(1) space with explanation | uzumaki01 | 3 | 322 | previous permutation with one swap | 1,053 | 0.508 | Medium | 17,182 |
https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/2082943/PYTHON-SOL-or-GREEDY-or-WELL-EXPLAINED-or-SIMPLE-or-EFFICIENT-APPROACH-or | class Solution:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
n = len(arr)
for i in range(n-2,-1,-1):
if arr[i] > arr[i+1]:
for j in range(n-1,i,-1):
if arr[j] < arr[i] and (j == i-1 or arr[j] != arr[j-1]):
arr[i],arr[j] = arr[j],arr[i]
return arr
return arr | previous-permutation-with-one-swap | PYTHON SOL | GREEDY | WELL EXPLAINED | SIMPLE | EFFICIENT APPROACH | | reaper_27 | 2 | 147 | previous permutation with one swap | 1,053 | 0.508 | Medium | 17,183 |
https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/1493969/Concise-oror-Greedy-oror-For-Beginners-oror-92-faster-oror | class Solution:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
ind = -1
for i in range(len(arr)-1,0,-1):
if arr[i-1]>arr[i]:
ind = i-1
break
if ind==-1: return arr
for i in range(len(arr)-1,ind,-1):
if arr[i]<arr[ind] and arr[i]!=arr[i-1]:
arr[i],arr[ind] = arr[ind],arr[i]
break
return arr | previous-permutation-with-one-swap | 📌📌 Concise || Greedy || For Beginners || 92% faster || 🐍 | abhi9Rai | 2 | 171 | previous permutation with one swap | 1,053 | 0.508 | Medium | 17,184 |
https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/1015220/Python3-find-the-place | class Solution:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
for i in reversed(range(len(arr)-1)):
if arr[i] > arr[i+1]: break
else: return arr
ii, val = i, 0
for k in range(i+1, len(arr)):
if val < arr[k] < arr[i]: ii, val = k, arr[k]
arr[i], arr[ii] = arr[ii], arr[i]
return arr | previous-permutation-with-one-swap | [Python3] find the place | ye15 | 2 | 98 | previous permutation with one swap | 1,053 | 0.508 | Medium | 17,185 |
https://leetcode.com/problems/distant-barcodes/discuss/411386/Two-Solutions-in-Python-3-(six-lines)-(beats-~95) | class Solution:
def rearrangeBarcodes(self, B: List[int]) -> List[int]:
L, A, i = len(B), [0]*len(B), 0
for k,v in collections.Counter(B).most_common():
for _ in range(v):
A[i], i = k, i + 2
if i >= L: i = 1
return A
class Solution:
def rearrangeBarcodes(self, B: List[int]) -> List[int]:
L, C = len(B), collections.Counter(B)
B.sort(key = lambda x: (C[x],x))
B[1::2], B[::2] = B[:L//2], B[L//2:]
return B
- Junaid Mansuri | distant-barcodes | Two Solutions in Python 3 (six lines) (beats ~95%) | junaidmansuri | 5 | 755 | distant barcodes | 1,054 | 0.457 | Medium | 17,186 |
https://leetcode.com/problems/distant-barcodes/discuss/1015250/Python3-every-other-spot | class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
freq = {}
for x in barcodes: freq[x] = 1 + freq.get(x, 0)
ans, i = [None] * len(barcodes), 0
for k, v in sorted(freq.items(), key=lambda x: x[1], reverse=True):
for _ in range(v):
ans[i] = k
i = i+2 if i+2 < len(ans) else 1
return ans | distant-barcodes | [Python3] every other spot | ye15 | 1 | 135 | distant barcodes | 1,054 | 0.457 | Medium | 17,187 |
https://leetcode.com/problems/distant-barcodes/discuss/2082962/PYTHON-or-EXPLAINED-WELL-or-HEAP-or-SIMPLE-or-FAST-or-EASY-or | class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
n = len(barcodes)
count = Counter(barcodes)
heap = []
for i in count:
heap.append((-count[i],i))
heapq.heapify(heap)
idx = 0
ans =[0]*n
while heap:
times,val = heapq.heappop(heap)
times = -times
for i in range(times):
ans[idx] = val
idx += 2
if idx >=n : idx = 1
return ans | distant-barcodes | PYTHON | EXPLAINED WELL | HEAP | SIMPLE | FAST | EASY | | reaper_27 | 0 | 83 | distant barcodes | 1,054 | 0.457 | Medium | 17,188 |
https://leetcode.com/problems/distant-barcodes/discuss/1307340/Easy-python-solution | class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
s=set(barcodes)
x=len(s)
if(x==1):
return barcodes
barcodes.sort()
q=mode(barcodes)
p=0
x1=0
while(p<len(barcodes)):
if(barcodes[p]==q):
del(barcodes[p])
x1=x1+1
continue
p=p+1
l2=len(barcodes)
l1=[0]*x1*x
z=0
a=0
i=0
while(a<l2 and i<len(l1)):
l1[z+i]=q
i=i+x
z=1
while(z<x):
i=0
while(a<l2 and i<len(l1)):
l1[z+i]=barcodes[a]
a=a+1
i=i+x
z=z+1
i=0
while(i<len(l1)):
if(l1[i]==0):
del(l1[i])
continue
i=i+1
return l1 | distant-barcodes | Easy python solution | Rajashekar_Booreddy | 0 | 169 | distant barcodes | 1,054 | 0.457 | Medium | 17,189 |
https://leetcode.com/problems/distant-barcodes/discuss/801339/Easy-to-Read-and-Understand-Python-Solution-with-Comments! | class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
# Get the counts of all of our barcode elements.
cnts = collections.Counter(barcodes)
# Put the -'ve counts along with themselves into a min heap.
# For those new to this we use -'ve because this is a min heap, so largest cnt pop'd first.
heap = [(-v, k) for k,v in cnts.items()]
heapq.heapify(heap)
res = []
# While we have elements on our heap.
while heap:
# pop the top element.
cnt1, num1 = heapq.heappop(heap)
# If the top element was the last we used, we need something different.
if res and res[-1] == num1:
# pop the next highest cnt element.
cnt, num = heapq.heappop(heap)
res.append(num)
cnt += 1
# If there's still elements left we put them back on the heap.
if cnt != 0:
heapq.heappush(heap, (cnt, num))
# We can also add the first that we popped, and push it back on the heap as well.
res.append(num1)
cnt1 += 1
if cnt1 != 0:
heapq.heappush(heap, (cnt1, num1))
# else we just add the highest cnt element and put the remaining back on.
else:
res.append(num1)
cnt1 += 1
if cnt1 != 0:
heapq.heappush(heap, (cnt1, num1))
return res | distant-barcodes | Easy to Read and Understand Python Solution with Comments! | Pythagoras_the_3rd | 0 | 198 | distant barcodes | 1,054 | 0.457 | Medium | 17,190 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/860984/Python-3-or-GCD-1-liner-or-Explanation | class Solution:
def gcdOfStrings(self, s1: str, s2: str) -> str:
return s1[:math.gcd(len(s1), len(s2))] if s1 + s2 == s2 + s1 else '' | greatest-common-divisor-of-strings | Python 3 | GCD 1-liner | Explanation | idontknoooo | 61 | 3,500 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,191 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/1136937/Python-Simple-iterative-(no-GCD) | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
m, n = len(str1), len(str2)
for i in range(min(m, n), 0, -1):
if n % i > 0 or m % i > 0: continue
a, b = m // i, n // i
test = str2[:i]
if test * a == str1 and test * b == str2:
return test
return '' | greatest-common-divisor-of-strings | [Python] Simple iterative (no GCD) | FooMan | 8 | 1,100 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,192 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/1120553/Short-and-Fast-Python-Recursion-Solution | class Solution:
def gcdOfStrings(self, s: str, t: str) -> str:
if not s: return t
if not t: return s
s, t = (s, t) if len(s) <= len(t) else (t, s)
if t[:len(s)] == s:
return self.gcdOfStrings(t[len(s):], s)
return '' | greatest-common-divisor-of-strings | Short and Fast Python Recursion Solution | Black_Pegasus | 5 | 845 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,193 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/1685848/Python-3-GCD-like-clean-solution-with-explanation | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
m, n = len(str1), len(str2)
if m == n:
if str1 == str2:
return str1
else:
return ""
elif m > n:
if str1[ : n] != str2:
return ""
else:
return self.gcdOfStrings(str1[n : ], str2)
else:
if str2[ : m] != str1:
return ""
else:
return self.gcdOfStrings(str2[m : ], str1) | greatest-common-divisor-of-strings | Python 3 GCD-like clean solution with explanation | xil899 | 3 | 396 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,194 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/1120574/Python-91-wexplanation | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
# swap if str2 longer than str1
str1, str2 = (str1, str2) if len(str1) >= len(str2) else (str1, str2)
len_str1 = len(str1)
len_str2 = len(str2)
# check if str1 == str2 * k
if str2 * int(len_str1 / len_str2) == str1:
return str2
best = ''
# prefix couldn't be longer than int(len_str2 / 2), exept it full word, wich we check already
for i in range(1, int(len_str2 / 2) + 1):
# check if prefix str2 * k == str2 and prefix str2 * k == str1 (from shortest to longest)
if str2[:i] * int(len_str2 / len(str2[:i])) == str2 and str2[:i] * int(len_str1 / len(str1[:i])) == str1:
best = str2[:i]
return best | greatest-common-divisor-of-strings | [Python] 91%, w/explanation | cruim | 3 | 821 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,195 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/2518779/Python-Iterative-and-with-GCD-Two-solutions | class Solution:
def gcdOfStrings2(self, str1: str, str2: str) -> str:
# check some conditions
if str1 == str2:
return str1
# check whether they could have common substring
if str1+str2 != str2+str1:
return ""
# get the shorter string of both
# since the prefix can only have a maximum length
# as long as the shorter string of both
if len(str1) > len(str2):
shorter = str2
longer = str1
else:
shorter = str1
longer = str2
# get the length of the strings, since we will need them later
shorter_length = len(shorter)
longer_length = len(longer)
# initialization of prefix
prefix = ""
# now we take all prefixes of one and see if they can
# be used to construct both strings.
for index in range(len(shorter), 0, -1):
# check whether the strings are divisable by the length of the prefix
if shorter_length % index == 0 and longer_length % index == 0:
# get the current prefix
pref = shorter[0:index]
# check whether the prefix repetition matches the strings
if shorter == pref*(shorter_length//index) and longer == pref*(longer_length//index):
prefix = pref
break
return prefix | greatest-common-divisor-of-strings | [Python] - Iterative and with GCD - Two solutions | Lucew | 1 | 133 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,196 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/1015047/Ultra-Simple-CppPython3-Solution-or-Suggesestions-for-optimization-are-welcomed-or | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
ans=""
if len(str1)<len(str2):
str1 , str2 = str2 , str1
temp=str2
for i in range(0,len(str2)):
if len(str1)%len(temp)==0 and temp*int(len(str1)/len(temp))==str1 and len(str2)%len(temp)==0 and temp*int(len(str2)/len(temp))==str2:
return temp
temp=temp[:-1]
return "" | greatest-common-divisor-of-strings | Ultra Simple Cpp/Python3 Solution | Suggesestions for optimization are welcomed | | angiras_rohit | 1 | 285 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,197 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/557072/Python-Straightforward-find-CD-of-both-lengths-~92100 | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
len1, len2 = len(str1), len(str2)
if set(str1) != set(str2):
return ""
stackCD = []
for i in range(1, min(len1, len2)+1):
if len1 % i == len2 % i == 0:
stackCD.append(i)
while stackCD:
i = stackCD.pop()
if str1[:i]*(len1//i) == str1 and str1[:i]*(len2//i) == str2:
return str1[:i]
return ""
``` | greatest-common-divisor-of-strings | Python Straightforward find CD of both lengths ~92/100 | leochans | 1 | 204 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,198 |
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/335470/Solution-in-Python-3-(faster-than-~100) | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if len(set(str1)) != len(set(str2)):
return ''
L1, L2 = len(str1), len(str2)
d = divisors(L2)
d.reverse()
for i in d:
s = str2[:i]
if L1%i == 0 and str2 == s*int(L2/i) and str1 == s*int(L1/i):
return s
def divisors(n):
d, e = [], []
for i in range(1,1+int(n**.5)):
if n%i == 0:
d += [i]
e += [int(n/i)]
e.reverse()
if d[-1] == e[0]: del e[0]
return(d+e)
- Python 3
- Junaid Mansuri | greatest-common-divisor-of-strings | Solution in Python 3 (faster than ~100%) | junaidmansuri | 1 | 965 | greatest common divisor of strings | 1,071 | 0.511 | Easy | 17,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.