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/mean-of-array-after-removing-some-elements/discuss/1893648/Python-easy-solution
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() remove = int(0.05 * len(arr)) return sum(arr[remove:len(arr)-remove]) / (len(arr) - (2 * remove))
mean-of-array-after-removing-some-elements
Python easy solution
alishak1999
0
121
mean of array after removing some elements
1,619
0.647
Easy
23,600
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1816148/2-Lines-Python-Solution-oror-60-Faster-oror-Memory-less-than-90
class Solution: def trimMean(self, arr: List[int]) -> float: for i in range(len(arr)//20): arr.remove(max(arr)) ; arr.remove(min(arr)) return sum(arr)/len(arr)
mean-of-array-after-removing-some-elements
2-Lines Python Solution || 60% Faster || Memory less than 90%
Taha-C
0
98
mean of array after removing some elements
1,619
0.647
Easy
23,601
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1761446/Python-dollarolution
class Solution: def trimMean(self, arr: List[int]) -> float: x = int(len(arr) * 0.05) arr = sorted(arr) arr = arr[x:len(arr)-x] return sum(arr)/len(arr)
mean-of-array-after-removing-some-elements
Python $olution
AakRay
0
87
mean of array after removing some elements
1,619
0.647
Easy
23,602
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1590644/Python-3-fast-solution-by-sorting
class Solution: def trimMean(self, arr: List[int]) -> float: n = len(arr) trim = n // 20 return sum(sorted(arr)[trim:n-trim]) / (n - 2*trim)
mean-of-array-after-removing-some-elements
Python 3 fast solution by sorting
dereky4
0
123
mean of array after removing some elements
1,619
0.647
Easy
23,603
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1457365/Sort-and-sub-sum-90-speed
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() len_arr = len(arr) n5percent = len_arr // 20 return (sum(arr[n5percent: len_arr - n5percent]) / (len_arr - 2 * n5percent))
mean-of-array-after-removing-some-elements
Sort and sub-sum, 90% speed
EvgenySH
0
84
mean of array after removing some elements
1,619
0.647
Easy
23,604
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1405981/Python3-Faster-Than-96.49-Memory-Less-Than-88.65
class Solution: def trimMean(self, arr: List[int]) -> float: arr.sort() l = len(arr) rate = 5 * l // 100 return sum(arr[rate:l - rate]) / (l - (rate * 2))
mean-of-array-after-removing-some-elements
Python3 Faster Than 96.49%, Memory Less Than 88.65%
Hejita
0
82
mean of array after removing some elements
1,619
0.647
Easy
23,605
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1311419/python-3-%3A-EASY-EXPLAINATION
class Solution: def trimMean(self, arr: List[int]) -> float: sortarr = sorted(arr) n = len(arr) return sum(sortarr[n//20 : -n//20]) / (n*0.9)
mean-of-array-after-removing-some-elements
python 3 : EASY EXPLAINATION
rohitkhairnar
0
99
mean of array after removing some elements
1,619
0.647
Easy
23,606
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1225835/36ms-Python
class Solution(object): def trimMean(self, arr): """ :type arr: List[int] :rtype: float """ #start = int(math.ceil(0.05*len(arr))) #end = len(arr)-start arr.sort() return float(sum(arr[int(math.ceil(0.05*len(arr))):(len(arr) - (int(math.ceil(0.05*len(arr)))))]))/(len(arr)-2*int(math.ceil(0.05*len(arr)))) #arr1 = arr[start:end] #return float(sum(arr1))/(len(arr1))
mean-of-array-after-removing-some-elements
36ms, Python
Akshar-code
0
71
mean of array after removing some elements
1,619
0.647
Easy
23,607
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1067041/Python3-simple-solution-beats-97-python3-users
class Solution: def trimMean(self, arr: List[int]) -> float: x = (len(arr)*5)//100 arr.sort() arr = arr[x:len(arr)-x] return sum(arr)/len(arr)
mean-of-array-after-removing-some-elements
Python3 simple solution beats 97% python3 users
EklavyaJoshi
0
95
mean of array after removing some elements
1,619
0.647
Easy
23,608
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1063466/Python-simple-3-liner
class Solution: def trimMean(self, arr: List[int]) -> float: trim = int(len(arr) / 20) arr.sort() return sum(arr[trim: len(arr) - trim]) / (len(arr) - trim * 2)
mean-of-array-after-removing-some-elements
Python simple 3 liner
peatear-anthony
0
92
mean of array after removing some elements
1,619
0.647
Easy
23,609
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1047741/Python3-faster-than-90.28
class Solution: def trimMean(self, arr: list): length = len(arr) removing_length = int(length *0.05) return round(sum(sorted(arr)[removing_length:-removing_length])/(length-removing_length*2),5)
mean-of-array-after-removing-some-elements
Python3 faster than 90.28%
WiseLin
0
109
mean of array after removing some elements
1,619
0.647
Easy
23,610
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1026756/Python3-1-line
class Solution: def trimMean(self, arr: List[int]) -> float: return sum(sorted(arr)[len(arr)//20:-len(arr)//20])/(len(arr)*0.9)
mean-of-array-after-removing-some-elements
[Python3] 1-line
ye15
0
33
mean of array after removing some elements
1,619
0.647
Easy
23,611
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1026756/Python3-1-line
class Solution: def trimMean(self, arr: List[int]) -> float: n = len(arr)//20 return sum(sorted(arr)[n:-n])/(len(arr)-2*n)
mean-of-array-after-removing-some-elements
[Python3] 1-line
ye15
0
33
mean of array after removing some elements
1,619
0.647
Easy
23,612
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/943309/Intuitive-approach
class Solution: def trimMean(self, arr: List[int]) -> float: sorted_arr = sorted(arr) num_5p = int(len(sorted_arr) * 0.05) removed_10p_arr = sorted_arr[num_5p:-num_5p] return sum(removed_10p_arr)/len(removed_10p_arr)
mean-of-array-after-removing-some-elements
Intuitive approach
puremonkey2001
0
37
mean of array after removing some elements
1,619
0.647
Easy
23,613
https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/900787/1619.-Python3-Remove-top-and-bottom-5-in-5-lines
class Solution: def trimMean(self, arr: List[int]) -> float: # Calculate how many elements make the top/bottom 5%. # Since the length of the array will always be a multiple # of 20, we don't need to do any special checks, just divide numToRemove = len(arr) // 20 # Remove the top and bottom 5% of the elements by finding # the min/max of the list for i in range(numToRemove): arr.remove(max(arr)) arr.remove(min(arr)) # Return the average of the new list return sum(arr) / len(arr)
mean-of-array-after-removing-some-elements
1619. [Python3] Remove top and bottom 5% in 5 lines
rafaelwi
-1
142
mean of array after removing some elements
1,619
0.647
Easy
23,614
https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/1103762/Python3-enumerate-all-candidates
class Solution: def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: mx = -inf for x in range(51): for y in range(51): val = 0 for xi, yi, qi in towers: d = sqrt((x-xi)**2 + (y-yi)**2) if d <= radius: val += int(qi/(1 + d)) if val > mx: ans = [x, y] mx = val return ans
coordinate-with-maximum-network-quality
[Python3] enumerate all candidates
ye15
2
143
coordinate with maximum network quality
1,620
0.376
Medium
23,615
https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/1447075/Elegant-Python3-Code
class Solution: def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: return max( ( (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius), [x, y]) for x in range(51) for y in range(51) ), key=lambda x: (x[0], -x[1][0], -x[1][1]) )[1]
coordinate-with-maximum-network-quality
Elegant Python3 Code
aquafie
0
126
coordinate with maximum network quality
1,620
0.376
Medium
23,616
https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/discuss/1103787/Python3-top-down-dp
class Solution: def numberOfSets(self, n: int, k: int) -> int: @cache def fn(n, k): """Return number of sets.""" if n <= k: return 0 if k == 0: return 1 return 2*fn(n-1, k) + fn(n-1, k-1) - fn(n-2, k) return fn(n, k) % 1_000_000_007
number-of-sets-of-k-non-overlapping-line-segments
[Python3] top-down dp
ye15
1
141
number of sets of k non overlapping line segments
1,621
0.422
Medium
23,617
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/899540/Python3-via-dictionary
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: ans = -1 seen = {} for i, c in enumerate(s): if c in seen: ans = max(ans, i - seen[c] - 1) seen.setdefault(c, i) return ans
largest-substring-between-two-equal-characters
[Python3] via dictionary
ye15
13
710
largest substring between two equal characters
1,624
0.591
Easy
23,618
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1173173/Python3-Simple-And-Readable-Solution
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: ans = [-1] for i in set(s): if(s.count(i) >= 2): ans.append(s.rindex(i) - s.index(i) - 1 ) return max(ans)
largest-substring-between-two-equal-characters
[Python3] Simple And Readable Solution
VoidCupboard
8
242
largest substring between two equal characters
1,624
0.591
Easy
23,619
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1016623/Easy-and-Clear-Solution-Python-3
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: occ=dict() mx=-1 for i in range(0,len(s)): if s[i] in occ.keys(): if i-occ[s[i]]-1>mx: mx=i-occ[s[i]]-1 else: occ.update({s[i]:i}) return mx
largest-substring-between-two-equal-characters
Easy & Clear Solution Python 3
moazmar
1
219
largest substring between two equal characters
1,624
0.591
Easy
23,620
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2824311/python
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: ans = -1 hashmap = {} for i, ch in enumerate(s): if ch not in hashmap: hashmap[ch] = i else: ans = max(ans, i - hashmap[ch] - 1) return ans
largest-substring-between-two-equal-characters
python
xy01
0
1
largest substring between two equal characters
1,624
0.591
Easy
23,621
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2651905/Python-O(n)-solution
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: seen = {} maxLen = -1 for idx, char in enumerate(s): if char in seen: maxLen = max(maxLen, idx - seen[char] - 1) else: seen[char] = idx return maxLen
largest-substring-between-two-equal-characters
Python O(n) solution
Mark5013
0
15
largest substring between two equal characters
1,624
0.591
Easy
23,622
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2423820/Beginner-Friendly-oror-Simple-Python-Solution-with-Comments
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: """ Time Complexity: O(n) Space Complexity: O(n) """ # Create a dictionary to store the index of the first occurence of each character # and a dictionary to store the index of the last occurence of each character first_occurence = {} last_occurence = {} for i, c in enumerate(s): if c not in first_occurence: first_occurence[c] = i last_occurence[c] = i # Iterate through the dictionary to find the maximum length max_length = -1 for c in first_occurence: max_length = max(max_length, last_occurence[c] - first_occurence[c] - 1) return max_length
largest-substring-between-two-equal-characters
Beginner Friendly || Simple Python Solution with Comments
Gyalecta
0
16
largest substring between two equal characters
1,624
0.591
Easy
23,623
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2340208/Easy-and-Simple-Python-Solution
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: dic={} max_diff=0 diff=0 for i in range(len(s)): if s[i] not in dic: dic[s[i]] =i else: diff=i-dic[s[i]] max_diff=max(max_diff,diff) if max_diff >-1: return max_diff-1 else: return -1
largest-substring-between-two-equal-characters
Easy and Simple Python Solution
sangam92
0
12
largest substring between two equal characters
1,624
0.591
Easy
23,624
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2252301/Python-Hashmap
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: d = {} maxlen = -1 for i , c in enumerate(s): if c not in d: d[c] = i ## Store the index of the first occurance. else: maxlen = max(maxlen , i - (d[c]+ 1) ) ## Length of the unqie string is last current index - (index + 1 - ) return maxlen
largest-substring-between-two-equal-characters
Python Hashmap
theReal007
0
15
largest substring between two equal characters
1,624
0.591
Easy
23,625
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/2129782/python-3-oror-simple-hash-map-solution-oror-O(n)O(1)
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: leftRight = {} for i, c in enumerate(s): if c not in leftRight: leftRight[c] = [i, i] else: leftRight[c][1] = i return max(right - left - 1 for left, right in leftRight.values())
largest-substring-between-two-equal-characters
python 3 || simple hash map solution || O(n)/O(1)
dereky4
0
39
largest substring between two equal characters
1,624
0.591
Easy
23,626
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1901884/Python-Solution
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: data, result = {}, -1 for index, char in enumerate(s): if char not in data: data[char] = index elif index - 1 - data[char] > result: result = index - 1 - data[char] return result
largest-substring-between-two-equal-characters
Python Solution
hgalytoby
0
36
largest substring between two equal characters
1,624
0.591
Easy
23,627
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1865511/Python-oror-Easy-Solution-oror-beat~99.25-ororusing-dictionary
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: d = {} maxi = 0 flag = 0 for i in range(len(s)): if len(d) == 0: d[s[i]] = i else: if s[i] in d: flag = 1 temp = i - d[s[i]] - 1 if temp > maxi: maxi = temp else: d[s[i]] = i if flag == 0: return -1 return maxi
largest-substring-between-two-equal-characters
Python || Easy Solution || beat~99.25% ||using dictionary
naveenrathore
0
36
largest substring between two equal characters
1,624
0.591
Easy
23,628
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1761483/Python-dollarolution
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: m = -1 for i in set(s): if s.count(i) > 1: x = len(s) - s[::-1].index(i)- 2 - s.index(i) if m < x: m = x return m
largest-substring-between-two-equal-characters
Python $olution
AakRay
0
87
largest substring between two equal characters
1,624
0.591
Easy
23,629
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1723380/Python-3-easy-and-simple-using-loops
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: maxi=0 c=0 for i in range(len(s)): a=s[i] for j in range(len(s)-1,-1,-1): if a==s[j] and i<j: c=1 maxi=max(maxi,len(s[i+1:j])) if c==0: return -1 else: return maxi
largest-substring-between-two-equal-characters
[Python 3] easy and simple using loops
akashmaurya001
0
62
largest substring between two equal characters
1,624
0.591
Easy
23,630
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1227529/Largest-Substring-Between-Two-Equal-Characters
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: ans = [] ans.append(-1) for i in set(s): if(s.count(i)>=2): ans.append(s.rindex(i)-s.index(i)-1) return max(ans)
largest-substring-between-two-equal-characters
Largest Substring Between Two Equal Characters
souravsingpardeshi
0
45
largest substring between two equal characters
1,624
0.591
Easy
23,631
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/1107848/Python3-simple-solution-using-dictionary
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: d = {} for i in range(len(s)): _s = s[::-1] x = _s.find(s[i]) if s[i] not in d and x != -1: d[s[i]] = len(s)-x-1-i-1 return max(d.values())
largest-substring-between-two-equal-characters
Python3 simple solution using dictionary
EklavyaJoshi
0
48
largest substring between two equal characters
1,624
0.591
Easy
23,632
https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/900544/Simple-HashMap-solution-in-Python-3%3A-100
class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: if(len(s)==len(set(s))): return -1 maxdiff=0 dicts=collections.defaultdict(list) for index,char in enumerate(s): dicts[char]+=[index] for k,v in dicts.items(): diff=v[-1]-v[0]-1 if diff>maxdiff: maxdiff=diff return maxdiff
largest-substring-between-two-equal-characters
Simple HashMap solution in Python 3: 100%
rcbcoders
0
50
largest substring between two equal characters
1,624
0.591
Easy
23,633
https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899547/Python3-dfs
class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: op1 = lambda s: "".join(str((int(c)+a)%10) if i&amp;1 else c for i, c in enumerate(s)) op2 = lambda s: s[-b:] + s[:-b] seen = set() stack = [s] while stack: s = stack.pop() seen.add(s) if (ss := op1(s)) not in seen: stack.append(ss) if (ss := op2(s)) not in seen: stack.append(ss) return min(seen)
lexicographically-smallest-string-after-applying-operations
[Python3] dfs
ye15
7
384
lexicographically smallest string after applying operations
1,625
0.66
Medium
23,634
https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899577/Python-DFS-with-high-level-explanation
class Solution: def __init__(self): self.smallest = float("inf") self.seen = {} def rotate(self, s, b): s = [char for char in s] def reverse_segment(start, end): end -= 1 while start < end: s[start], s[end] = s[end], s[start] start += 1 end -= 1 rotations = b % len(s) reverse_segment(0, len(s)) reverse_segment(0, rotations) reverse_segment(rotations, len(s)) return "".join(s) def add_one(self, char, a): return str((int(char)+a) % 10) def add(self, s, a): s = [char for char in s] for idx in range(len(s)): if idx % 2 != 0: s[idx] = self.add_one(s[idx], a) return "".join(s) def findLexSmallestString(self, s: str, a: int, b: int) -> str: if self.smallest == float("inf"): self.smallest = s if int(s) < int(self.smallest): self.smallest = s if s in self.seen: return self.seen[s] = True self.findLexSmallestString(self.rotate(s,b), a, b) self.findLexSmallestString(self.add(s,a), a, b) return self.smallest
lexicographically-smallest-string-after-applying-operations
Python DFS with high-level explanation
Frikster
1
160
lexicographically smallest string after applying operations
1,625
0.66
Medium
23,635
https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/1473993/Python-3-or-BFS-or-Explanation
class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: dq, visited = collections.deque([s]), set([s]) ans, n = s, len(s) while dq: cur = dq.popleft() ans = min(ans, cur) cur_a = ''.join([ str((int(cur[i]) + a) % 10) if i % 2 else cur[i] for i in range(n) ]) cur_b = cur[b:] + cur[:b] if cur_a not in visited: dq.append(cur_a) visited.add(cur_a) if cur_b not in visited: dq.append(cur_b) visited.add(cur_b) return ans
lexicographically-smallest-string-after-applying-operations
Python 3 | BFS | Explanation
idontknoooo
0
180
lexicographically smallest string after applying operations
1,625
0.66
Medium
23,636
https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/1230645/python3-or-dfs-or-simple-solution
class Solution: def __init__(self): self.mn = 'z' * 100 self.vis = set() def solve(self, st): if ''.join(st) in self.vis: return self.vis.add(''.join(st)) new = st for i in range(1, len(st), 2): st[i] = str((int(st[i]) + self.a) % 10) self.mn = min(''.join(st), self.mn) lp = new[-self.b:] fp = new[:self.l - self.b] new = lp + fp self.mn = min(self.mn, ''.join(new)) self.solve(st) self.solve(new) def findLexSmallestString(self, s: str, a: int, b: int) -> str: self.a = a ; self.b = b self.l = len(s) self.b = self.b % self.l s = list(s) self.solve(s) return self.mn
lexicographically-smallest-string-after-applying-operations
python3 | dfs | simple solution
_YASH_
0
126
lexicographically smallest string after applying operations
1,625
0.66
Medium
23,637
https://leetcode.com/problems/best-team-with-no-conflicts/discuss/2848106/Python-Heavily-commented-to-self-understand-first-of-all-DP-2-Loops
class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: ''' Using example scores = [1,2,3,5] and ages = [8,9,10,1] data is [(1, 5), (8, 1), (9, 2), (10, 3)] and dp is [5, 1, 2, 3] when curr player is (1, 5) there are no prev players -> so leave dp of curr as-is when curr player is (8, 1) prev player's score is not less than curr player score nor is previous player's age same as curr player age -> so leave dp of curr as-is when curr player is (9, 2) prev player (1, 5) has score NOT less than, and age NOT equal to ... skipping prev player (8, 1) has score YES less than ... so we do something! since the accumulated dp of prev player + curr's score is GREATER than curr's accumulated dp value: we update curr's accumulated dp value to be instead sum of prev player's dp value and curr's score when curr player is (10, 3) prev player (1, 5) has score NOT less, and age NTO equal to ... skipping prev player (8, 1) has score YES less, so update curr's dp value from 3 -> 3+1 = 4 prev player (9, 2) has score YES less, so update curr's dp value from 4 -> 4+2 = 6 finally we return the max of all dp values for the dream team. ''' # Sort by age and score ASC data = sorted(zip(ages, scores), key=lambda x:(x[0], x[1])) # Initialize dp with scores for each player dp = [score for age, score in data] N = len(data) # For every current player for curr in range(N): # Compare every previous player for prev in range(0, curr): # And if previous player score is less OR previous player is same age if (data[prev][1] <= data[curr][1] or data[curr][0] == data[prev][0]): # Then update dp value for current player to be the max of either # -> the current score as it is OR # -> the current score PLUS the dp value of previous player dp[curr] = max(dp[curr], data[curr][1] + dp[prev]) return max(dp)
best-team-with-no-conflicts
[Python] Heavily commented to self understand first of all - DP 2 Loops
graceiscoding
0
1
best team with no conflicts
1,626
0.412
Medium
23,638
https://leetcode.com/problems/best-team-with-no-conflicts/discuss/2813639/Python-(Simple-Dynamic-Programming)
class Solution: def bestTeamScore(self, scores, ages): ans = sorted(zip(ages,scores)) dp = [i[1] for i in ans] for i in range(1,len(ans)): for j in range(i): if ans[i][1] >= ans[j][1]: dp[i] = max(dp[i],dp[j]+ans[i][1]) return max(dp)
best-team-with-no-conflicts
Python (Simple Dynamic Programming)
rnotappl
0
2
best team with no conflicts
1,626
0.412
Medium
23,639
https://leetcode.com/problems/best-team-with-no-conflicts/discuss/1357546/subsequence-DP-sort-by-scores-Longest-Score-Sum-Increasing-Ages
class Solution: def lsis(self, ppl): # lambdas to avoid hardcoding [0] and [1] :) score = lambda idx: ppl[idx][0] age = lambda idx: ppl[idx][1] # suffix DP / knapsack # at each index -> include in subsequence / skip :) @functools.cache def dp(i, prev = -1): if i == len(ppl): return 0 # skip this player res = dp(i+1, prev) # pick this player if age(i) >= prev: res = max(res, score(i) + dp(i+1, age(i))) return res # return dp(0) # let's try bottom up 1D DP dp_next = [0]*1001 dp_cur = [0]*1001 for i in range(len(ppl)-1,-1,-1): for prev in range(1000,-1,-1): res = dp_next[prev] if age(i) >= prev: res = max(res, score(i) + dp_next[age(i)]) dp_cur[prev] = res dp_next = dp_cur dp_cur = [0]*1001 return dp_next[0] def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: ppl = [(score, age) for score, age in zip(scores, ages)] # let it get sorted by score, so I need to only check ages later ppl.sort() # now find Largest Sum Increasing Subsequence of ages ;) return self.lsis(ppl)
best-team-with-no-conflicts
subsequence DP-sort by scores-Longest Score Sum Increasing Ages
yozaam
0
145
best team with no conflicts
1,626
0.412
Medium
23,640
https://leetcode.com/problems/best-team-with-no-conflicts/discuss/899650/Python3-top-down-dp
class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: ages, scores = zip(*sorted(zip(ages, scores))) @lru_cache(None) def fn(i): """Return max score up to ith player included.""" if i < 0: return 0 # boundary condition return scores[i] + max((fn(ii) for ii in range(i) if ages[ii] == ages[i] or scores[ii] <= scores[i]), default=0) return max(fn(i) for i in range(len(scores)))
best-team-with-no-conflicts
[Python3] top-down dp
ye15
-1
170
best team with no conflicts
1,626
0.412
Medium
23,641
https://leetcode.com/problems/slowest-key/discuss/1172372/Python3-Simple-And-Readable-Solution
class Solution: def slowestKey(self, r: List[int], k: str) -> str: times = {r[0]: [k[0]]} for i in range(1 , len(r)): t = r[i] - r[i - 1] if(t in times): times[t].append(k[i]) else: times[t] = [k[i]] keys = times[max(times.keys())] return max(keys)
slowest-key
[Python3] Simple And Readable Solution
VoidCupboard
7
337
slowest key
1,629
0.593
Easy
23,642
https://leetcode.com/problems/slowest-key/discuss/1748201/Easy-Python-Three-Rows-Solution
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: for i in range(len(releaseTimes)-1, 0, -1): releaseTimes[i] = releaseTimes[i] - releaseTimes[i-1] return max(zip(releaseTimes,list(keysPressed)))[1]
slowest-key
Easy Python Three Rows Solution
MengyingLin
1
41
slowest key
1,629
0.593
Easy
23,643
https://leetcode.com/problems/slowest-key/discuss/1447915/Python3-memory-less-than-94-faster-than-77-simple-and-straightforward
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: max_duration = releaseTimes[0] max_key = keysPressed[0] for i in range(1, len(releaseTimes)): if (releaseTimes[i]-releaseTimes[i-1] > max_duration) or ( releaseTimes[i]-releaseTimes[i-1] == max_duration and keysPressed[i] >= max_key): max_key = keysPressed[i] max_duration = releaseTimes[i]-releaseTimes[i-1] return max_key
slowest-key
Python3 - memory less than 94%, faster than 77%, simple and straightforward
elainefaith0314
1
48
slowest key
1,629
0.593
Easy
23,644
https://leetcode.com/problems/slowest-key/discuss/1099764/Python3-simple-solution-beats-90-users
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: x = {releaseTimes[0] : keysPressed[0]} for i in range(1,len(releaseTimes)): a = releaseTimes[i] - releaseTimes[i-1] if a in x: if x[a] < keysPressed[i]: x[a] = keysPressed[i] else: x[a] = keysPressed[i] return x[max(x.keys())]
slowest-key
Python3 simple solution beats 90% users
EklavyaJoshi
1
51
slowest key
1,629
0.593
Easy
23,645
https://leetcode.com/problems/slowest-key/discuss/924637/Readable-Python-O(N)-No-ZipCounter
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: maxTime = float("-inf") maxChar = "" for i in range(len(keysPressed)): # the first one is alwasys the specified release time if i==0: time = releaseTimes[i] # everything after requires a difference in times # releasedTimes[i+1] >= releasedTimes[i] else: time = releaseTimes[i] - releaseTimes[i-1] if time > maxTime: maxTime = time maxChar = keysPressed[i] # comparing chars, operators allow for lexicographical comparison elif time == maxTime and maxChar < keysPressed[i]: maxChar = keysPressed[i] # time complexity : O(N) where N=len(keys)=len(releasedTimes) # space complexity: O(1) return maxChar
slowest-key
Readable Python O(N) No Zip/Counter
JuanTheDoggo
1
106
slowest key
1,629
0.593
Easy
23,646
https://leetcode.com/problems/slowest-key/discuss/909078/Python3-5-line-linear-scan
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: ans, mx = "", 0 for i, (t, k) in enumerate(zip(releaseTimes, keysPressed)): if i: t -= releaseTimes[i-1] if t > mx or t == mx and k > ans: ans, mx = k, t # update return ans
slowest-key
[Python3] 5-line linear scan
ye15
1
96
slowest key
1,629
0.593
Easy
23,647
https://leetcode.com/problems/slowest-key/discuss/909078/Python3-5-line-linear-scan
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: ans = "" mx = prev = 0 for t, k in zip(releaseTimes, keysPressed): mx, ans = max((mx, ans), (t-prev, k)) prev = t return ans
slowest-key
[Python3] 5-line linear scan
ye15
1
96
slowest key
1,629
0.593
Easy
23,648
https://leetcode.com/problems/slowest-key/discuss/909033/Python-Simple-solution
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: times = [0 for _ in range(26)] releaseTimes = [releaseTimes[0]] + [releaseTimes[i] - releaseTimes[i-1] for i in range(1, len(releaseTimes))] for r in range(len(releaseTimes)): c = ord(keysPressed[r]) - ord('a') times[c] = max(times[c], releaseTimes[r]) m = max(times) can = [t for t in range(len(times)) if times[t] == m] return chr(ord('a') + can[-1])
slowest-key
[Python] Simple solution
cyshih
1
93
slowest key
1,629
0.593
Easy
23,649
https://leetcode.com/problems/slowest-key/discuss/2811146/Python-Solution-EXPLAINED-LINE-BY-LINE
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: m=releaseTimes[0] #initially duration is releaseTimes[0] so take it max duration found till now index=0 #storing the character index of respective max duration (initially 0th index) for i in range(1,len(releaseTimes)): d=releaseTimes[i]-releaseTimes[i-1] #duration of key pressing #if duration d is maximum till now , update the m and index for that particular character #if duration is same as m , update the m and check lexographically larger character then update its index if d>m or (d==m and keysPressed[i]>keysPressed[index]): m=d #storing maximum duration index=i #keysPressed indexes return keysPressed[index] #found larger duration index from keyPressed
slowest-key
Python Solution - EXPLAINED LINE BY LINE✔
T1n1_B0x1
0
2
slowest key
1,629
0.593
Easy
23,650
https://leetcode.com/problems/slowest-key/discuss/2560909/Python-or-Slowest-Key-or-O(n)
class Solution(object): def slowestKey(self, releaseTimes, keysPressed): dur = releaseTimes[0] key = keysPressed[0] for i in range(1,len(keysPressed)): if releaseTimes[i] - releaseTimes[i-1] == dur and keysPressed[i] > key: key = keysPressed[i] elif releaseTimes[i] - releaseTimes[i-1] > dur: dur = releaseTimes[i] - releaseTimes[i-1] key = keysPressed[i] return key
slowest-key
Python | Slowest Key | O(n)
snehaa26_s
0
25
slowest key
1,629
0.593
Easy
23,651
https://leetcode.com/problems/slowest-key/discuss/2559222/Easy-12-lines-python-solution-with-Explanation
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: p=0 #holds the current maximum value key="" #holds the currently longest pressed key releaseTimes.insert(0,0) #adding zero as the first element for i in range(1,len(releaseTimes)): diff=releaseTimes[i]-releaseTimes[i-1] #finding the total time for which the key ispressed k=keysPressed[i-1] #the key for which "diff" is calculated if diff > p: p=diff key=k if diff==p: #if two keys are pressed for the same time, lexographically greater is taken key=max(key,k) return key
slowest-key
Easy 12 lines python solution with Explanation
keertika27
0
14
slowest key
1,629
0.593
Easy
23,652
https://leetcode.com/problems/slowest-key/discuss/2461048/Python3-or-Hashmap-duration-and-return-key-of-max-duration
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: prev_r = 0 d = defaultdict(int) for r, k in zip(releaseTimes, keysPressed): d[k] = max(d[k], r-prev_r) prev_r = r max_duration = max(list(d.values())) return sorted([k for k in d.keys() if d[k] == max_duration], reverse=True)[0]
slowest-key
Python3 | Hashmap duration and return key of max duration
Ploypaphat
0
15
slowest key
1,629
0.593
Easy
23,653
https://leetcode.com/problems/slowest-key/discuss/1900850/Python-Clean-and-Simple!-Multiple-Solutions!
class Solution: def slowestKey(self, releaseTimes, keysPressed): key, maxDur = keysPressed[0], releaseTimes[0] for i in range(1, len(releaseTimes)): dur = releaseTimes[i] - releaseTimes[i-1] if dur > maxDur: key = keysPressed[i] elif dur == maxDur: key = max(key, keysPressed[i]) maxDur = max(dur, maxDur) return key
slowest-key
Python - Clean and Simple! Multiple Solutions!
domthedeveloper
0
103
slowest key
1,629
0.593
Easy
23,654
https://leetcode.com/problems/slowest-key/discuss/1900850/Python-Clean-and-Simple!-Multiple-Solutions!
class Solution: def slowestKey(self, times, keys): durations = [times[i]-times[i-1] if i>0 else times[i] for i in range(len(times))] slowestKeys = [keys[i] for i in range(len(durations)) if durations[i] == max(durations)] return max(slowestKeys)
slowest-key
Python - Clean and Simple! Multiple Solutions!
domthedeveloper
0
103
slowest key
1,629
0.593
Easy
23,655
https://leetcode.com/problems/slowest-key/discuss/1900850/Python-Clean-and-Simple!-Multiple-Solutions!
class Solution: def slowestKey(self, t, k): return max(zip(map(sub,t,[0]+t),k))[1]
slowest-key
Python - Clean and Simple! Multiple Solutions!
domthedeveloper
0
103
slowest key
1,629
0.593
Easy
23,656
https://leetcode.com/problems/slowest-key/discuss/1773220/Interesting-Python3-one-liner-(very-slow)
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: return [i for _, i in sorted(zip([([0] + releaseTimes)[i] - ([0] + releaseTimes)[i - 1] for i in range(len(releaseTimes) + 1)][1:], keysPressed))][-1]
slowest-key
Interesting Python3 one-liner (very slow)
y-arjun-y
0
37
slowest key
1,629
0.593
Easy
23,657
https://leetcode.com/problems/slowest-key/discuss/1761521/Python-dollarolution
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: m = releaseTimes[0] x = [keysPressed[0]] for i in range(1,len(releaseTimes)): y = releaseTimes[i]-releaseTimes[i-1] if m < y: x = [keysPressed[i]] m = y elif m == y: x.append(keysPressed[i]) return sorted(x)[-1]
slowest-key
Python $olution
AakRay
0
42
slowest key
1,629
0.593
Easy
23,658
https://leetcode.com/problems/slowest-key/discuss/1709623/Python3-accepted-solution
class Solution: def slowestKey(self, rt: List[int], kp: str) -> str: li = ([rt[i] for i in range(len(rt)) if(i==0)] + [rt[i]-rt[i-1] for i in range(len(rt)) if(i!=0)]) return max([kp[i] for i in range(len(li)) if(li[i]==max(li))])
slowest-key
Python3 accepted solution
sreeleetcode19
0
45
slowest key
1,629
0.593
Easy
23,659
https://leetcode.com/problems/slowest-key/discuss/1639523/Python-O(n)-time-O(1)-space-simple-solution
class Solution: def slowestKey(self, times: List[int], keys: str) -> str: n = len(keys) maxdur = -1 res = "z" for i in range(n): if i == 0: dur = times[0] else: dur = times[i]-times[i-1] if dur > maxdur: maxdur = dur res = keys[i] elif dur == maxdur: res = max(res, keys[i]) else: pass return res
slowest-key
Python O(n) time, O(1) space simple solution
byuns9334
0
73
slowest key
1,629
0.593
Easy
23,660
https://leetcode.com/problems/slowest-key/discuss/1449209/Python-solution-with-comment
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: # Key: Key, value: duration pressed key_to_duration = {} # First item no need to get time by taking difference, so directly put into key_to_duration[keysPressed[0]] = releaseTimes[0] for i in range(1, len(releaseTimes)): # Get pressed duration time curr_duration = releaseTimes[i] - releaseTimes[i - 1] curr_key = keysPressed[i] # We can have the same key multiple times. Need to update with the longest duration key_to_duration[curr_key] = max(key_to_duration.get(curr_key, 0), curr_duration) # Initialize for making answer answer = '' longest = 0 # Key: pressed key, value: duration pressed for key, value in key_to_duration.items(): if value > longest: longest = value answer = key # we can have multiple same length durations, but we need to return lexicographically bigger # below if key: 'b', answer: 'a', it's True elif value == longest and key > answer: answer = key return answer
slowest-key
Python solution with comment
yukikitayama
0
27
slowest key
1,629
0.593
Easy
23,661
https://leetcode.com/problems/slowest-key/discuss/1448262/Python3-solution-or-O(n)-easy-approach
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: count = releaseTimes[0] let = keysPressed[0] for i in range(1, len(releaseTimes)): if count == (releaseTimes[i] - releaseTimes[i - 1]): if let < keysPressed[i]: let = keysPressed[i] if count < (releaseTimes[i] - releaseTimes[i-1]): count = (releaseTimes[i] - releaseTimes[i-1]) let = keysPressed[i] return let
slowest-key
Python3 solution | O(n) easy approach
FlorinnC1
0
24
slowest key
1,629
0.593
Easy
23,662
https://leetcode.com/problems/slowest-key/discuss/1448202/Python-Solution-TC%3A-96.02
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: max_time = releaseTimes[0] curr_time = 0 cur_ans = 0 n = len(releaseTimes) for i in range(n-1): j = i + 1 curr_time = releaseTimes[j] - releaseTimes[i] if(curr_time > max_time): max_time,cur_ans = curr_time,j elif(curr_time == max_time and ord(keysPressed[j]) > ord(keysPressed[cur_ans])): cur_ans = j return keysPressed[cur_ans]
slowest-key
Python Solution TC: 96.02%
Ritesh2345
0
26
slowest key
1,629
0.593
Easy
23,663
https://leetcode.com/problems/slowest-key/discuss/1448129/Python-Solution
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: startDuration = 0 maxDuration = 0 longestKey = None for letter, endDuration in zip(list(keysPressed), releaseTimes): duration = endDuration - startDuration startDuration = endDuration if duration == maxDuration: longestKey = max(longestKey, letter) elif duration > maxDuration: longestKey = letter maxDuration = duration return longestKey
slowest-key
Python Solution
peatear-anthony
0
24
slowest key
1,629
0.593
Easy
23,664
https://leetcode.com/problems/slowest-key/discuss/1447907/Python-O(N)-Time-O(1)-Space-solution.-Beats-98-with-comments-and-annotations
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: # (releaseTime, Character) # used @ because its ascii value is lower than "A" which will help in comparsion. slowKeySoFar = (0, '@') # Pad left of input to handle i - 1 overflow easily releaseTimes = [0] + releaseTimes # '#' is some random char we dont care. Just to pad indices equally keysPressed = '#' + keysPressed i = 1 while i < len(keysPressed): c = keysPressed[i] # calculate release time releaseTime = releaseTimes[i] - releaseTimes[i - 1] if releaseTime > slowKeySoFar[0]: slowKeySoFar = (releaseTime, c) elif releaseTime == slowKeySoFar[0]: # if same release times then check lexiographical order. if ord(c) > ord(slowKeySoFar[1]) : slowKeySoFar = (releaseTime, c) i += 1 return slowKeySoFar[1]
slowest-key
Python O(N) Time, O(1) Space solution. Beats 98% with comments and annotations
vineeth_moturu
0
24
slowest key
1,629
0.593
Easy
23,665
https://leetcode.com/problems/slowest-key/discuss/1319898/Easy-Python-Solution
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: temp=[releaseTimes[0]] for i in range(1,len(releaseTimes)): temp.append(releaseTimes[i]-releaseTimes[i-1]) idx=[] res="" for i in range(len(temp)): if temp[i]==max(temp): #idx.append(i) res+=keysPressed[i] return max(res)
slowest-key
Easy Python Solution
sangam92
0
72
slowest key
1,629
0.593
Easy
23,666
https://leetcode.com/problems/slowest-key/discuss/1273017/pythonic-solution-using-ord(char)
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: if keysPressed is None: return None if len(keysPressed) == 1: return keysPressed releaseTimes.insert(0, 0) pressed_durations = [] for i in range(1, len(releaseTimes)): duration_pressed = releaseTimes[i] - releaseTimes[i-1] pressed_durations.append((duration_pressed, i-1)) longest_ord = 0 longest_duration = float('-inf') answer = "" for duration, i in pressed_durations: char = keysPressed[i] if duration > longest_duration: longest_duration = max(longest_duration, duration) longest_ord = ord(char) - ord('a') answer = char elif duration == longest_duration: current_ord = ord(char) - ord('a') if current_ord > longest_ord: longest_ord = max(longest_ord, current_ord) answer = char return answer
slowest-key
pythonic solution using ord(char)
certifiedpandaboy
0
74
slowest key
1,629
0.593
Easy
23,667
https://leetcode.com/problems/slowest-key/discuss/1259870/python3-O(N)-solution-easy-to-read
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: prev_key, prev_ts = ('',0) ## this tuple will contain the previous key press and when that was released (prev_ts) slowest_key, max_duration = ('',0) ## this tuple will contain the slowest key and for how long it was pressed for for key,release_ts in zip(keysPressed,releaseTimes): ## convert keyPressed and releaseTimes into tuples and example the tuple one-by-one cur_duration = release_ts - prev_ts ## get the duration for which the key was pressed if prev_ts == 0: ## initial case, first key press prev_ts = release_ts max_duration=release_ts if cur_duration > max_duration: ## subsequent keys, check if current duration is more than max we have seen so far slowest_key, max_duration = key, cur_duration ## assign the max tuple with the new max and corresponding key elif cur_duration == max_duration: ## if current key press duration and max are the same, if key > slowest_key: ## check which one is higher lexically, if current key is higher then update the slowest key to current key slowest_key = key prev_key, prev_ts = key, release_ts ## set current key and release_ts to prev for next iteration return slowest_key
slowest-key
python3 O(N) solution easy to read
anupamkumar
0
59
slowest key
1,629
0.593
Easy
23,668
https://leetcode.com/problems/slowest-key/discuss/1187886/python-defaultdict
class Solution: def slowestKey(self, release_times: List[int], keys_pressed: str) -> str: key_tracker = defaultdict(list) for i, key in enumerate(keys_pressed): if i == 0: # the reason this is in a list is because default dict would fall on expecting ints # and thus append would not work anymore down below key_tracker[key] = [release_times[0]] else: key_tracker[key].append(release_times[i] - release_times[i-1]) # What the lambda is doing here is saying, first sort by the max of the collected list of key press times, # then sort by the key(the actual letter, lexigraphically) return sorted(key_tracker.items(), key=lambda x: (max(x[1]), x[0]))[-1][0]
slowest-key
python defaultdict
uzumaki01
0
150
slowest key
1,629
0.593
Easy
23,669
https://leetcode.com/problems/slowest-key/discuss/1174289/Python-one-pass-solution-O(n)
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: max_d = -1 letter = None duration = [releaseTimes[0]] for i in range(1,len(releaseTimes)): duration.append(releaseTimes[i]- releaseTimes[i-1]) for index, i in enumerate(duration): if(i > max_d): max_d = i letter = keysPressed[index] elif(i == max_d and ord(keysPressed[index])>ord(letter)): letter = keysPressed[index] return letter
slowest-key
Python one pass solution O(n)
Sai_prakash007
0
88
slowest key
1,629
0.593
Easy
23,670
https://leetcode.com/problems/arithmetic-subarrays/discuss/1231666/Python3-Brute-force
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] def find_diffs(arr): arr.sort() dif = [] for i in range(len(arr) - 1): dif.append(arr[i] - arr[i + 1]) return len(set(dif)) == 1 for i , j in zip(l , r): ans.append(find_diffs(nums[i:j + 1])) return ans
arithmetic-subarrays
[Python3] Brute force
VoidCupboard
9
468
arithmetic subarrays
1,630
0.8
Medium
23,671
https://leetcode.com/problems/arithmetic-subarrays/discuss/1314773/Python-or-without-sort-or-164ms-or-100-faster
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: out=[] for i, j in zip(l, r): out.append(self.canMakeArithmeticProgression(nums[i:j+1])) return out def canMakeArithmeticProgression(self, arr: List[int]) -> bool: minArr = min(arr) maxArr = max(arr) # if difference between minArr and maxArr cannot be divided into equal differences, then return false if (maxArr-minArr)%(len(arr)-1)!=0: return False # consecutive difference in arithmetic progression diff = int((maxArr-minArr)/(len(arr)-1)) if diff == 0: if arr != [arr[0]]*len(arr): return False return True # array to check all numbers in A.P. are present in input array. # A.P.[minArr, minArr+d, minArr+2d, . . . . . . . maxArr] check = [1]*len(arr) for num in arr: if (num-minArr)%diff != 0: return False check[(num-minArr)//diff]=0 # if 1 is still in check array it means at least one number from A.P. is missing from input array. if 1 in check: return False return True
arithmetic-subarrays
Python | without sort | 164ms | 100% faster
SurajJadhav7
6
476
arithmetic subarrays
1,630
0.8
Medium
23,672
https://leetcode.com/problems/arithmetic-subarrays/discuss/2391583/Python-easy-to-understand-approach-oror-beginner-friendly
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] for i in range(len(l)): check = nums[l[i]:r[i]+1] check.sort() val = check[0]-check[1] flag = True for x,y in itertools.pairwise(check): if x-y != val: flag = False ans.append(flag) return ans
arithmetic-subarrays
Python easy to understand approach || beginner friendly
Shivam_Raj_Sharma
2
79
arithmetic subarrays
1,630
0.8
Medium
23,673
https://leetcode.com/problems/arithmetic-subarrays/discuss/1816290/Python-Simple
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: main=[] for i in range(len(l)): l1=(nums[l[i]:r[i]+1]) mi = min(l1) ma=max(l1) check=(ma-mi)//(len(l1)-1) x=mi while(x<ma): if x not in l1: main.append(False) break l1.remove(x) x+=check if(x==ma): main.append(True) return main
arithmetic-subarrays
Python Simple
vedank98
2
46
arithmetic subarrays
1,630
0.8
Medium
23,674
https://leetcode.com/problems/arithmetic-subarrays/discuss/2765726/easy-python-solutionoror-beats-92
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: d = {} ans = [] for i in range(len(l)): d[i] = nums[l[i]:r[i]+1] for ele in d: j = 0 d[ele].sort() for i in range(2,len(d[ele])): if d[ele][i]-d[ele][i-1]!=d[ele][1]-d[ele][0]: ans.append(False) break j+=1 if j==len(d[ele])-2: ans.append(True) return ans
arithmetic-subarrays
easy python solution|| beats 92%
chessman_1
1
79
arithmetic subarrays
1,630
0.8
Medium
23,675
https://leetcode.com/problems/arithmetic-subarrays/discuss/1899388/Python-easy-solution-for-beginners-using-sorting
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: res = [] for i in range(len(l)): subarr = sorted(nums[l[i]:r[i]+1]) diff = [subarr[j+1] - subarr[j] for j in range(len(subarr) - 1)] if len(set(diff)) == 1: res.append(True) else: res.append(False) return res
arithmetic-subarrays
Python easy solution for beginners using sorting
alishak1999
1
48
arithmetic subarrays
1,630
0.8
Medium
23,676
https://leetcode.com/problems/arithmetic-subarrays/discuss/2832963/Python-wo-sorting-O(N*max(M))
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def is_arihmetic(l, r): mn,mx = float('inf'), -float('inf') for i in range(l, r+1): mx = max(mx, nums[i]) mn = min(mn, nums[i]) if (mx-mn) % (r-l) != 0: return False inc = (mx-mn) // (r-l) if inc == 0: return True seen = set() for i in range(l, r+1): if (nums[i] - mn) % inc != 0: return False if nums[i] in seen: return False seen.add(nums[i]) return True return [is_arihmetic(lb,rb) for lb, rb in zip(l, r)]
arithmetic-subarrays
Python w/o sorting O(N*max(M))
gleberof
0
2
arithmetic subarrays
1,630
0.8
Medium
23,677
https://leetcode.com/problems/arithmetic-subarrays/discuss/2806955/Python-3-Solution.
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def checkArithemetic(arr): n = len(arr) print("arr: ",arr) for k in range(n-2): if abs(arr[k] - arr[k+1]) != abs(arr[k+2] - arr[k+1]): return False return True ans = [] length = len(l) for i in range(length): part = sorted(nums[l[i]:r[i]+1]) if checkArithemetic(part): ans.append(True) else: ans.append(False) return ans
arithmetic-subarrays
Python 3 Solution.
fahadahasmi
0
1
arithmetic subarrays
1,630
0.8
Medium
23,678
https://leetcode.com/problems/arithmetic-subarrays/discuss/2805014/Python3-simple-solution-with-explanation
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: i = 0 ans = [] while i < len(l): subs = nums[l[i]:r[i]+1] subs.sort() diffs = [subs[i+1] - subs[i] for i in range(len(subs)-1)] ans.append(max(diffs) == min(diffs)) i += 1 return ans
arithmetic-subarrays
Python3 simple solution with explanation
sipi09
0
1
arithmetic subarrays
1,630
0.8
Medium
23,679
https://leetcode.com/problems/arithmetic-subarrays/discuss/2802627/Simple-python-with-step-by-step-comments.
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: #list for answer as per question answer=[] #loop through either l or r, as these subarrays give us the divisions for i in range(len(l)): #current subarray to inspect is defined as per question _cur = nums[l[i]:(r[i]+1)] #sort the current subarray _cur.sort() #find the difference between the first 2 elements _dif = _cur[1] - _cur[0] #test variable init at 0 _t=0 #loop through _cur: don't need to include 1st or last #we've already looked at first when finding _dif #we look at j+1 each loop so last loop of len(_cur) isn't necessary for j in range(1,len(_cur)-1): #if the dif between the next 2 elements is not the same as _dif if (_cur[j+1] - _cur[j]) != _dif: #change test var to 1 _t=1 #break the loop break #if test var is still 0 if _t==0: #we can add True to the answer list answer.append(True) #if that's not the case else: #add false to the list answer.append(False) #you know what this does return answer
arithmetic-subarrays
Simple python with step by step comments.
ATHBuys
0
2
arithmetic subarrays
1,630
0.8
Medium
23,680
https://leetcode.com/problems/arithmetic-subarrays/discuss/2792697/Python3%3A-Easy-to-understand
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: L = len(r) res = [False]*L for i in range(L): arr = sorted(nums[l[i]:r[i] + 1]) diff = set() for j in range(len(arr) - 1): diff.add(abs(arr[j + 1] - arr[j])) if len(diff) == 1: res[i] = True return res
arithmetic-subarrays
Python3: Easy to understand
mediocre-coder
0
3
arithmetic subarrays
1,630
0.8
Medium
23,681
https://leetcode.com/problems/arithmetic-subarrays/discuss/2768179/BF-Approach
class Solution: def checkArithmeticSubarrays(self, N: List[int], L: List[int], R: List[int]) -> List[bool]: ans = [] for l, r in zip(L, R): m0, m1 = min(N[l: r+1]), max(N[l: r+1]) # print(m0, m1, r, l, (m1-m0)//(r-l)) if m0 == m1: ans.append(True) elif len(set(N[l: r+1])) != (r+1-l): ans.append(False) else: ans.append(set(range(m0, m1+1, (m1-m0)//(r-l))) == set(N[l: r+1])) return ans
arithmetic-subarrays
BF Approach
Mencibi
0
3
arithmetic subarrays
1,630
0.8
Medium
23,682
https://leetcode.com/problems/arithmetic-subarrays/discuss/2752412/Python-or-Simple-sorting-solution
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] for i in range(len(l)): if r[i] - l[i] < 1: ans.append(False) continue diff, to_add = None, True cmp = nums[l[i]: r[i] + 1] cmp.sort() for j in range(1, len(cmp)): if diff is None: diff = cmp[j - 1] - cmp[j] else: if cmp[j - 1] - cmp[j] != diff: to_add = False break ans.append(to_add) return ans
arithmetic-subarrays
Python | Simple sorting solution
LordVader1
0
3
arithmetic subarrays
1,630
0.8
Medium
23,683
https://leetcode.com/problems/arithmetic-subarrays/discuss/2746055/Python3-Beginner-Friendly-A-Clear-and-Concise-way
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def isArithmetic(lst): interval = lst[1] - lst[0] for i in range(len(lst)-1): if lst[i+1] - lst[i] != interval: return False return True return [isArithmetic(sorted(nums[l[i]:r[i]+1])) for i in range(len(r))]
arithmetic-subarrays
[Python3] [Beginner Friendly] A Clear and Concise way
Lemorage
0
6
arithmetic subarrays
1,630
0.8
Medium
23,684
https://leetcode.com/problems/arithmetic-subarrays/discuss/2736603/python3-or-simple-or-easy-solution-or-99.78-faster
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: out = [] for i, j in zip(l, r): array = nums[i:j+1] array.sort() tmp = array[1] - array[0] flag = True for k in range(2, len(array)): if array[k] - array[k-1] != tmp: flag = False break out.append(flag) return out
arithmetic-subarrays
python3 | simple | easy solution | 99.78% faster
axce1
0
9
arithmetic subarrays
1,630
0.8
Medium
23,685
https://leetcode.com/problems/arithmetic-subarrays/discuss/2695228/Simple-Python-Solution-beats-95-in-runtime-and-91-in-memory
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: output = [] for i in range(0, len(l)): diff = r[i] - l[i] if diff < 2: output.append(True) else: temp = nums[l[i]:r[i]+1] temp.sort() lastArr = temp[1]-temp[0] flag = True for j in range(1, len(temp)-1): if temp[j+1]-temp[j] != lastArr: flag = False break if flag == True: output.append(True) else: output.append(False) return output
arithmetic-subarrays
Simple Python Solution beats 95% in runtime and 91% in memory
sunnysharma03
0
9
arithmetic subarrays
1,630
0.8
Medium
23,686
https://leetcode.com/problems/arithmetic-subarrays/discuss/2643893/Python-or-97
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] def returnTag(arr): arr.sort() for i in range(1,len(arr)-1): if arr[i]-arr[i-1]!=arr[i+1]-arr[i]: return False return True for i in range(len(l)): ans.append(returnTag(nums[l[i]:r[i]+1])) return (ans)
arithmetic-subarrays
Python | 97%
naveenraiit
0
7
arithmetic subarrays
1,630
0.8
Medium
23,687
https://leetcode.com/problems/arithmetic-subarrays/discuss/2385188/Python3-or-Solved-using-Generic-Timsort
class Solution: #T.C = O(m*n + m*(nlogn)) -> O(m*nlogn) #S.C = O(m + m*n) -> O(m*n) def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: #approach is for all i, get the effective range query using l and r -> [l[i], r[i]] #splice nums array from those indices and sort it in ascending order! #check every pair of adjacent elemetns to see if the difference is constant -> #easy case: subarray with any 2 elements will always be arithmetic sequence! n, m = len(nums), len(r) ans = [] for a in range(m): low, high = l[a], r[a] #get the splice of nums in that range cur_sub = nums[low: high+1] cur_sub.sort() #check if cur_sub is length 2! -> True if(len(cur_sub) == 2): ans.append(True) else: #cur_sub is gauranteed to have at least two elements since for every a #l[a] < r[a] for range query! #initialize diff as difference between first and second elements! diff = cur_sub[1] - cur_sub[0] #use bool flag1 flag = True for b in range(1, len(cur_sub)-1, 1): if(cur_sub[b+1] - cur_sub[b] != diff): ans.append(False) flag = False break if(flag == True): ans.append(True) return ans
arithmetic-subarrays
Python3 | Solved using Generic Timsort
JOON1234
0
12
arithmetic subarrays
1,630
0.8
Medium
23,688
https://leetcode.com/problems/arithmetic-subarrays/discuss/2383922/Python3-Solution-with-using-sortingset
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: res = [] for i in range(len(l)): arr = nums[l[i]:r[i] + 1] arr.sort() diff = arr[1] - arr[0] j = 2 while j < len(arr): if arr[j] - arr[j - 1] != diff: break j += 1 res.append(j == len(arr)) return res
arithmetic-subarrays
[Python3] Solution with using sorting/set
maosipov11
0
8
arithmetic subarrays
1,630
0.8
Medium
23,689
https://leetcode.com/problems/arithmetic-subarrays/discuss/2383922/Python3-Solution-with-using-sortingset
class Solution: def is_arithmetic_seq(self, nums, begin, end): s = set() _min, _max = float('inf'), float('-inf') for i in range(begin, end + 1): _min = min(_min, nums[i]) _max = max(_max, nums[i]) s.add(nums[i]) if (_max - _min) % (end - begin) != 0: return False interval = (_max - _min) // (end - begin) for i in range(end - begin + 1): if (_min + i * interval) not in s: return False return True def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: res = [] for i in range(len(l)): res.append(self.is_arithmetic_seq(nums, l[i], r[i])) return res
arithmetic-subarrays
[Python3] Solution with using sorting/set
maosipov11
0
8
arithmetic subarrays
1,630
0.8
Medium
23,690
https://leetcode.com/problems/arithmetic-subarrays/discuss/2313358/Python-Simple-fast-and-clean
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: res = [True]*len(l) for i in range(len(l)): sub = nums[l[i]:r[i]+1] sub.sort() diff = sub[1]-sub[0] for j in range(2,len(sub)): if sub[j] - sub[j-1] != diff: res[i]= False break return res
arithmetic-subarrays
Python Simple fast and clean
harsh30199
0
19
arithmetic subarrays
1,630
0.8
Medium
23,691
https://leetcode.com/problems/arithmetic-subarrays/discuss/2082378/Python3-%3A-95
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def check_arm(nums): if len(nums) <= 2: return True temp = nums[1] - nums[0] for i in range(2,len(nums)): if nums[i] - nums[i-1] != temp: return False return True res = [] for i, j in zip(l,r): res.append(check_arm(list(sorted(nums[i:j+1])))) return res
arithmetic-subarrays
Python3 : 95%
iamirulofficial
0
34
arithmetic subarrays
1,630
0.8
Medium
23,692
https://leetcode.com/problems/arithmetic-subarrays/discuss/2050049/Simple-Python-96-Faster-99-Memory
class Solution: def canMakeArithmeticProgression(self,arr: List[int]) -> bool: arr.sort() dif = arr[1] - arr[0] for i in range(len(arr)): if i > 0: if arr[i] - arr[i-1] != dif: return False return True def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: bools = [] for i in range(len(l)): bools.append(self.canMakeArithmeticProgression(nums[l[i]:r[i]+1])) return bools
arithmetic-subarrays
Simple Python 96% Faster 99% Memory
codeee5141
0
52
arithmetic subarrays
1,630
0.8
Medium
23,693
https://leetcode.com/problems/arithmetic-subarrays/discuss/1897544/Python-3-or-No-need-for-explanation
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans=[True for i in range(len((l)))] for i in range(len(l)): if r[i]-l[i]>=2: temp=nums[l[i]:r[i]+1] temp.sort() diff=temp[1]-temp[0] for j in range(2,len(temp)): if temp[j]-temp[j-1]!=diff: ans[i]=False break return ans
arithmetic-subarrays
Python 3 | No need for explanation
RickSanchez101
0
32
arithmetic subarrays
1,630
0.8
Medium
23,694
https://leetcode.com/problems/arithmetic-subarrays/discuss/1889936/Python3-Simple-Solution
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: stack = [] for (x, y) in zip(l, r): arr = nums[x:y + 1] arr.sort() diff = arr[1] - arr[0] is_arithmetic = True for i in range(1, len(arr) - 1): if arr[i + 1] - arr[i] != diff: is_arithmetic = False break stack.append(is_arithmetic) return stack
arithmetic-subarrays
Python3 Simple Solution
prodotiscus
0
24
arithmetic subarrays
1,630
0.8
Medium
23,695
https://leetcode.com/problems/arithmetic-subarrays/discuss/1864684/Python-or-Slice-and-Sort-Brute-Force
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: m = len(l) res = [] for i in range(m): seq = sorted(nums[l[i]:r[i]+1]) res.append(self.is_arithmetic(seq)) return res def is_arithmetic(self, nums): n = len(nums) if n < 2: return False dif = nums[1] - nums[0] for i in range(1, n): if nums[i] - nums[i-1] != dif: return False return True
arithmetic-subarrays
Python | Slice and Sort Brute Force
jgroszew
0
33
arithmetic subarrays
1,630
0.8
Medium
23,696
https://leetcode.com/problems/arithmetic-subarrays/discuss/1729737/Python-Two-Approaches-or-With-and-Without-sort
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: output=[] for i in range(len(l)): arr=nums[l[i]:r[i]+1] arr.sort() diff=arr[1]-arr[0] j=1 while j<len(arr)-1: if arr[j+1]-arr[j] != diff: output.append(False) break j+=1 else: output.append(True) return output
arithmetic-subarrays
Python Two Approaches | With and Without sort
shandilayasujay
0
42
arithmetic subarrays
1,630
0.8
Medium
23,697
https://leetcode.com/problems/arithmetic-subarrays/discuss/1729737/Python-Two-Approaches-or-With-and-Without-sort
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def checkArithmetic(arr: List[int]): if len(arr)==2: return True min_num=min(arr) max_num=max(arr) if min_num==max_num: return True diff=int((max_num-min_num)//(len(arr)-1)) if (max_num-min_num)%(len(arr)-1)!=0: return False res=[1]*(len(arr)) for num in arr: if (num-min_num)%diff !=0: return False res[(num-min_num)//diff]=0 if 1 in res: return False return True output=[] for i in range(len(l)): arr=nums[l[i]:r[i]+1] output.append(checkArithmetic(arr)) return output
arithmetic-subarrays
Python Two Approaches | With and Without sort
shandilayasujay
0
42
arithmetic subarrays
1,630
0.8
Medium
23,698
https://leetcode.com/problems/arithmetic-subarrays/discuss/1438517/WEEB-DOES-PYTHON
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: result = [] for low, high in zip(l, r): isArith = True arr = sorted(nums[low:high+1]) d = arr[1] - arr[0] for i in range(1,len(arr)-1): if arr[i+1] - arr[i] != d: result.append(False) isArith = False break if isArith: result.append(True) return result
arithmetic-subarrays
WEEB DOES PYTHON
Skywalker5423
0
60
arithmetic subarrays
1,630
0.8
Medium
23,699