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/shifting-letters/discuss/938487/Python3-suffix-sum-O(N)
class Solution: def shiftingLetters(self, S: str, shifts: List[int]) -> str: for i in reversed(range(1, len(shifts))): shifts[i-1] += shifts[i] S = list(S) for i, x in enumerate(shifts): S[i] = chr(97 + (ord(S[i]) - 97 + x) % 26) return "".join(S)
shifting-letters
[Python3] suffix sum O(N)
ye15
0
94
shifting letters
848
0.454
Medium
13,800
https://leetcode.com/problems/shifting-letters/discuss/938487/Python3-suffix-sum-O(N)
class Solution: def shiftingLetters(self, S: str, shifts: List[int]) -> str: for i in reversed(range(1, len(shifts))): shifts[i-1] += shifts[i] return "".join(chr(97 + (ord(c) - 97 + x) % 26) for c, x in zip(S, shifts))
shifting-letters
[Python3] suffix sum O(N)
ye15
0
94
shifting letters
848
0.454
Medium
13,801
https://leetcode.com/problems/shifting-letters/discuss/938487/Python3-suffix-sum-O(N)
class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: ans = [""] * len(s) for i in reversed(range(len(s))): if i+1 < len(s): shifts[i] += shifts[i+1] ans[i] = chr((ord(s[i]) - 97 + shifts[i]) % 26 + 97) return "".join(ans)
shifting-letters
[Python3] suffix sum O(N)
ye15
0
94
shifting letters
848
0.454
Medium
13,802
https://leetcode.com/problems/shifting-letters/discuss/708698/Python3-suffix-sum-Shifting-Letters
class Solution: def shiftingLetters(self, S: str, shifts: List[int]) -> str: for i in range(len(shifts)-2, -1, -1): shifts[i] += shifts[i+1] return ''.join(chr((ord(c) - ord('a') + shift) % 26 + ord('a')) for c, shift in zip(S, shifts))
shifting-letters
Python3 suffix sum - Shifting Letters
r0bertz
0
138
shifting letters
848
0.454
Medium
13,803
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706156/python%3A-easy-to-understand-3-situations
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: #initialization, starting index is 0, result is res left,res,index = -1,0,0 while index != len(seats): # only right is 1 if left == -1 and seats[index] == 1: res = max(res,index) left = index index+=1 continue # only left is 1 if index == len(seats)-1 and seats[index] == 0: res = max(res,index-left) index+=1 continue # left and right both 1, sitting in the middle if seats[index] == 1: res = max(res,(index-left)//2) left = index index+=1 return res
maximize-distance-to-closest-person
python: easy to understand, 3 situations
zoey513
2
95
maximize distance to closest person
849
0.476
Medium
13,804
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1694631/Python-O(n)-Solution-with-comments
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: distance = -1 Maximum_Distance = 0 for i in range(len(seats)): if seats[i] == 1: # if seat is 0 that means it is empty we won't perform any action if distance == -1: # if we are encounting the first seated person Maximum_Distance = i else: Maximum_Distance = max(Maximum_Distance,((i - distance) // 2)) # if we have encounted any seated person before then we will compare for the maximum distance till now to the current distance possible distance = i if seats[-1] == 0: # if end seat is empty Maximum_Distance = max(Maximum_Distance, (len(seats) - 1 - distance)) return Maximum_Distance
maximize-distance-to-closest-person
Python O(n) Solution with comments
yashitanamdeo
2
131
maximize distance to closest person
849
0.476
Medium
13,805
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/343294/Solution-in-Python-3-(beats-~99)
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: L = len(seats) S = [i for i in range(L) if seats[i]] d = [S[i+1]-S[i] for i in range(len(S)-1)] if len(S) > 1 else [0] return max(max(d)//2, S[0], L-1-S[-1]) - Python 3 - Junaid Mansuri
maximize-distance-to-closest-person
Solution in Python 3 (beats ~99%)
junaidmansuri
2
647
maximize distance to closest person
849
0.476
Medium
13,806
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/254232/Python3-Solution%3A-using-split-and-simple-trick-for-corner-cases
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: seats = ''.join(map(str, seats)) intervals = [len(x) for x in seats.split('1')] intervals[0] *= 2 intervals[-1] *= 2 return max((i + 1) // 2 for i in intervals)
maximize-distance-to-closest-person
Python3 Solution: using `split` and simple trick for corner cases
jinjiren
2
131
maximize distance to closest person
849
0.476
Medium
13,807
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1694755/Python-O(n)-or-easy-to-understand-solution
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: n = len(seats) MAX = 10 ** 9 prefix = [MAX] * n suffix = [MAX] * n for i in range(n): if seats[i] == 1: prefix[i] = 0 elif i > 0 and prefix[i - 1] != MAX: prefix[i] = 1 + prefix[i - 1] for i in range(n - 1, -1, -1): if seats[i] == 1: suffix[i] = 0 elif i < n - 1 and suffix[i + 1] != MAX: suffix[i] = 1 + suffix[i + 1] ans = 0 for i in range(n): ans = max(ans, min(prefix[i], suffix[i])) return ans
maximize-distance-to-closest-person
[Python] O(n) | easy to understand solution
BrijGwala
1
31
maximize distance to closest person
849
0.476
Medium
13,808
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1693893/Python-Solution-O(n)-Intuitive-Easy-to-understand-Algorithm-Explained
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: l_to_r, r_to_l = [0] * len(seats), [0] * len(seats) if seats[0] == 0: l_to_r[0] = float('inf') for i in range(1, len(l_to_r)): if seats[i] == 0: l_to_r[i] = l_to_r[i - 1] + 1 if seats[len(seats) - 1] == 0: r_to_l[len(seats) - 1] = float('inf') for i in range(len(seats) - 2, -1, -1): if seats[i] == 0: r_to_l[i] = r_to_l[i + 1] + 1 res = float('-inf') for i in range(len(seats)): temp = min(l_to_r[i], r_to_l[i]) res = max(temp, res) return res
maximize-distance-to-closest-person
Python Solution, O(n), Intuitive, Easy to understand, Algorithm Explained
pradeep288
1
41
maximize distance to closest person
849
0.476
Medium
13,809
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1692715/Python3-Onepass-keep-last-position
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: maxDist = 0 lastSeat = -1 for i,seat in enumerate(seats): if seat == 1: # if else deals with 1st edge case # if lastSeat is not overwritten by a non-positive number, then no person sits to the left newDist = (i-lastSeat)//2 if lastSeat >= 0 else i maxDist = max(maxDist, newDist) lastSeat = i # deal with 2nd edge case maxDist = max(maxDist, len(seats)-1-lastSeat) return maxDist
maximize-distance-to-closest-person
[Python3] Onepass keep last position
Rainyforest
1
43
maximize distance to closest person
849
0.476
Medium
13,810
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1081775/Python-2-Solutions-with-simple-explanation
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: maxDist = seats.index(1) seats.reverse() maxDist = max(maxDist, seats.index(1)) string = "" for seat in seats: string += str(seat) lis = string.split('1') print(lis) for string in lis: if string != '': maxDist = max(maxDist, (len(string)+1) // 2) return maxDist
maximize-distance-to-closest-person
Python 2 Solutions with simple explanation
mahadrehan
1
116
maximize distance to closest person
849
0.476
Medium
13,811
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1081775/Python-2-Solutions-with-simple-explanation
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: indices = [] for i in range(0, len(seats)): if seats[i] == 1: indices.append(i) greatest = max(indices[0],len(seats)- 1 - indices[-1]) for i in range(1, len(indices)): if (indices[i] - indices[i-1])//2 > greatest: greatest = (indices[i] - indices[i-1])//2 return greatest
maximize-distance-to-closest-person
Python 2 Solutions with simple explanation
mahadrehan
1
116
maximize distance to closest person
849
0.476
Medium
13,812
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/914792/Maximum-Distance-or-Python-3-or-beats-98
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: m = 0 count = 1 #check how many seats are empty at the left while not seats[m]: m += 1 #check all the empty seats inbetween for s in seats[m:]: if s == 0: count += 1 else: m = max(m, count//2) count = 1 else: #check the empty seats at the end m = max(m, count-1) return m
maximize-distance-to-closest-person
Maximum Distance | Python 3 | beats 98%
Jagaya
1
255
maximize distance to closest person
849
0.476
Medium
13,813
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2808764/Python-solution-easy-to-understand
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: first_one = len(seats) last_one = -1 max_dist = float("-inf") for idx in range(len(seats)): if seats[idx] == 0: i = idx - 1 left_dist = 1 while i >= 0 and seats[i] != 1: left_dist += 1 i -= 1 j = idx + 1 right_dist = 1 while j < len(seats) and seats[j] != 1: right_dist += 1 j += 1 closest_dist = min(left_dist, right_dist) max_dist = max(max_dist, closest_dist) else: first_one = min(first_one, idx) last_one = max(last_one, idx) # edge case if the 1st or/and last index has 0 if seats[0] == 0: dist = first_one - 0 max_dist = max(max_dist, dist) if seats[-1] == 0: dist = len(seats) - 1 - last_one max_dist = max(max_dist, dist) return max_dist
maximize-distance-to-closest-person
Python solution easy to understand
SuvroBaner
0
3
maximize distance to closest person
849
0.476
Medium
13,814
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706155/python%3A-easy-to-understand-3-situations
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: #initialization, starting index is 0, result is res left,res,index = -1,0,0 while index != len(seats): # only right is 1 if left == -1 and seats[index] == 1: res = max(res,index) left = index index+=1 continue # only left is 1 if index == len(seats)-1 and seats[index] == 0: res = max(res,index-left) index+=1 continue # left and right both 1, sitting in the middle if seats[index] == 1: res = max(res,(index-left)//2) left = index index+=1 return res
maximize-distance-to-closest-person
python: easy to understand, 3 situations
zoey513
0
3
maximize distance to closest person
849
0.476
Medium
13,815
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706150/python%3A-3-situations
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: #initialization, starting index is 0, result is res left,res,index = -1,0,0 while index != len(seats): # only right is 1 if left == -1 and seats[index] == 1: res = max(res,index) left = index index+=1 continue # only left is 1 if index == len(seats)-1 and seats[index] == 0: res = max(res,index-left) index+=1 continue # left and right both 1, sitting in the middle if seats[index] == 1: res = max(res,(index-left)//2) left = index index+=1 return res
maximize-distance-to-closest-person
python: 3 situations
zoey513
0
2
maximize distance to closest person
849
0.476
Medium
13,816
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2695039/Python-O(n)-Easy-Pre-and-Post-Array-Solution
class Solution(object): def maxDistToClosest(self, seats): ## Get the length and initialize the prefix and postfix arrays to know the closest person to left and right n=len(seats); pre,post=[-1]*n,[-1]*n; best = 0; MAX = 10000000; ## If there is a taken/not taken seat at the start, mark pre if seats[0] == 1: pre[0] = 0; else: pre[0] = MAX; ## If there is a taken/not taken seat at end, mark post if seats[n-1] == 1: post[n-1] = n-1; else: post[n-1] = MAX; ## Iterate over the seats to populate the pre and post arrays for x in range(1,n): ## If we find someone at the current seat, mark pre at current since we are iterating left to right if seats[x] == 1: pre[x] = x; ## If we don't, take the previous seat value. elif pre[x-1] != -1: pre[x] = pre[x-1]; ## If we find someone at the current index from the right of the seats, mark post with shifted index. if seats[n-1-x] == 1: post[n-1-x] = n-1-x; ## If we don't, take next seat value elif post[n-x] != -1: post[n-1-x] = post[n-x]; ## Iterate through the list ## We are trying to find the maximum distance we have from someone. ## So we check the minimum distance to someone from our left in pre and our right in post inclusive of current location ## It doesn't matter if there's a taken seat at index, it will just be 0 ## Then we try to maximize that minimum at each location. for x in range(n): best = max( best, min( abs( x-pre[x] ), abs( x-post[x] ) ) ); ## return answer return best;
maximize-distance-to-closest-person
Python O(n) Easy Pre and Post Array Solution
zeyf
0
6
maximize distance to closest person
849
0.476
Medium
13,817
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2389868/Linear-Python3-solution
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: max_dist, prev = 0, -1 i = 0 while i < len(seats): if seats[i] == 1: if prev == -1: max_dist = i else: max_dist = max(max_dist, (i - prev) // 2) prev = i i += 1 return max(max_dist, i - 1 - prev)
maximize-distance-to-closest-person
Linear Python3 solution
azatey
0
41
maximize distance to closest person
849
0.476
Medium
13,818
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2184698/Python-easy-to-read-and-understand
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: n = len(seats) i, j = 0, n-1 zeros = 0 ans = 0 while i < n and seats[i] == 0: zeros += 1 ans = max(ans, zeros) i += 1 zeros = 0 while j >= 0 and seats[j] == 0: zeros += 1 ans = max(ans, zeros) j -= 1 zeros = 0 while i < j: if seats[i] == 0: zeros += 1 ans = max(ans, (zeros+1) // 2) else: zeros = 0 i += 1 return ans
maximize-distance-to-closest-person
Python easy to read and understand
sanial2001
0
83
maximize distance to closest person
849
0.476
Medium
13,819
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1700107/Easy-Python3-Solution-(Accepted)(Commented)
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: prev = 0 //Maintain a previous pointer at the starting of array when traversing in forward direction ans = 0 //To store the max distance for i in range(len(seats)): //Traverse the array if seats[i] == 1: //If a persion is found in a seat then ans = max(ans, (i-prev)//2) //Calculate the distance from both the persons by dividing the total distance by 2 prev = i //Update the prev pointer ans = max(ans, len(seats)-1-prev) //Check a case where there was only one person in the array and the travelsal is complete then the distance will be the length of the array - the position of the person prev = len(seats)-1 //Now traversing the array in reverse direction for i in range(len(seats)-1, -1, -1): if seats[i] == 1: ans = max(ans, (prev-i)//2) prev = i ans = max(ans, prev) return ans
maximize-distance-to-closest-person
Easy Python3 Solution (Accepted)(Commented)
sdasstriver9
0
45
maximize distance to closest person
849
0.476
Medium
13,820
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1694548/Rick-gives-solution-for-Maximize-Distance-to-Closest-Person-or-Python
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: occu=[] for i in range(len(seats)): if seats[i]==1: occu.append(i) ma=-1 if len(occu)==1: return max(occu[0]-0,len(seats)-1-(occu[0])) for i in range(len(occu)): if i==0: ma=max(occu[i]-0,ma) continue elif i==len(occu)-1: ma=max(len(seats)-1-occu[i],ma) ma=max((occu[i]-occu[i-1])//2,ma) return ma
maximize-distance-to-closest-person
Rick gives solution for Maximize Distance to Closest Person | Python
RickSanchez101
0
15
maximize distance to closest person
849
0.476
Medium
13,821
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1694192/Python3-Short-and-fairly-simple-solution-or-O(N)-time-132ms
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: res, s = 0, -1 # The s variable is for start and is initialised with -1 to handle the case where seats[0] == 0 for i,seat in enumerate(seats): # Single pass to get the maximum required result if seat: # If seats[i] =1 you need to calculate the max distance for the person who wants to sit if s == -1: # As I said before, this would do the trick of handling the seats[0] = 0 case res = max(res, i) # Since, the start is the first seat the max distance is the index of the occupied seat we encountered to its right else: res = max(res, ((i-s)//2)) # If s not -1 this means the seat is between two occupied seats, meaning the minimum distance from each of the seats to the mid point s = i # Since you have encountered an occupied seat, now the start will be the current occupied seat return max(res, len(seats)-1-s) # This is, you might have already realised, the case to handle the right end seats[-1] = 0 # The s would be storing the last encountered occupied seat index. and the return statement will return of max of them. ```
maximize-distance-to-closest-person
[Python3] Short and fairly simple solution | O(N) time 132ms
nandhakiran366
0
15
maximize distance to closest person
849
0.476
Medium
13,822
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1693832/O(n)-Time-Complexity-or-One-Pass-or-Optimized-or-Easy-understanding
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: n = len(seats) result, left, right = 0, -1, -1 for i in range(n): if seats[i]==1: left, right = right, i if left==-1: result = max(result, right) else: result = max(result, (right-left)//2) if seats[-1]==0: result = max(result, n-right-1) return result
maximize-distance-to-closest-person
O(n) Time Complexity | One-Pass | Optimized | Easy-understanding
Aman_24
0
17
maximize distance to closest person
849
0.476
Medium
13,823
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1693519/Python3-97.35-or-Beginner-Friendly-or-Well-Documented
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: # find the longest 0 sequence, left, right, and mid def find_from_side(l): ans = 0 for x in l: if x == 1: return ans ans += 1 # find the maximum distance to the closest person from mid def find_from_mid(l): ans = 0 output = [i for i, x in enumerate(l) if x == 1] leng = len(output) # put -inf as a default value to avoid the 'no mid sequence' case rev = [-inf] for i in range(leng - 1): rev.append((output[i + 1] - output[i]) // 2) return rev left = find_from_side(seats) right = find_from_side(seats[::-1]) mid = find_from_mid(seats) # calculate maximum value among left, right, and everything in mid return max(left, right, max(mid))
maximize-distance-to-closest-person
Python3 97.35% | Beginner Friendly | Well Documented
doneowth
0
17
maximize distance to closest person
849
0.476
Medium
13,824
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1693325/Python-Easy-Solution-!!-Checking-Adjacent-Distance-!!-O(N)
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: if seats.count(1)==1: ind=seats.index(1) s=ind e=len(seats)-ind-1 return max(s,e) pre=0 curr=0 mid=[] for i in range(len(seats)): if seats[i]==1: mid.append(i) ans=-100000 i=0 while i<len(mid)-1: if mid[i+1]-mid[i]>ans: ans=mid[i+1]-mid[i] i=i+1 s,e=0,0 if seats[0]==0: s=mid[0] if seats[len(seats)-1]==0: e=len(seats)-1-mid[-1] if max(s,e)>ans//2: return max(s,e) return ans//2 # If It is Useful to Understand Please UpVote 🙏🙏 Please Support Me
maximize-distance-to-closest-person
Python Easy Solution !! Checking Adjacent Distance !! O(N)
ASHOK_KUMAR_MEGHVANSHI
0
15
maximize distance to closest person
849
0.476
Medium
13,825
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1692854/Simple-One-Pass-Python-Solution-With-Iterator
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: res, cnt = 0, 0 it = iter(seats) while next(it) == 0: res += 1 for s in it: if s == 0: cnt += 1 else: res = max(res, (cnt + 1) // 2) cnt = 0 return max(res, cnt)
maximize-distance-to-closest-person
Simple One Pass Python Solution With Iterator
atiq1589
0
16
maximize distance to closest person
849
0.476
Medium
13,826
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1692718/Python3-or-Simple-approach-or-Linear
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: candidates = list() i = 0 q = 0 while (seats[i] == 0): q += 1 i=i+1 candidates.append(q) q = 0 max_q = 0 for i in range(i, len(seats)): s = seats[i] if s: max_q = max(max_q, q) q = 0 else: q += 1 candidates.append( math.ceil(max_q / 2)) if not seats[len(seats)-1]: candidates.append(q) return max(candidates) ```
maximize-distance-to-closest-person
Python3 | Simple approach | Linear
letyrodri
0
18
maximize distance to closest person
849
0.476
Medium
13,827
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1692674/Python3-Resizable-Sliding-Window-(2-Pointers)
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: res, last = 0, -1 for i, seat in enumerate(seats): if seat: # `else i` takes care of the edge case when we do not have a seat at first index res = max(res, (i - last) // 2 if last >= 0 else i) last = i # `len(seats) - 1 - last` takes care of the edge case when we do not have a seat at last index return max(res, len(seats) - 1 - last if not seats[-1] else 0)
maximize-distance-to-closest-person
[Python3] Resizable Sliding Window (2 Pointers)
PatrickOweijane
0
83
maximize distance to closest person
849
0.476
Medium
13,828
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1560876/Python3-One-Pass-Solution-with-using-two-pointers
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: left = 0 distance = 0 for right in range(len(seats)): if seats[right] == 0: continue if seats[left] == 0: distance = max(distance, right - left) # border case: most left seats = 0 else: distance = max(distance, (right - left) // 2) left = right return max(distance, right - left) # border case: most right seats = 0
maximize-distance-to-closest-person
[Python3] One Pass Solution with using two pointers
maosipov11
0
51
maximize distance to closest person
849
0.476
Medium
13,829
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1449151/Simple-Python-O(n)-one-pass-solution
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: prev_seat_idx = -1 n_empty_seats = ret = 0 for i in range(len(seats)): if seats[i]: if prev_seat_idx == -1: ret = max(ret, n_empty_seats) else: ret = max(ret, (i-prev_seat_idx)//2) prev_seat_idx = i n_empty_seats = 0 else: n_empty_seats += 1 ret = max(ret, n_empty_seats) return ret
maximize-distance-to-closest-person
Simple Python O(n) one pass solution
Charlesl0129
0
66
maximize distance to closest person
849
0.476
Medium
13,830
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1408288/Intuitive-Python-single-pass-solution
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: ret = cur_empty = 0 at_start = True for i, occupied in enumerate(seats): if occupied: if not at_start: dist = cur_empty//2+1 if cur_empty%2 else cur_empty//2 else: dist = cur_empty at_start = False ret = max(ret, dist) cur_empty = 0 else: cur_empty += 1 ret = max(ret, cur_empty) return ret
maximize-distance-to-closest-person
Intuitive Python single pass solution
Charlesl0129
0
31
maximize distance to closest person
849
0.476
Medium
13,831
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1384272/Easy-Fast-Python-Solution-(Faster-greater-95-Memory-less-99)
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: d, ele, val = 0, 0, 0 bw, fl = [], [] length = len(seats) # Counting 0's in the starting/front if seats[0] == 0: i = 0 while seats[i] != 1: i += 1 fl.append(i) # Counting 0's in the end/last if seats[-1] == 0: i = length-1 while seats[i] != 1: i -= 1 fl.append(length-1 - i) # Counting 0's in between for i in range(length): if seats[i] != 1: d += 1 else: if d != 0: bw.append(d) d = 0 if fl: fl.sort(reverse=True) ele = fl[0] if bw: bw.sort(reverse=True) if bw[0] == 2: val = 1 elif bw[0] > 2: if bw[0] % 2 == 0: val = (bw[0]//2) else: val = (bw[0]//2) + 1 else: val = bw[0] if ele >= val: return ele else: return val
maximize-distance-to-closest-person
Easy, Fast Python Solution (Faster > 95%, Memory < 99%)
the_sky_high
0
61
maximize distance to closest person
849
0.476
Medium
13,832
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/1237007/Python3-Easy-to-understand-solution-by-hash-map
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: res, dic = 0, {} for idx, cur in enumerate(seats): if cur in dic: res = max(res, (idx - dic[cur])//2) if cur == 1: if not dic: res = idx dic[cur] = idx return max(res, len(seats) - dic[1] - 1)
maximize-distance-to-closest-person
Python3 Easy to understand solution by hash map
georgeqz
0
60
maximize distance to closest person
849
0.476
Medium
13,833
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/916423/python3-beats-80-clear-and-concise
class Solution: def search(self,l,n,i): try: res = l.index(n,i) except: return -1 return res def maxDistToClosest(self, seats: List[int]) -> int: i_0 = self.search(seats, 0, 0) i_1 = self.search(seats, 1, 0) if i_0 > i_1: max_d = 1 search_1 = True else: max_d = i_1 - i_0 search_1 = False seated = False while not seated: if search_1: i_1 = self.search(seats, 1, i_0) if i_1 == -1: d = len(seats) - i_0 max_d = max(d, max_d) seated = True else: d = (i_1 - i_0 + 1) // 2 max_d = max(d, max_d) search_1 = False else: i_0 = self.search(seats, 0, i_1) if i_0 == -1: seated = True else: search_1 = True return max_d
maximize-distance-to-closest-person
python3, beats 80%, clear and concise
w7089
0
43
maximize distance to closest person
849
0.476
Medium
13,834
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/915828/Python-on-solution
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: location = [] for i in range(len(seats)): if seats[i] == 1: location.append(i) distance_left,distance_right = location[0],len(seats)-location[-1]-1 if len(location) == 1: return max(distance_left,distance_right) else: distance_mid = 0 for i in range(len(location)-1): distance_mid = max(distance_mid,int((location[i+1]-location[i])/2)) return max(distance_mid,distance_left,distance_right)
maximize-distance-to-closest-person
Python on solution
yingziqing123
0
35
maximize distance to closest person
849
0.476
Medium
13,835
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/915801/Python-Clean-and-Simple
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: last = result = 0 for i, seat in enumerate(seats): if seat: result = max(result, (i-last) // 2) last = i return max(result, len(seats)-1-last, seats.index(1))
maximize-distance-to-closest-person
[Python] Clean & Simple
yo1995
0
37
maximize distance to closest person
849
0.476
Medium
13,836
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/915284/Python3-linear-scan
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: ans = cnt = one = 0 for x in seats: if not x: cnt += 1 # number of consequtive empty seats else: ans = max(ans, (cnt + 1)//2 if one else cnt) cnt, one = 0, 1 return max(ans, cnt)
maximize-distance-to-closest-person
[Python3] linear scan
ye15
0
47
maximize distance to closest person
849
0.476
Medium
13,837
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/915284/Python3-linear-scan
class Solution: def maxDistToClosest(self, seats: List[int]) -> int: ans = 0 ii = -1 for i, x in enumerate(seats): if x: ans = max(ans, i) if ii < 0 else max(ans, (i-ii)//2) ii = i return max(ans, i - ii)
maximize-distance-to-closest-person
[Python3] linear scan
ye15
0
47
maximize distance to closest person
849
0.476
Medium
13,838
https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/424670/Python-Simple-Solution
class Solution(object): def maxDistToClosest(self, seats): indices = [0]+[i for i in range(len(seats)) if seats[i]==1]+[len(seats)-1] diff = [(indices[i] - indices[i-1])/2 for i in range(1,len(indices))] ind = max(seats.index(1), seats[::-1].index(1)) return max(max(diff), ind)
maximize-distance-to-closest-person
Python Simple Solution
saffi
0
150
maximize distance to closest person
849
0.476
Medium
13,839
https://leetcode.com/problems/rectangle-area-ii/discuss/1398210/Python3-sweeping
class Solution: def rectangleArea(self, rectangles: List[List[int]]) -> int: line = [] for x1, y1, x2, y2 in rectangles: line.append((y1, x1, x2, 1)) line.append((y2, x1, x2, 0)) ans = yy = val = 0 seg = [] for y, x1, x2, tf in sorted(line): ans += val * (y - yy) yy = y if tf: insort(seg, (x1, x2)) else: seg.remove((x1, x2)) val = 0 prev = -inf for x1, x2 in seg: val += max(0, x2 - max(x1, prev)) prev = max(prev, x2) return ans % 1_000_000_007
rectangle-area-ii
[Python3] sweeping
ye15
1
212
rectangle area ii
850
0.537
Hard
13,840
https://leetcode.com/problems/loud-and-rich/discuss/2714041/Python-Pure-topological-sort
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: richer_count = [0 for _ in range(len(quiet))] graph = defaultdict(list) answer = [idx for idx in range(len(quiet))] ## create the graph so that we go from the richer to the poorer for rich, poor in richer: graph[rich].append(poor) richer_count[poor] += 1 ## we include the richest ones. queue = collections.deque([]) for person, rich_count in enumerate(richer_count): if not rich_count: queue.append(person) while queue: person = queue.popleft() ## pointer to the quietest person quieter_person = answer[person] for poorer in graph[person]: ## pointer to the quietest person richer than me quieter_richer = answer[poorer] ## on the answer we are storing the pointer to the quietest one. so for the next poorer we are going to store the pointer which contains the quietest answer[poorer] = min(quieter_person, quieter_richer, key = lambda prsn : quiet[prsn]) richer_count[poorer] -= 1 if not richer_count[poorer]: queue.append(poorer) return answer
loud-and-rich
Python Pure topological sort
Henok2011
1
77
loud and rich
851
0.582
Medium
13,841
https://leetcode.com/problems/loud-and-rich/discuss/939564/Python3-(memoized)-dfs-O(N)
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: graph = {} # graph as adjacency list for x, y in richer: graph.setdefault(y, []).append(x) @lru_cache(None) def fn(x): """Return richer &amp; loudest person given person.""" ans = x for xx in graph.get(x, []): if quiet[fn(xx)] < quiet[ans]: ans = fn(xx) return ans return [fn(x) for x in range(len(quiet))]
loud-and-rich
[Python3] (memoized) dfs O(N)
ye15
1
70
loud and rich
851
0.582
Medium
13,842
https://leetcode.com/problems/loud-and-rich/discuss/2736922/simple-Python-Solution
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: N = len(quiet) graph = [[] for _ in range(N)] for i,j in richer: graph[j].append(i) answer = [None] * N def explore(node): if answer[node] is None: answer[node] = node for child in graph[node]: cand = explore(child) if quiet[cand] < quiet[answer[node]]: answer[node] = cand return answer[node] return map(explore, range(N))
loud-and-rich
simple Python Solution
vijay_2022
0
2
loud and rich
851
0.582
Medium
13,843
https://leetcode.com/problems/loud-and-rich/discuss/2333986/Python3-or-Solved-using-Topo-Sort-%2B-bfs
class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: #Let len(richer) = n and let len(quiet) = m! #Time: O(n + m + m + m*m + m + m) -> O(m^2 + n) #Space: O(m*m + m + m + m*m + m) -> O(m^2) #step 1: build adjacency list representation and update indegrees of every node initially! adj = [[] for _ in range(len(quiet))] indegrees = [0] * len(quiet) #we want edges to go from richer to poorer so that ancestors of every node are all people #who have more money than the node person! for rel in richer: richer, poorer = rel[0], rel[1] adj[richer].append(poorer) indegrees[poorer] += 1 queue = deque() ancestors = [] for i in range(len(quiet)): new = set() new.add(i) ancestors.append(new) #step 2: fill in the queue all nodes that have indegrees of 0! #step 3: proceeding with Kahn's algorithm and recording list of all ancestors to every node! while queue: cur = queue.pop() for neighbor in adj[cur]: ancestors[neighbor].add(cur) ancestors[neighbor].update(ancestors[cur]) indegrees[neighbor] -= 1 if(indegrees[neighbor] == 0): queue.append(neighbor) ancestors = [list(s) for s in ancestors] output = [] #step 4:for each person, find the least quiet person who also has more money than the current #person we're iterating on! for a in range(len(ancestors)): cur_ancestors = ancestors[a] if(len(cur_ancestors) == 1): output.append(a) continue minimum = cur_ancestors[0] for ancestor in cur_ancestors: #check if current person with more money than person a has lower quiet level! if(quiet[ancestor] < quiet[minimum]): minimum = ancestor output.append(minimum) return output
loud-and-rich
Python3 | Solved using Topo-Sort + bfs
JOON1234
0
16
loud and rich
851
0.582
Medium
13,844
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2068528/Simple-Python-one-liner
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return (arr.index(max(arr)))
peak-index-in-a-mountain-array
Simple Python one-liner
tusharkhanna575
3
144
peak index in a mountain array
852
0.694
Medium
13,845
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1568560/Python-intuitive-solution-with-explanation-(two-approaches-binary-search-and-brutefoce)
class Solution(object): def peakIndexInMountainArray(self, arr): """ :type arr: List[int] :rtype: int """ Brute force for i in range(1,len(arr)-1): if arr[i-1] < arr[i] and arr[i+1] < arr[i]: return i
peak-index-in-a-mountain-array
Python intuitive solution with explanation (two approaches, binary search and brutefoce)
Abeni
3
144
peak index in a mountain array
852
0.694
Medium
13,846
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1568560/Python-intuitive-solution-with-explanation-(two-approaches-binary-search-and-brutefoce)
class Solution(object): def peakIndexInMountainArray(self, arr): """ :type arr: List[int] :rtype: int """ #binary search lower = 0 upper = len(arr)-1 while lower <= upper: mid = (lower+upper)//2 print(arr[mid]) if arr[mid-1] < arr[mid] > arr[mid+1]: return mid elif arr[mid-1] < arr[mid] < arr[mid+1]: # we are at the left side of the mountain we need to climb up to the right lower = mid+1 elif arr[mid-1] > arr[mid] > arr[mid+1]: # we are at the right side of the mountain we need to climb up to the left upper = mid-1
peak-index-in-a-mountain-array
Python intuitive solution with explanation (two approaches, binary search and brutefoce)
Abeni
3
144
peak index in a mountain array
852
0.694
Medium
13,847
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2377750/Python-Solution-Binary-Search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: low = 0 high = len(arr) - 1 while low <= high : mid = (low+high)//2 if arr[mid] < arr[mid+1]: low = mid + 1 elif arr[mid] > arr[mid+1]: high = mid - 1 return low
peak-index-in-a-mountain-array
Python Solution [Binary Search]
Yauhenish
2
33
peak index in a mountain array
852
0.694
Medium
13,848
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1150221/Python3-1-Line-Solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
[Python3] 1 Line Solution
Lolopola
2
40
peak index in a mountain array
852
0.694
Medium
13,849
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2833569/Pen-n-Paper-Solution-oror-with-3-examples-ororEasy-SolutionororPython
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: low=0 #first index high=len(arr)-1 #last index while low<high: #if true then calculate mid mid=(low+high)//2 #mid is the index of the middle element if arr[mid-1]<=arr[mid] and arr[mid]>=arr[mid+1]: #if condition satisfies then simply return the index value of middle element i.e mid return mid elif arr[mid]<arr[mid+1]: #if middle ele is smaller than next element low=mid #then increse the index value of low and again loop the arr using updated low pointer else: # and vice versa...!! high=mid #keep doing..!! #stay motivated..!!
peak-index-in-a-mountain-array
Pen n Paper Solution || with 3 examples ||Easy Solution||Python
user9516zM
1
18
peak index in a mountain array
852
0.694
Medium
13,850
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1847043/Easy-to-understand-solution.-Beats-99-submissions-in-terms-of-space.
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start = 0 end = len(arr)-1 while start < end: mid = start + (end-start)//2 if arr[mid] > arr[mid+1]: end = mid else: start = mid + 1 return end
peak-index-in-a-mountain-array
Easy to understand solution. Beats 99% submissions in terms of space.
1903480100017_A
1
50
peak index in a mountain array
852
0.694
Medium
13,851
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1658653/Python-all-approaches
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return(arr.index(max(arr)))
peak-index-in-a-mountain-array
Python all approaches
CoderIsCodin
1
94
peak index in a mountain array
852
0.694
Medium
13,852
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1658653/Python-all-approaches
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: for i in range(1,len(arr)): if(arr[i]<arr[i-1]): return(i)
peak-index-in-a-mountain-array
Python all approaches
CoderIsCodin
1
94
peak index in a mountain array
852
0.694
Medium
13,853
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1658653/Python-all-approaches
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start = 0 end = len(arr) mid = int(start +((end-start)/2)) while(start<end): if(arr[mid] < arr[mid+1]): start = (mid+1) else: end = mid mid = int(start +((end-start)/2)) return(start)
peak-index-in-a-mountain-array
Python all approaches
CoderIsCodin
1
94
peak index in a mountain array
852
0.694
Medium
13,854
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1154426/Python-one-liner-solution(Simple-and-Fast)
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
Python one-liner solution(Simple & Fast)
kuanyshbekuly
1
110
peak index in a mountain array
852
0.694
Medium
13,855
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1052673/Python-Binary-Search-O(log-n)
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: lo, hi = 0, len(arr) while lo < hi: m = (lo+hi) // 2 if arr[m-1] < arr[m] > arr[m+1]: return m elif arr[m-1] < arr[m]: lo = m else: hi = m+1 raise Exception("Invalid test case?")
peak-index-in-a-mountain-array
Python Binary Search O(log n)
dev-josh
1
139
peak index in a mountain array
852
0.694
Medium
13,856
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/552781/2-Solutions-or-Easy-to-understand-or-Faster-or-Time-and-Space-complexities-or-Simple-or-Python
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return self.optimized(arr) def optimized(self, arr): """ Time: O(logn), n = length of list Space: O(1) """ start, end = 0, len(arr) - 1 while start < end: mid = (start + end) // 2 if arr[mid-1] < arr[mid] and arr[mid] > arr[mid + 1]: return mid if arr[mid-1] < arr[mid]: start = mid + 1 else: end = mid - 1 return start def brute(self, arr): """ Time complexity: O(n), n = length of array Space: O(1) """ for i in range(len(arr) - 1): if arr[i]>arr[i+1]: return i
peak-index-in-a-mountain-array
2 Solutions | Easy to understand | Faster | Time and Space complexities | Simple | Python
Mrmagician
1
186
peak index in a mountain array
852
0.694
Medium
13,857
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2848311/python%3A-binary-search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: s = 0 e = len(arr) - 1 while s < e: mid = (s+e) // 2 if arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1]: return mid if arr[mid-1] < arr[mid] and arr[mid] < arr[mid+1]: s = mid else: e = mid
peak-index-in-a-mountain-array
python: binary search
zoey513
0
1
peak index in a mountain array
852
0.694
Medium
13,858
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2847776/Beats-100-Python-code
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
Beats 100% Python code
Akash2907
0
1
peak index in a mountain array
852
0.694
Medium
13,859
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2844889/Simple-step-by-step-solution%3A-PYTHON
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: if len(arr)<3: return 0 # 0 2 3 7 9 5 4 3 l=0 r=4 mid=2 p = 8 l=0 r=1 mid=5 p=5 l=4 r=4 l,r = 0,len(arr)-1 while(l<r): mid = (l+r)//2 peak = arr[mid] if arr[mid-1]<peak and arr[mid+1]<peak: return mid elif arr[mid-1]<peak and arr[mid+1]>peak: l = mid elif arr[mid-1]>peak and arr[mid+1]<peak: r = mid return l
peak-index-in-a-mountain-array
Simple step by step solution: PYTHON
arvindgongati
0
1
peak index in a mountain array
852
0.694
Medium
13,860
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2835815/1-line-python-solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(sorted(arr)[-1])
peak-index-in-a-mountain-array
1 line python solution
Cosmodude
0
4
peak index in a mountain array
852
0.694
Medium
13,861
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2814422/Peak-Index-in-a-Mountain-or-Python-very-easy-solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: peak = max(arr) for i in range(len(arr)): if arr[i] == peak: return i
peak-index-in-a-mountain-array
Peak Index in a Mountain | Python very easy solution
jashii96
0
2
peak index in a mountain array
852
0.694
Medium
13,862
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2762780/Python3-or-BS
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid - 1] < arr[mid] > arr[mid + 1]: return mid elif arr[mid - 1] < arr[mid] < arr[mid + 1]: left = mid else: right = mid
peak-index-in-a-mountain-array
Python3 | BS
joshua_mur
0
1
peak index in a mountain array
852
0.694
Medium
13,863
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2761532/SImple-Python-Solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: if len(arr) == 3: return arr[1] left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left)// 2 if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]: return mid if arr[mid] > arr[-1] and arr[mid] > arr[mid + 1]: right = mid - 1 else: left = mid + 1
peak-index-in-a-mountain-array
SImple Python Solution
ArnoldB
0
5
peak index in a mountain array
852
0.694
Medium
13,864
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2705261/easy-iterative
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: for i in range(0,len(arr)): if(arr[i]>arr[i+1]): return i return len(arr)-1
peak-index-in-a-mountain-array
easy iterative
rahul026
0
3
peak index in a mountain array
852
0.694
Medium
13,865
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2700171/weird-binary-search-but-it-works
class Solution: def isDecreasing(self, arr, index): if index == len(arr)-1: return True return arr[index+1] < arr[index] def peakIndexInMountainArray(self, arr: List[int]) -> int: left, right = 0, len(arr)-1 mid = right // 2 while left < right-1: if self.isDecreasing(arr, mid): right = mid else: left = mid mid = (left + right) // 2 return right
peak-index-in-a-mountain-array
weird binary search but it works
d1c3
0
4
peak index in a mountain array
852
0.694
Medium
13,866
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2664592/Python3-or-binary-search-and-using-inbuilt-method
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
Python3 | binary search & using inbuilt method
19pa1a1257
0
6
peak index in a mountain array
852
0.694
Medium
13,867
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2664592/Python3-or-binary-search-and-using-inbuilt-method
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start=0 end=len(arr)-1 while start<=end: mid=start+(end-start)//2 if arr[mid]>arr[mid-1] and arr[mid]>arr[mid+1]: return mid elif arr[mid-1]>arr[mid] and arr[mid]>arr[mid+1]: end=mid-1 else: start=mid+1
peak-index-in-a-mountain-array
Python3 | binary search & using inbuilt method
19pa1a1257
0
6
peak index in a mountain array
852
0.694
Medium
13,868
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2652409/Simple-Python-Solution%3A-Faster-than-91
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: low, high = 0, len(arr) - 1 while low <= high: mid = low + (high - low)//2 print(mid) if arr[mid-1] < arr[mid] > arr[mid + 1]: return mid elif arr[mid-1] > arr[mid]: high = mid elif arr[mid + 1] > arr[mid]: low = mid + 1 return low
peak-index-in-a-mountain-array
Simple Python Solution: Faster than 91 %
vijay_2022
0
2
peak index in a mountain array
852
0.694
Medium
13,869
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2558318/Python3-or-Easy-Binary-Search-Solution
class Solution: #Time-Complexity: O(log(n)), where n = len(arr)! #Space-Complexity: O(1) def peakIndexInMountainArray(self, arr: List[int]) -> int: #Basically, we know that input array is gauranteed to be a #mountain type array with exactly one peak! #Basically, we can perform binary search on input array #and handle the two cases where we don't find peak! #Case 1: Current element is greater than left neighbor but #smaller than right neighbor -> current index lies to left #of peak so reduce search space to right half! #Case 2: Current element is greater than right neighbor but #smaller than left neighbor -> current index lies to right #of peak so reduce search space to left half! l, h = 0, (len(arr) - 1) #as long as we have at least one index pos. rem. to consider, #continue binary searching! while l <= h: mid = (l + h) // 2 #if middle index happens to be 0, adjust it to 1 since #peak index can't ever be 0! if(mid == 0): mid = 1 middle = arr[mid] #we found peak! if(middle > arr[mid - 1] and middle > arr[mid+1]): return mid #mid index is to left of peak! elif(arr[mid-1] < middle < arr[mid+1]): l = mid + 1 continue else: h = mid - 1 continue
peak-index-in-a-mountain-array
Python3 | Easy Binary Search Solution
JOON1234
0
9
peak index in a mountain array
852
0.694
Medium
13,870
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2457993/Python-O(logn)-time-complexity-O(1)-space-complexity-example-with-drawing.
class Solution: def peakIndexInMountainArray(self, arr): l, r = 1, len(arr)-2 while l <= r: # O(log(n)) m = (l+r)//2 mid = arr[m] leftOfMid = arr[m-1] rightOfMid = arr[m+1] if mid > leftOfMid and mid > rightOfMid: return m elif mid < leftOfMid: r = m-1 else: l = m+1
peak-index-in-a-mountain-array
Python O(logn) time complexity, O(1) space complexity, example with drawing.
OsamaRakanAlMraikhat
0
29
peak index in a mountain array
852
0.694
Medium
13,871
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2350599/3-lines-of-code-(Easy-and-fastest-solution)
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: for i in range(len(arr)-1): if arr[i]>arr[i+1]: return i
peak-index-in-a-mountain-array
3 lines of code (Easy and fastest solution)
Sankalpa02
0
44
peak index in a mountain array
852
0.694
Medium
13,872
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2324333/CPP-or-Java-or-Python3-or-Binary-Search-Approach-only-or-O(log-n-)
class Solution: def peakIndexInMountainArray(self, nums: List[int]) -> int: start, end = 0, len(nums)-1 if(end == 0): return nums[0] else: while(start < end): mid = start + (end - start)//2 if nums[mid] < nums[mid + 1]: start = mid + 1 else: end = mid return start
peak-index-in-a-mountain-array
CPP | Java | Python3 | Binary Search Approach only | O(log n )
devilmind116
0
20
peak index in a mountain array
852
0.694
Medium
13,873
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2185107/Faster-than-90-python-one-liner
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
Faster than 90% python one-liner
pro6igy
0
27
peak index in a mountain array
852
0.694
Medium
13,874
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2150882/Python-solution-using-Binary-search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start=0 end=len(arr)-1 while(start!=end): mid=(start+end)//2 if arr[mid]>arr[mid+1]: end=mid elif arr[mid]<arr[mid+1]: start=mid+1 return start
peak-index-in-a-mountain-array
Python solution using Binary search
yashkumarjha
0
32
peak index in a mountain array
852
0.694
Medium
13,875
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2150833/Python-Solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: count = 0 for i in range(1,len(arr)): if(arr[i-1]<arr[i]): count+=1 else: count = count return count
peak-index-in-a-mountain-array
Python Solution
yashkumarjha
0
11
peak index in a mountain array
852
0.694
Medium
13,876
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2126700/Python-simple-solution
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
Python simple solution
StikS32
0
31
peak index in a mountain array
852
0.694
Medium
13,877
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2119616/Python-One-Liner-Using-max()
class Solution(object): def peakIndexInMountainArray(self, arr): return arr.index(max(arr))
peak-index-in-a-mountain-array
[Python] One Liner Using max()
NathanPaceydev
0
40
peak index in a mountain array
852
0.694
Medium
13,878
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2116904/Python-Easy-solution-with-complexity
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if (arr[mid] < arr[mid + 1]) and (arr[mid] > arr[mid + 1]): return mid elif arr[mid] < arr[mid + 1]: left = mid + 1 elif arr[mid] > arr[mid + 1]: right = mid -1 return left # space O(1) # time O(logn)
peak-index-in-a-mountain-array
[Python] Easy solution with complexity
mananiac
0
30
peak index in a mountain array
852
0.694
Medium
13,879
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2077291/C%2B%2BPython-solution-with-O(LogN)-Complexity
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start = 0 end = len(arr)-1 while(start<end): mid = start + (end-start)//2 if(arr[mid]<arr[mid+1]): start = mid+1 else: end = mid return start
peak-index-in-a-mountain-array
C++/Python solution with O(LogN) Complexity
arpit3043
0
93
peak index in a mountain array
852
0.694
Medium
13,880
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2061129/Python-easy-to-read-and-understand-or-binary-search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: start, end = 0, len(arr)-1 while start <= end: mid = (start+end) // 2 print(mid) if arr[mid-1] < arr[mid] and arr[mid] > arr[mid+1]: return mid elif arr[mid-1] < arr[mid] < arr[mid+1]: start = mid+1 else: end = mid
peak-index-in-a-mountain-array
Python easy to read and understand | binary-search
sanial2001
0
43
peak index in a mountain array
852
0.694
Medium
13,881
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2031807/Basic-easy-solution-using-max-and-index
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: val = max(arr) return arr.index(val)
peak-index-in-a-mountain-array
Basic easy solution using max and index
andrewnerdimo
0
11
peak index in a mountain array
852
0.694
Medium
13,882
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2022160/Python-One-Liners-(x2)-O(n)-and-O(log-n)-Clean-and-Simple!
class Solution: def peakIndexInMountainArray(self, arr): return arr.index(max(arr))
peak-index-in-a-mountain-array
Python - One Liners (x2) - O(n) and O(log n) - Clean and Simple!
domthedeveloper
0
30
peak index in a mountain array
852
0.694
Medium
13,883
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2022160/Python-One-Liners-(x2)-O(n)-and-O(log-n)-Clean-and-Simple!
class Solution: def peakIndexInMountainArray(self, arr): return bisect.bisect_left(range(len(arr)), True, key=lambda i: arr[i] > arr[i + 1])
peak-index-in-a-mountain-array
Python - One Liners (x2) - O(n) and O(log n) - Clean and Simple!
domthedeveloper
0
30
peak index in a mountain array
852
0.694
Medium
13,884
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1991763/Python-Easy-Binary-Search-O(log-n)
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: left, right = 0, len(arr) - 1 while left <= right: pivot = (left + right) // 2 if((arr[pivot + 1] < arr[pivot]) and (arr[pivot - 1] < arr[pivot])): return pivot elif(arr[pivot + 1] > arr[pivot]): left = pivot + 1 else: right = pivot - 1
peak-index-in-a-mountain-array
[Python] Easy Binary Search O(log n)
ksinar
0
37
peak index in a mountain array
852
0.694
Medium
13,885
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1985081/Simple-solution-python3
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: l = 1; r = len(arr)-1 while(l<=r): mid = l + (r-l)//2 if arr[mid -1] < arr[mid] > arr[mid +1]: return mid elif arr[mid -1] < arr[mid]: l = mid + 1 else: r = mid - 1 return l
peak-index-in-a-mountain-array
Simple solution python3
tauilabdelilah97
0
10
peak index in a mountain array
852
0.694
Medium
13,886
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1891590/Python-easy-solution-for-beginners
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: for i in range(0, len(arr)-2): if arr[i+1] > arr[i] and arr[i+1] > arr[i+2]: return i + 1
peak-index-in-a-mountain-array
Python easy solution for beginners
alishak1999
0
31
peak index in a mountain array
852
0.694
Medium
13,887
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1836544/1-Line-Python-Solution-oror-65-Faster-oror-Memory-less-than-75
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: return arr.index(max(arr))
peak-index-in-a-mountain-array
1-Line Python Solution || 65% Faster || Memory less than 75%
Taha-C
0
32
peak index in a mountain array
852
0.694
Medium
13,888
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1834768/Python-Easiest-Solutions-With-Explanation-O(log-n)or-Beg-to-Adv-or-Binary-Search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: max_elem = max(arr) return arr.index(max_elem)
peak-index-in-a-mountain-array
Python Easiest Solutions With Explanation O(log n)| Beg to Adv | Binary Search
rlakshay14
0
63
peak index in a mountain array
852
0.694
Medium
13,889
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1834768/Python-Easiest-Solutions-With-Explanation-O(log-n)or-Beg-to-Adv-or-Binary-Search
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: left = 0 right = len(arr) - 1 while left <= right: mid = (right + left) // 2 if (arr[mid-1] < arr[mid]) and (arr[mid] > arr[mid+1]): # in this way, mid is the peak of the mountain return mid elif arr[mid-1] < arr[mid] < arr[mid+1]: # if true, peak should be on the right hand side left = mid else: # if true, peak should be on the left hand side right = mid return -1
peak-index-in-a-mountain-array
Python Easiest Solutions With Explanation O(log n)| Beg to Adv | Binary Search
rlakshay14
0
63
peak index in a mountain array
852
0.694
Medium
13,890
https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/1833655/Python-3-(60ms)-or-8-Lines-Binary-Search-Approach-O(logn)-or-Easy-to-Understand
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: s,e=0,len(arr)-1 while s<e: m=s+(e-s)//2 if arr[m]<arr[m+1]: s=m+1 else: e=m return s
peak-index-in-a-mountain-array
Python 3 (60ms) | 8-Lines Binary Search Approach O(logn) | Easy to Understand
MrShobhit
0
40
peak index in a mountain array
852
0.694
Medium
13,891
https://leetcode.com/problems/car-fleet/discuss/939525/Python3-greedy-O(NlogN)
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: ans = prev = 0 for pp, ss in sorted(zip(position, speed), reverse=True): tt = (target - pp)/ss # time to arrive at target if prev < tt: ans += 1 prev = tt return ans
car-fleet
[Python3] greedy O(NlogN)
ye15
17
1,200
car fleet
853
0.501
Medium
13,892
https://leetcode.com/problems/car-fleet/discuss/1537985/Python3-Increasing-stack
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: """ sort the start position. the car behind can only catch up no exceed. so if the car start late and speed is faster, it will catch up the car ahead of itself and they become a fleet. there is a target(or desitination),so use arrive time to measure. start late but arrive ealier means the car is behind and will catch up before arriving the destination. position 10 8 5 3 0 distance 2 4 7 9 12 speed. 2 4 1 3 1 time. 1 1 7 3 12 ^ ^ | | catch catch up the previous car before target, join the fleet stack = [1] , [1],[1,7],[1,7][1,7,12] """ stack = [] for pos, v in sorted(zip(position, speed),reverse = True): dist = target - pos time = dist / v if not stack: stack.append(time) elif time > stack[-1]: stack.append(time) return len(stack)
car-fleet
[Python3] Increasing stack
zhanweiting
12
700
car fleet
853
0.501
Medium
13,893
https://leetcode.com/problems/car-fleet/discuss/1429879/Python3-Intuitive-solution-with-sorting-with-comments
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: # Init fleets = 0 fleet_time = float("-inf") # Cars which are ahead are checked first for pos, reach_time in sorted([(position[i], (target-position[i])/speed[i]) for i in range(len(position))], reverse=True): # If no collision, consider it a fleet. Read the comments. # If a car has higher reach time then the current fleet, that car # will never reach the fleet. So increment the no of fleets # and change fleet time to the time of the current car. As # there is no other car between the fleet and the current car. # If a car has lower reach time than the current fleet, that # car will collied with the fleet and hence no need to increment # the no of fleet as fleet time will remain the same. # Remember the fleet time is decided by the first car of the fleet. if reach_time > fleet_time: fleet_time = reach_time fleets += 1 return fleets
car-fleet
[Python3] Intuitive solution with sorting with comments
ssshukla26
3
446
car fleet
853
0.501
Medium
13,894
https://leetcode.com/problems/car-fleet/discuss/1429879/Python3-Intuitive-solution-with-sorting-with-comments
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: # Sort in reverse order of the car w.r.t position ps = sorted(list(zip(position, speed)), key = lambda x: x[0], reverse=True) # Find timestamp of each car reaching the target ts = [(target-p)/s for p, s in ps] # Main logic stack = [] for t in ts: # Add to stack if stack is empty, or # the car ahead of the current car has # already reach the target if not stack or stack[-1] < t: stack.append(t) # return total no. of fleets return len(stack)
car-fleet
[Python3] Intuitive solution with sorting with comments
ssshukla26
3
446
car fleet
853
0.501
Medium
13,895
https://leetcode.com/problems/car-fleet/discuss/679156/Python3-sort-time-by-position-then-find-the-length-of-the-ever-increasing-sequence-Car-Fleet
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: time = [((target - p)/s, p) for p, s in zip(position, speed)] time.sort(key=lambda x:-x[1]) ans = prev = 0 for t, _ in time: if t > prev: prev = t ans += 1 return ans
car-fleet
Python3 sort time by position then find the length of the ever increasing sequence - Car Fleet
r0bertz
3
378
car fleet
853
0.501
Medium
13,896
https://leetcode.com/problems/car-fleet/discuss/1629048/Well-Explained-and-Coded-oror-95-faster-oror-For-Beginners
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: n = len(position) time = [0]*n for i in range(n): time[i] = (target-position[i])/speed[i] local = [] for p,t in zip(position,time): local.append([p,t]) local.sort() res = 1 ma = local[n-1][1] for i in range(n-2,-1,-1): if local[i][1]>ma: ma = local[i][1] res+=1 return res
car-fleet
📌📌 Well-Explained & Coded || 95% faster || For Beginners 🐍
abhi9Rai
2
208
car fleet
853
0.501
Medium
13,897
https://leetcode.com/problems/car-fleet/discuss/1423765/python3-solution
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: n=len(position) zipped_lists = zip(position, speed) sorted_pairs = sorted(zipped_lists,reverse=True) prev=ans=0 for position,speed in sorted_pairs: time_taken=(target-position)/speed if prev < time_taken: ans+=1 prev=time_taken return ans
car-fleet
python3 solution
minato_namikaze
2
231
car fleet
853
0.501
Medium
13,898
https://leetcode.com/problems/car-fleet/discuss/2424577/Python-Solution-Without-Stack
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: cars = sorted(zip(position, speed))[::-1] res = 1 slowest = cars[0] for car in cars[1:]: cPos, cSpeed = car sPos, sSpeed = slowest if ((target - sPos)/ sSpeed) < ((target - cPos)/ cSpeed): slowest = car res += 1 return res
car-fleet
Python Solution Without Stack
putu_gde
1
73
car fleet
853
0.501
Medium
13,899