post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1342438/Easy-Python-Solution-w-Comments
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = 0 #holds the current non repeating substring passed = [] for i in range(len(s)): if s[i] not in passed: passed.append(s[i]) max_len = max(len(passed), max_len) else: #if repeat found, update max_len with current substr in passed max_len = max(len(passed), max_len) #begin the next substr after the first char in s that is repeated passed = passed[passed.index(s[i])+1:] + [s[i]] return max_len
longest-substring-without-repeating-characters
Easy Python Solution w/ Comments
mguthrie45
4
413
longest substring without repeating characters
3
0.338
Medium
100
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2670619/Simple-python-code-with-explanation
class Solution: def lengthOfLongestSubstring(self, s): #create a variable and assign value 0 to it longest_substring = 0 #create a pointer l and assign 0 to it l = 0 #create a pointer r and assign 0 to it r = 0 #iterate over the elements in string(s) for i in range(len(s)): #if the length of string[l:r+1] is same as the length of set(s[l:r+1]) #that means the elements in substring are unique if len(s[l:r+1] ) == len(set(s[l:r+1])): #then change the longest_substring value as the maximum of r-l+1 and itself longest_substring = max(longest_substring,r-l + 1) #increse the r pointer by 1 r = r +1 #if the elements in substring are repeating else: #then increse the l pointer by 1 l = l + 1 #and increse r pointer value by 1 r = r + 1 #after iterating over the string #return the variable(longest_substring) return longest_substring
longest-substring-without-repeating-characters
Simple python code with explanation
thomanani
3
274
longest substring without repeating characters
3
0.338
Medium
101
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2670619/Simple-python-code-with-explanation
class Solution: #just used the iterator as r pointer def lengthOfLongestSubstring(self, s): summ = 0 l = 0 for r in range(len(s)): if len(s[l:r+1]) == len(set(s[l:r+1])): summ = max(summ,r-l+1) else: l = l + 1 return summ
longest-substring-without-repeating-characters
Simple python code with explanation
thomanani
3
274
longest substring without repeating characters
3
0.338
Medium
102
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2450783/Python3%3A-Sliding-window-O(N)-greater-Faster-than-99.7
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: seen = {} left = 0 output = 0 for right, char in enumerate(s): # If char not in seen dictionary, we can keep increasing the window size by moving right pointer if char not in seen: output = max(output, right - left + 1) # There are two cases if `char` in seen: # case 1: char is inside the current window, we move left pointer to seen[char] + 1. # case 2: char is not inside the current window, we can keep increase the window else: if seen[char] < left: output = max(output, right - left + 1) else: left = seen[char] + 1 seen[char] = right return output
longest-substring-without-repeating-characters
Python3: Sliding window O(N) => Faster than 99.7%
cquark
3
294
longest substring without repeating characters
3
0.338
Medium
103
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2423128/Faster-than-99.5-Python-Solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: substr = deque() index = set() max_len = 0 for char in s: if char not in index: substr.append(char) index.add(char) else: while substr: c = substr.popleft() index.remove(c) if c == char: substr.append(char) index.add(char) break if len(substr) > max_len: max_len = len(substr) return max_len
longest-substring-without-repeating-characters
Faster than 99.5% Python Solution
vyalovvldmr
3
332
longest substring without repeating characters
3
0.338
Medium
104
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2383487/Fastest-Solution-Explained0ms100-O(n)time-complexity-O(n)space-complexity
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: seen = {} l = 0 output = 0 for r in range(len(s)): """ If s[r] not in seen, we can keep increasing the window size by moving right pointer """ if s[r] not in seen: output = max(output,r-l+1) """ There are two cases if s[r] in seen: case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1. case2: s[r] is not inside the current window, we can keep increase the window """ else: if seen[s[r]] < l: output = max(output,r-l+1) else: l = seen[s[r]] + 1 seen[s[r]] = r return output
longest-substring-without-repeating-characters
[Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity
cucerdariancatalin
3
808
longest substring without repeating characters
3
0.338
Medium
105
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2377883/Python-Solution-or-Classic-Two-Pointer-Sliding-Window-Based
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: store = set() maxLen = 0 left = 0 for right in range(len(s)): # to skip consecutive repeating characters while s[right] in store: store.remove(s[left]) # lower window size left += 1 store.add(s[right]) maxLen = max(maxLen,right - left + 1) return maxLen
longest-substring-without-repeating-characters
Python Solution | Classic Two Pointer - Sliding Window Based
Gautam_ProMax
3
188
longest substring without repeating characters
3
0.338
Medium
106
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/673878/Simple-python
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: length, start = 0, 0 seen = {} for idx, c in enumerate(s): if c in seen and start <= seen[c]: start = seen[c] + 1 length = max(length, idx-start+1) seen[c] = idx return length
longest-substring-without-repeating-characters
Simple python
etherealoptimist
3
737
longest substring without repeating characters
3
0.338
Medium
107
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/266333/Python-Solution-faster-than-100.00-other-solutions
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s): result = [] temp = s[0] for i in s[1:]: if i not in temp: temp += i elif i == temp[0]: temp = temp[1:] + i elif i == temp[-1]: result.append(temp) temp = i else: result.append(temp) temp = temp[temp.find(i) + 1:] + i result.append(temp) return len(max(result, key=len)) return 0
longest-substring-without-repeating-characters
Python Solution faster than 100.00% other solutions
_l0_0l_
3
586
longest substring without repeating characters
3
0.338
Medium
108
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2778596/Python-3-O(n)-faster-than-99.94
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: seen = {} best = 0 front = -1 for i, c in enumerate(s): if c in seen and front < seen[c]: front = seen[c] seen[c] = i if (i - front) > best: best = i - front return best
longest-substring-without-repeating-characters
Python 3 O(n) faster than 99.94%
Zachii
2
756
longest substring without repeating characters
3
0.338
Medium
109
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2775814/Efficient-Python-solution-(SLIDING-WINDOW)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: length = 0 count = {} l = 0 for r in range(len(s)): count[s[r]] = count.get(s[r], 0)+1 while count[s[r]] > 1: count[s[l]] -= 1 l += 1 length = max(length, 1+r-l) return length
longest-substring-without-repeating-characters
Efficient Python solution (SLIDING WINDOW)
really_cool_person
2
1,100
longest substring without repeating characters
3
0.338
Medium
110
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2764542/Python-Simple-Python-Solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: m=0 for i in range(len(s)): l=[] c=0 for j in range(i,len(s)): if s[j] not in l: l.append(s[j]) c+=1 m=max(m,c) else: break return m
longest-substring-without-repeating-characters
[ Python ]๐Ÿ๐ŸSimple Python Solution โœ…โœ…
sourav638
2
18
longest substring without repeating characters
3
0.338
Medium
111
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2488819/Python-simple-solution.-O(n)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) == 0: return 0 global_max = 1 left = 0 used = {} for right in range(0,len(s)): if s[right] in used: left = max(left, used[s[right]]+1) used[s[right]] = right global_max = max(right-left+1, global_max) return global_max
longest-substring-without-repeating-characters
Python simple solution. O(n)
haruka980209
2
180
longest substring without repeating characters
3
0.338
Medium
112
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2403381/C%2B%2BPython-O(N)-Solution-with-better-and-faster-approach
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: start = maxLength = 0 usedChar = {} for i in range(len(s)): if s[i] in usedChar and start <= usedChar[s[i]]: start = usedChar[s[i]] + 1 else: maxLength = max(maxLength, i - start + 1) usedChar[s[i]] = i return maxLength
longest-substring-without-repeating-characters
C++/Python O(N) Solution with better and faster approach
arpit3043
2
422
longest substring without repeating characters
3
0.338
Medium
113
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2359311/Python-runtime-63.07-memory-49.48
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = 0 sub = set() start_delete_index = 0 for index, character in enumerate(s): while character in sub: sub.remove(s[start_delete_index]) start_delete_index += 1 sub.add(character) if len(sub) > max_len: max_len = len(sub) return max_len
longest-substring-without-repeating-characters
Python, runtime 63.07%, memory 49.48%
tsai00150
2
190
longest substring without repeating characters
3
0.338
Medium
114
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2359311/Python-runtime-63.07-memory-49.48
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = start = 0 seen = {} for index, character in enumerate(s): if character in seen and start <= seen[character]: start = seen[character] + 1 seen[character] = index max_len = max(max_len, index-start+1) return max_len
longest-substring-without-repeating-characters
Python, runtime 63.07%, memory 49.48%
tsai00150
2
190
longest substring without repeating characters
3
0.338
Medium
115
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2233725/Simple-python-solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: mapping = {} output = 0 start = 0 for char in range(len(s)): if s[char] in mapping: start = max(mapping[s[char]] + 1,start) mapping[s[char]] = char output = max(output, char - start + 1) return output
longest-substring-without-repeating-characters
Simple python solution
asaffari101
2
182
longest substring without repeating characters
3
0.338
Medium
116
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2119781/Python-or-Easy-Solution-using-hashset
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: res = 0 charSet = set() l = 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res,r-l+1) return res
longest-substring-without-repeating-characters
Python | Easy Solution using hashset
__Asrar
2
272
longest substring without repeating characters
3
0.338
Medium
117
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2078071/Python3-sliding-window-solution-in-O(n)-77ms-14MB
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: chars = set() l = r = 0 top = 0 while r < len(s): while s[r] in chars: chars.remove(s[l]) l += 1 chars.add(s[r]) top = max(top, len(chars)) r += 1 # top = max(top, len(chars)) return top
longest-substring-without-repeating-characters
Python3 sliding window solution in O(n) 77ms 14MB
GeorgeD8
2
190
longest substring without repeating characters
3
0.338
Medium
118
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1889624/Simple-python3-solution-oror-two-pointer
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: i=0 j=i+1 max_len = 0 temp = [] while(i<len(s)): temp.append(s[i]) while(j<len(s) and s[j] not in temp): temp.append(s[j]) j+=1 if max_len<len(temp): max_len = len(temp) temp=[] i+=1 j=i+1 return max_len
longest-substring-without-repeating-characters
Simple python3 solution || two pointer
darshanraval194
2
348
longest substring without repeating characters
3
0.338
Medium
119
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1860113/Clean-Python-3-solution-(sliding-window-%2B-hash-map)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: dic = dict() max_len = 0 l = 0 r = 0 while l < len(s) and r < len(s): if s[r] not in dic: dic[s[r]] = True r += 1 max_len = max(max_len, r - l) else: dic.pop(s[l]) l += 1 return max_len
longest-substring-without-repeating-characters
Clean Python 3 solution (sliding window + hash map)
Hongbo-Miao
2
128
longest substring without repeating characters
3
0.338
Medium
120
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1829631/Python-or-Walkthrough-%2B-Complexity-or-Sliding-Window
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: def has_duplicates(start, end): seen = set() while start <= end: letter = s[start] if letter in seen: return True else: seen.add(letter) start += 1 return False n = len(s) longest = 0 for start in range(n): for end in range(start, n): if not has_duplicates(start, end): longest = max(longest, end - start + 1) return longest
longest-substring-without-repeating-characters
Python | Walkthrough + Complexity | Sliding Window
leetbeet73
2
520
longest substring without repeating characters
3
0.338
Medium
121
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1829631/Python-or-Walkthrough-%2B-Complexity-or-Sliding-Window
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: start = longest = 0 seen = {} for end in range(len(s)): letter = s[end] if letter in seen: start = max(seen[letter] + 1, start) longest = max(longest, end - start + 1) seen[letter] = end return longest
longest-substring-without-repeating-characters
Python | Walkthrough + Complexity | Sliding Window
leetbeet73
2
520
longest substring without repeating characters
3
0.338
Medium
122
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1077043/Python3-O(1)-space!
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) == 1: return 1 long = 0 l = 0 r = 1 while r < len(s): if s[r] not in s[l:r]: r += 1 long = max(long, len(s[l:r])) else: while s[r] in s[l:r]: l += 1 return long
longest-substring-without-repeating-characters
Python3 O(1) space!
BeetCoder
2
253
longest substring without repeating characters
3
0.338
Medium
123
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/905320/Python-3-solution-or-Memory-Usage%3A-14.3-MB-less-than-100.00-of-Python3-online-submissions.
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: maxlength = 0 startIndex = 0 i = 0 letters = [] while i < len(s): if s[i] not in letters: letters.append(s[i]) i = i + 1 else: maxlength = max(len(letters), maxlength) startIndex = startIndex + 1 i = startIndex letters.clear() return max(len(letters), maxlength)
longest-substring-without-repeating-characters
Python 3 solution | Memory Usage: 14.3 MB, less than 100.00% of Python3 online submissions.
manojkumarmanusai
2
358
longest substring without repeating characters
3
0.338
Medium
124
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/468273/Easy-to-follow-Python3-solution-(faster-than-99-and-memory-usage-less-than-100)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: b = '' l = '' for c in s: if c in b: i = b.index(c) b = b[i+1:] + c else: b += c if len(b) > len(l): l = b return len(l)
longest-substring-without-repeating-characters
Easy-to-follow Python3 solution (faster than 99% & memory usage less than 100%)
gizmoy
2
391
longest substring without repeating characters
3
0.338
Medium
125
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2619481/Simple-python3-solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: charSet = set() l = 0 res = 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res, r - l + 1) return res
longest-substring-without-repeating-characters
Simple python3 solution
__Simamina__
1
174
longest substring without repeating characters
3
0.338
Medium
126
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2591490/Python-solution-with-comments
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: seen = {} #Hashmap to keep track of where we last saw a given character res = 0 #Initial longest substring start = 0 #Window starting point for end,char in enumerate(s): if char in seen and start <= seen[char]: #If we've seen this character before and the start position is before or equal #to the current character then we must move the window starting point #since no duplicates allowed start = seen[char] + 1 else: #Otherwise #Compute the size of the current window and update the result res = max(res,end - start + 1) #Always update the current position for any given character seen[char] = end return res
longest-substring-without-repeating-characters
Python solution with comments
harrisonhcue
1
124
longest substring without repeating characters
3
0.338
Medium
127
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2511175/simple-Python3-solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: charSet = set() l = 0 res = 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res, r - l + 1) return res
longest-substring-without-repeating-characters
simple Python3 solution
__Simamina__
1
163
longest substring without repeating characters
3
0.338
Medium
128
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2445855/Python3-or-2-Different-Solutions-or-Optimal-Solution
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: # Method 1: Naive Inefficient Approach l = 0 r = 0 ans = 0 maxans = 0 count = [] while r<=len(s)-1: if s[r] not in count: count.append(s[r]) ans += 1 r += 1 else: count.clear() ans = 0 l += 1 r = l maxans = max(maxans,ans) return maxans # Method 2: T.C: O(n) S.C: O(n) count = set() l = 0 maxcount = 0 for r in range(len(s)): while s[r] in count: count.remove(s[l]) l+=1 count.add(s[r]) maxcount = max(maxcount,len(count)) return maxcount # Search with tag chawlashivansh for my solutions
longest-substring-without-repeating-characters
Python3 | 2 Different Solutions | Optimal Solution
chawlashivansh
1
187
longest substring without repeating characters
3
0.338
Medium
129
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2306073/Python-Two-Clean-Sliding-Window-Solutions
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: maxLength = left = 0 seen = {} for i in range(len(s)): # If letter is already seen, move left window by 1 to the right until letter is no longer in dictionary while s[i] in seen: seen[s[left]] -= 1 if seen[s[left]] == 0: del seen[s[left]] left += 1 # Add letter seen[s[i]] = 1 maxLength = max(maxLength, i - left + 1) return maxLength
longest-substring-without-repeating-characters
Python - Two Clean Sliding Window Solutions
Reinuity
1
141
longest substring without repeating characters
3
0.338
Medium
130
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2306073/Python-Two-Clean-Sliding-Window-Solutions
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: maxLength = left = 0 seen = {} for i in range(len(s)): #If letter is already seen if s[i] in seen: # Set left window to the max between its current index, or the index of the last occurance of the current letter + 1 left = max(left, seen[s[i]] + 1) # Save the index seen[s[i]] = i maxLength = max(maxLength, i - left + 1) return maxLength
longest-substring-without-repeating-characters
Python - Two Clean Sliding Window Solutions
Reinuity
1
141
longest substring without repeating characters
3
0.338
Medium
131
https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/2188837/Sliding-Window-Solution-oror-Implementation-of-Approach-by-Aditya-Verma
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: i, j = 0, 0 n = len(s) frequencyArray = [0]*(5 * 10**4) maxSize = 0 while j < n: frequencyArray[ord(s[j]) - ord('a')] += 1 mapSize = (5*10**4) - frequencyArray.count(0) if mapSize == j - i + 1: maxSize = max(maxSize, j - i + 1) j += 1 elif mapSize < j - i + 1: while mapSize < j - i + 1: frequencyArray[ord(s[i]) - ord('a')] -= 1 mapSize = (5*10**4) - frequencyArray.count(0) i += 1 j += 1 return maxSize
longest-substring-without-repeating-characters
Sliding Window Solution || Implementation of Approach by Aditya Verma
Vaibhav7860
1
151
longest substring without repeating characters
3
0.338
Medium
132
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/949705/Python3-two-pointer-greater9621-runtime-commented
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # Get the lengths of both lists l1,l2 = len(nums1), len(nums2) # Determine the middle middle = (l1 + l2) / 2 # EDGE CASE: # If we only have 1 value (e.g. [1], []), return nums1[0] if the length of # that list is greater than the length of l2, otherwise return nums2[1] if middle == 0.5: return float(nums1[0]) if l1 > l2 else float(nums2[0]) # Initialize 2 pointers x = y = 0 # Initialize 2 values to store the previous and current value (in case of an even # amount of values, we need to average 2 values) cur = prev = 0 # Determine the amount of loops we need. If the middle is even, loop that amount + 1: # eg: [1, 2, 3, 4, 5, 6] 6 values, middle = 3, loops = 3+1 # ^ ^ # | +-- cur # +----- prev # If the middle is odd, loop that amount + 0.5 # eg: [1, 2, 3, 4, 5] 5 values, middle = 2.5, loops = 2.5+0.5 # ^ # +--- cur loops = middle+1 if middle % 1 == 0 else middle+0.5 # Walk forward the amount of loops for _ in range(int(loops)): # Store the value of cur in prev prev = cur # If the x pointer is equal to the amount of elements of nums1 (l1 == len(nums1)) if x == l1: # Store nums2[y] in cur, 'cause we hit the end of nums1 cur = nums2[y] # Move the y pointer one ahead y += 1 # If the y pointer is equal to the amount of elements of nums2 (l2 == len(nums2)) elif y == l2: # Store nums1[x] in cur, 'cause we hit the end of nums2 cur = nums1[x] # Move the x pointer one ahead x += 1 # If the value in nums1 is bigger than the value in nums2 elif nums1[x] > nums2[y]: # Store nums2[y] in cur, because it's the lowest value cur = nums2[y] # Move the y pointer one ahead y += 1 # If the value in nums2 is bigger than the value in nums1 else: # Store nums1[x] in, because it's the lowest value cur = nums1[x] # Move the x pointer one ahead x += 1 # If middle is even if middle % 1 == 0.0: # Return the average of the cur + prev values (which will return a float) return (cur+prev)/2 # If middle is odd else: # Return the cur value, as a float return float(cur)
median-of-two-sorted-arrays
Python3 two pointer >96,21% runtime [commented]
tomhagen
32
5,100
median of two sorted arrays
4
0.353
Hard
133
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1592457/Python-O(m-%2B-n)-time-O(1)-space
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) mid = (m + n) // 2 + 1 prev2 = prev1 = None i = j = 0 for _ in range(mid): prev2 = prev1 if j == n or (i != m and nums1[i] <= nums2[j]): prev1 = nums1[i] i += 1 else: prev1 = nums2[j] j += 1 return prev1 if (m + n) % 2 else (prev1 + prev2) / 2
median-of-two-sorted-arrays
Python O(m + n) time, O(1) space
dereky4
21
2,100
median of two sorted arrays
4
0.353
Hard
134
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1174195/C%2B%2BPython-O(log(m%2Bn))-solution
class Solution: def findkth(self, a: List[int], b: List[int], target) -> int: # print("a: {}, b:{}".format(a, b)) n, m = len(a), len(b) if n <= 0: return b[target - 1] if m <= 0: return a[target - 1] med_a, med_b = n // 2 + 1, m // 2 + 1 ma, mb = a[n // 2], b[m // 2] if med_a + med_b > target: if ma > mb: return self.findkth(a[:med_a - 1], b, target) else: return self.findkth(a, b[:med_b - 1], target) else: if ma > mb: return self.findkth(a, b[med_b:], target - med_b) else: return self.findkth(a[med_a:], b, target - med_a) def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n, m = len(nums1), len(nums2) if n == 0 : if m % 2 == 0: return (nums2[m // 2 - 1] + nums2[m // 2]) / 2 else: return nums2[m // 2] if m == 0 : if n % 2 == 0: return (nums1[n // 2 - 1] + nums1[n // 2]) / 2 else: return nums1[n // 2] if (m + n) % 2 == 0: return (self.findkth(nums1, nums2, (m + n) // 2) + self.findkth(nums1, nums2, (m + n) // 2 + 1)) / 2 return self.findkth(nums1, nums2, (m + n) // 2 + 1)
median-of-two-sorted-arrays
C++/Python O(log(m+n)) solution
m0biu5
21
4,800
median of two sorted arrays
4
0.353
Hard
135
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1309837/Elegant-Python-Binary-Search-or-O(log(min(mn)))-O(1)
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: if len(nums2) < len(nums1): nums1, nums2 = nums2, nums1 m, n = len(nums1), len(nums2) left, right = 0, m-1 while True: pointer1 = left + (right-left) // 2 pointer2 = (m+n)//2 - pointer1 - 2 left1 = nums1[pointer1] if pointer1 in range(m) else -math.inf left2 = nums2[pointer2] if pointer2 in range(n) else -math.inf right1 = nums1[pointer1+1] if pointer1+1 in range(m) else math.inf right2 = nums2[pointer2+1] if pointer2+1 in range(n) else math.inf if left1 <= right2 and left2 <= right1: if (m+n) % 2 == 0: return (max(left1, left2) + min(right1, right2)) / 2 else: return min(right1, right2) elif left1 > right2: right = pointer1 - 1 else: left = pointer1 + 1
median-of-two-sorted-arrays
Elegant Python Binary Search | O(log(min(m,n))), O(1)
soma28
10
2,100
median of two sorted arrays
4
0.353
Hard
136
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1067613/Python-O(log(m%2Bn))-with-explanation-and-comments
class Solution: def findMedianSortedArrays(self, nums1, nums2) -> float: # odd length -> e.g. length 5, left(2) and right(2) would be the same index # even length -> e.g. length 6, left(2) and right(3) would be different indices m, n = len(nums1), len(nums2) left, right = (m+n-1)//2, (m+n)//2 return (self.getKth(nums1, nums2, left) + self.getKth(nums1, nums2, right))/2 def getKth(self, nums1, nums2, k): # if one list is exhausted, return the kth index of the other list if nums1 == []: return nums2[k] if nums2 == []: return nums1[k] # base case # k is 0-based, so finding the kth index equals eliminating k length elements. # k == 0 means we have eliminated all smaller indices, return the next highest number, which would be the median # e.g. to find the third index (k = 3), we eliminate 3 smaller elements (index 0, 1, 2) if k == 0: return min(nums1[0], nums2[0]) # find the subarray to be eliminated this iteration m, n = len(nums1), len(nums2) eliminated_length = min(m,n,(k+1)//2) # 1-based so k + 1 eliminated_index = eliminated_length - 1 # 0-based so - 1 if nums1[eliminated_index] <= nums2[eliminated_index]: nums1 = nums1[eliminated_index+1:] else: nums2 = nums2[eliminated_index+1:] # update k, the number of elements to be eliminated next round k -= eliminated_length return self.getKth(nums1, nums2, k)
median-of-two-sorted-arrays
Python O(log(m+n)) with explanation and comments
killerf1
8
1,400
median of two sorted arrays
4
0.353
Hard
137
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2672475/Python-O(-Log(-Min(m-n)-)-)-Solution-with-full-working-explanation
class Solution: # Time: O(log(min(m, n))) and Space: O(n) def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A, B = nums1, nums2 total = len(nums1) + len(nums2) half = total // 2 if len(A) > len(B): # for our solution we are assuming that B will be bigger than A, if it's not given than make it A, B = B, A l, r = 0, len(A) - 1 # we also assume that A is exactly half of B while True: # when any return statement is executed it will stop i = (l + r) // 2 # A[mid] # B[mid] = total//2(divide by 2 will get us mid B ) - A[mid](if we sub A from total, B's left) - # 2(to make it align with starting index 0 of A &amp; B, else it will go out of bounds) j = half - i - 2 Aleft = A[i] if i >= 0 else float("-infinity") # if index i is in negative than assign -infinity to Aleft Aright = A[i + 1] if (i + 1) < len(A) else float("infinity") # if index i+1 is greater than the size of A assign infinity to Aright Bleft = B[j] if j >= 0 else float("-infinity") # if index j is in negative than assign -infinity to Bleft Bright = B[j + 1] if (j + 1) < len(B) else float("infinity") # if index j+1 is greater than the size of B assign infinity to Bright # A = [1, 2, 3(left), 4(right), 5] and B = [1, 2, 3(left), 4(right), 5, 6, 7, 8] # B = 6 - 2 - 2 = 2(i.e 0,1,2) if Aleft <= Bright and Bleft <= Aright: # 3 <= 4 and 3 <= 4 if total % 2: # odd: min(4, 4) return min(Aright, Bright) return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 # even: max(3, 3) + min(4, 4) / 2 elif Aleft > Bright: # A = [1, 2, 3(left), 4(right), 5, 6] and B = [1, 2(left), 3(right), 4, 5] r = i - 1 # r = 3 - 1 = 2(i.e. index 0,1,2) --> A = [1, 2(L), 3(R), 4, 5, 6] and B = [1, 2, 3(L), 4(R), 5, 6] else: # when Bleft > Aright, we will increase l so L becomes R, and R pointer is shifted to R+1 index l = i + 1
median-of-two-sorted-arrays
Python O( Log( Min(m, n) ) ) Solution with full working explanation
DanishKhanbx
7
3,300
median of two sorted arrays
4
0.353
Hard
138
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2672475/Python-O(-Log(-Min(m-n)-)-)-Solution-with-full-working-explanation
class Solution: # Time: O(NLogN) and Space: O(1) def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1 = nums1 + nums2 nums1 = sorted(nums1) n = len(nums1) if n % 2 == 0: return (nums1[n//2 - 1] + nums1[(n//2)])/2 else: n = math.ceil(n/2) return nums1[n-1]
median-of-two-sorted-arrays
Python O( Log( Min(m, n) ) ) Solution with full working explanation
DanishKhanbx
7
3,300
median of two sorted arrays
4
0.353
Hard
139
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/697669/Python-or-simple-or-BInary-search-or-O(log(min(mn)))
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1_len = len(nums1) nums2_len = len(nums2) if (nums1_len > nums2_len): return self.findMedianSortedArrays(nums2,nums1) low = 0 high = nums1_len while(low<=high): partition_nums1 = (low+high)//2 partition_nums2 = (nums1_len+nums2_len+1)//2 - partition_nums1 max_left_x = nums1[partition_nums1-1] if partition_nums1 else -float('inf') min_right_x = nums1[partition_nums1] if partition_nums1 < nums1_len else float('inf') max_left_y = nums2[partition_nums2-1] if partition_nums2 else -float('inf') min_right_y = nums2[partition_nums2] if partition_nums2 < nums2_len else float('inf') if (max_left_x<=min_right_y and max_left_y <= min_right_x): if (nums1_len+nums2_len)%2 == 0: return (max(max_left_x,max_left_y)+min(min_right_x,min_right_y))/2 else: return max(max_left_x,max_left_y) elif(max_left_x>min_right_y): high = partition_nums1-1 else: low = partition_nums1+1
median-of-two-sorted-arrays
Python | simple | BInary search | O(log(min(m,n)))
ekantbajaj
7
1,800
median of two sorted arrays
4
0.353
Hard
140
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2799909/Python-or-Easy-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: final = [] i = 0 j = 0 while i<len(nums1) and j<len(nums2): if nums1[i] <= nums2[j]: final.append(nums1[i]) i += 1 else: final.append(nums2[j]) j += 1 final = final + nums1[i:] + nums2[j:] size = len(final) return (final[size//2]) if size % 2 != 0 else (final[size//2 - 1] + final[(size//2)])/2
median-of-two-sorted-arrays
Python | Easy Solutionโœ”
manayathgeorgejames
6
3,700
median of two sorted arrays
4
0.353
Hard
141
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2032243/Python-Tushar-Roy's-Solution-9463
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: if len(nums1) > len(nums2): return self.findMedianSortedArrays(nums2, nums1) all_len = len(nums1) + len(nums2) left_size = (all_len + 1) // 2 lo, hi = 0, len(nums1) - 1 while True: med1 = (lo + hi) // 2 med2 = left_size - 1 - (med1 + 1) left1 = -float('inf') if med1 < 0 else nums1[med1] right1 = float('inf') if med1 + 1 >= len(nums1) else nums1[med1 + 1] left2 = -float('inf') if med2 < 0 else nums2[med2] right2 = float('inf') if med2 + 1 >= len(nums2) else nums2[med2 + 1] if left1 > right2: hi = med1 if hi != 0 else med1 - 1 elif left2 > right1: lo = med1 + 1 else: break if all_len % 2 == 1: return max(left1, left2) else: return (max(left1, left2) + min(right1, right2)) / 2
median-of-two-sorted-arrays
โœ… Python, Tushar Roy's Solution, 94,63%
AntonBelski
5
666
median of two sorted arrays
4
0.353
Hard
142
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1874742/Python-O(log(m%2Bn))-Modifed-Binary-Search-w-Comments
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # Initialize total length of array len(A) + len(B), and rounded down half = total // 2 # We will assume A is smaller array of two(swap A and B if needed) # Binary search array A, find its middle i # Then the middle of B is j = half - i because half is supposed to be the length of left partition in global scale # But we are not sure if this is valid partition where all left partition values are smaller than right partitions # So we cross check the end of A's left partition(Aleft) and the start of B's right partition(Bright), and vice versa for B and A # If we confirm they are in ascending order, we have a valid partition so we just need to compute median # If they are not in ascending order, fix partitions to make it correct # Fixing A will result in B being fixed automatically A, B = nums1, nums2 total = len(nums1) + len(nums2) half = total // 2 # make sure A is always smaller array if len(B) < len(A): A, B = B, A l = 0 r = len(A) - 1 while True: # no condition because there is guaranteed to be a median so we can just return right away i = l + (r - l) // 2 #Middle of A j = half - i - 2 #Middle of B # we subtract by 2 because array index starts at 0. j starts and 0 and i starts at 0 so take those into account # Aleft is the end of left partition(= middle, i) # Aright is the beginning of right partition(= adjacent to middle, i+1) # Vice versa for B Aleft = A[i] if i >= 0 else float('-inf') # Is i out of bound? If yes, give it default value of -infinity Aright = A[i+1] if (i+1) < len(A) else float('inf') # likewise for right boundary Bleft = B[j] if j >= 0 else float('-inf') Bright = B[j+1] if (j+1) < len(B) else float('inf') # This infinity arrangement for out of bound is useful for when we check valid partition in next step # If end of A's left partition is smaller than right partition B's start, and vice versa for B and A, we have a valid partition # so then we compute result and return it if Aleft <= Bright and Bleft <= Aright: # if we have odd length of array if total % 2 != 0: return min(Aright, Bright) # median is the beginning of right partition and it will be min value between Aright and Bright # even length of array # median is the mean of two values adjacent to mid, which are end of left partition and beginning of right partition return (max(Aleft, Bleft) + min(Aright, Bright))/2 # If end A's left partition is larger than B's start of right partition, we need to fix partitions. # Since arrays are in ascending order, shifting r will result in smaller A's left partition, which leads to smaller Aleft elif Aleft > Bright: r = i-1 # Or we could have too small A, in which case we increase A's size by shifting l else: l = i+1
median-of-two-sorted-arrays
Python O(log(m+n)) Modifed Binary Search w/ Comments
hermit1007
4
621
median of two sorted arrays
4
0.353
Hard
143
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1522910/Python%3A-O(log(m%2Bn))-solution-with-diagram-explanation
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m,n=len(nums1),len(nums2) k=ceil((m+n)/2) lo=max(0,k-n) hi=min(k,m) def calculateBorder(k,x): m_k=nums1[x] if x<m else math.inf n_k=nums2[k-x] if k-x<n else math.inf m_k_1=nums1[x-1] if x>0 else -math.inf n_k_1=nums2[k-x-1] if k-x>0 else -math.inf return m_k,n_k,m_k_1,n_k_1 while lo<hi: x=(lo+hi)//2 m_k,n_k,m_k_1,n_k_1=calculateBorder(k,x) if m_k_1>n_k: hi=x elif n_k_1>m_k: lo=x+1 else: return max(m_k_1,n_k_1) if (m+n)%2 else (max(m_k_1,n_k_1)+min(m_k,n_k))/2 m_k,n_k,m_k_1,n_k_1=calculateBorder(k,lo) return max(m_k_1,n_k_1) if (m+n)%2 else (max(m_k_1,n_k_1)+min(m_k,n_k))/2
median-of-two-sorted-arrays
Python: O(log(m+n)) solution with diagram explanation
SeraphNiu
4
1,200
median of two sorted arrays
4
0.353
Hard
144
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2779958/Python-Simple-Python-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: num=sorted(nums1+nums2) if len(num)%2==0: return (num[(len(num)//2)-1] + num[(len(num)//2)])/2 else: return (num[(len(num)//2)]*2)/2
median-of-two-sorted-arrays
[ Python ] ๐Ÿ๐Ÿ Simple Python Solution โœ…โœ…
sourav638
2
96
median of two sorted arrays
4
0.353
Hard
145
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2444913/median-of-two-sorted-arrays-simple-understandable-python3-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1.extend(nums2) nums1.sort() l = len(nums1) mid1 = l // 2 if l % 2 == 1: return nums1[mid1] else: mid2 = (l // 2) - 1 return (nums1[mid1] + nums1[mid2])/2
median-of-two-sorted-arrays
median of two sorted arrays - simple understandable python3 solution
whammie
2
555
median of two sorted arrays
4
0.353
Hard
146
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2361650/Easy-solution-using-Python-or-76ms
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: list1=nums1+nums2 list1.sort() length=len(list1) if length%2==1: return float(list1[((length+1)//2)-1]) else: return (list1[length//2-1]+list1[(length//2)])/2
median-of-two-sorted-arrays
Easy solution using Python | 76ms
Hardik-26
2
240
median of two sorted arrays
4
0.353
Hard
147
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2361650/Easy-solution-using-Python-or-76ms
class Solution(object): def findMedianSortedArrays(self, nums1, nums2): list1=nums1+nums2 list1.sort() length=len(list1) if length%2==1: return float(list1[((length+1)//2)-1]) else: return float(list1[length//2-1]+list1[(length//2)])/2
median-of-two-sorted-arrays
Easy solution using Python | 76ms
Hardik-26
2
240
median of two sorted arrays
4
0.353
Hard
148
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2267528/FASTEST-PYTHON-3-LINE-SOLUTION
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1[0:0]=nums2 nums1.sort() return float(nums1[len(nums1)//2]) if len(nums1)%2==1 else (nums1[len(nums1)//2]+nums1[(len(nums1)//2)-1])/2
median-of-two-sorted-arrays
FASTEST PYTHON 3 LINE SOLUTION
afz123
2
484
median of two sorted arrays
4
0.353
Hard
149
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1970305/Python-optimal-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: #last index n=len(nums2) m=len(nums1) for i in range(n): nums1.append(0) lst=n+m-1 # merging from last index while m>0 and n>0: if nums1[m-1] > nums2[n-1]: nums1[lst]=nums1[m-1] m-=1 else: nums1[lst]=nums2[n-1] n-=1 lst-=1 # for remaining values in nums2 while n>0: nums1[lst]=nums2[n-1] n-=1 lst-=1 if len(nums1)%2!=0: return nums1[len(nums1)//2] else: return (nums1[len(nums1)//2]+nums1[(len(nums1)//2)-1])/2
median-of-two-sorted-arrays
Python optimal solution
saty035
2
296
median of two sorted arrays
4
0.353
Hard
150
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1961779/Python-easy-to-read-and-understand
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) i, j = 0, 0 nums = [] while i < m and j < n: if nums1[i] < nums2[j]: nums.append(nums1[i]) i += 1 else: nums.append(nums2[j]) j += 1 while i < m: nums.append(nums1[i]) i += 1 while j < n: nums.append(nums2[j]) j += 1 l = len(nums) if l%2 == 0: return (nums[l//2] + nums[l//2-1]) / 2 else: return nums[l//2]
median-of-two-sorted-arrays
Python easy to read and understand
sanial2001
2
579
median of two sorted arrays
4
0.353
Hard
151
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1805841/Short-Simple-Solution
class Solution(): def findMedianSortedArrays(self, nums1, nums2): combined = nums1 + nums2 combined.sort() length = len(combined) if length % 2 == 0: length = (length / 2) - 1 median = (combined[int(length)] + combined[int(length + 1)]) / 2 else: length = ((length - 1) / 2) - 1 median = combined[int(length) + 1] return median
median-of-two-sorted-arrays
Short Simple Solution
blacksquid
2
478
median of two sorted arrays
4
0.353
Hard
152
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/714754/Python-O(log(m%2Bn))-Solution-with-comments
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: if len(nums1) > len(nums2): nums1,nums2 = nums2, nums1 #Shorter array is nums1 n1,n2 = len(nums1),len(nums2) leftHalf = (n1+n2+1)//2 #Now the minimum contribution nums1 can make to the merged array is 0 and the max contribution is n1(nums1's length) minContribution = 0 maxContribution = n1 #We are essentially finding the last element of the left half of the merged final array, because it is sufficient for finding the median. We do this using binary search. while minContribution <= maxContribution: #We are searching in the space [minContribution,maxContribution] for the number of elements nums1 will contribute to the left half of the merged array. Since we know the size of the left half of the merged array, we can calculate the number of elements nums2 will contribute. Thus, we can find the median. c1 = minContribution + (maxContribution-minContribution)//2 #Num of elements nums1 contributes c2 = leftHalf - c1#Num of elements nums2 contributes x,x2,y,y2 = None,None,None,None if c1>0 : x = nums1[c1-1] if c2>0 : y = nums2[c2-1] if c1<n1: x2 = nums1[c1] if c2<n2: y2 = nums2[c2] #This is the important part. If x > y2, it means that x will come after y2 in the final merged array. Hence, we need to decrease maxContribution by 1. if x and y2 and x>y2: maxContribution= c1-1 #Similarly, if y>x2, we need to increase num of elements nums2 contributes; hence, increase the number of elemenets nums1 contributes. elif y and x2 and y>x2: minContribution = c1+1 #This is the case which happens when we've found our answer else: #Here we find out the last element of the left half of the merged array. If x>y, it means that x will be the, median(since it will occur after y in the merged array). SImilar reasoning is applicable for the other case. leftHalfEnd = None if not x: leftHalfEnd = y elif not y or x>y: leftHalfEnd = x else: leftHalfEnd = y #Now if the total elements(n1+n2) is odd, we can simply return the leftHalfEnd if (n1+n2)%2: return leftHalfEnd #However, if it is even, we need to find the first element in the right half of the merged array and calculate their mean and return it. else: rightHalfFirst = None if not x2: rightHalfFirst = y2 elif not y2 or x2<y2: rightHalfFirst = x2 else: rightHalfFirst = y2 return (rightHalfFirst + leftHalfEnd)/2 return -1
median-of-two-sorted-arrays
[Python] O(log(m+n)) Solution with comments
spongeb0b
2
512
median of two sorted arrays
4
0.353
Hard
153
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/622231/python3-solution-77ms-beats-99
class Solution: def findMedianSortedArrays(self, A: List[int], B: List[int]) -> float: """ Brute Force --> O(m + n) """ # nums3 = sorted(nums1 + nums2) # print(nums3) # if len(nums3) % 2 == 0: # mid = len(nums3)//2 # mid1 = mid-1 # return (nums3[mid] + nums3[mid1])/2 # else: # mid = len(nums3)//2 # return nums3[mid] """ O(log(m + n)) """ def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A, B = nums1, nums2 total = len(A) + len(B) half = total // 2 if len(B) < len(A): A, B = B, A l, r = 0, len(A)-1 while True: i = (l + r) // 2 j = half - i - 2 Aleft = A[i] if i >= 0 else float("-inf") Aright = A[i+1] if (i+1) < len(A) else float("inf") Bleft = B[j] if j >= 0 else float("-inf") Bright = B[j+1] if (j+1) < len(B) else float("inf") if Aleft <= Bright and Bleft < Aright: if total % 2: return min(Aright, Bright) else: return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 elif Aleft > Bright: r = i-1 else: l = i+1
median-of-two-sorted-arrays
python3 solution - 77ms - beats 99%
ratikdubey
2
147
median of two sorted arrays
4
0.353
Hard
154
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2501326/Simple-Logical-Solution-in-Python
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums = nums1 + nums2 nums.sort() med = len(nums)/2 if med.is_integer(): med = int(med) return (nums[med]+nums[med-1])/2 return nums[int(med)]
median-of-two-sorted-arrays
Simple Logical Solution in Python
Real-Supreme
1
181
median of two sorted arrays
4
0.353
Hard
155
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2459620/Simple-python-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: num3=nums1+nums2 num3.sort() l=len(num3) if l%2==1: return num3[l//2] else: return(num3[l//2]+num3[l//2-1])/2
median-of-two-sorted-arrays
Simple python solution
ilancheran
1
234
median of two sorted arrays
4
0.353
Hard
156
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2418916/Simple-Solutionor-Very-Easy-to-Understand
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: for i in range(len(nums2)): nums1.append(nums2[i]) nums1.sort() # sort the merged array length = len(nums1) half = length//2 if(length%2 != 0): return nums1[half] # median is the middle number else: mean = (nums1[half] + nums1[half - 1])/2 # median is the avg. of 2 middle numbers return mean
median-of-two-sorted-arrays
Simple Solution| Very Easy to Understand
AngelaInfantaJerome
1
121
median of two sorted arrays
4
0.353
Hard
157
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2412098/Python-Short-Easy-and-Faster-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: arr = sorted(nums1 + nums2) mid = len(arr) // 2 if len(arr) % 2: return arr[mid] return (arr[mid-1] + arr[mid]) / 2.0
median-of-two-sorted-arrays
[Python] Short, Easy and Faster Solution
Buntynara
1
223
median of two sorted arrays
4
0.353
Hard
158
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2371583/Very-Easy-solution-with-python
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: mergedList = nums1 + nums2 mergedList.sort() midIndex = int(len(mergedList)/2) if len(mergedList) % 2 == 0: res = (mergedList[midIndex-1] + mergedList[midIndex]) / 2 return res else: res = merge ```dList[midIndex] return res
median-of-two-sorted-arrays
Very Easy solution with python
amr-khalil
1
177
median of two sorted arrays
4
0.353
Hard
159
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2356530/Python-simple-one-liner
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: return median(sorted(nums1 + nums2))
median-of-two-sorted-arrays
Python simple one-liner
Arrstad
1
132
median of two sorted arrays
4
0.353
Hard
160
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2336302/Simple-or-Python-or-Beats-96.89
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1 = sorted(nums1 + nums2) l = len(nums1) if l % 2: return nums1[l // 2] else: l //= 2 return (nums1[l] + nums1[l - 1]) / 2
median-of-two-sorted-arrays
Simple | Python | Beats 96.89%
fake_death
1
238
median of two sorted arrays
4
0.353
Hard
161
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2308549/93-faster-or-python-or-O(n-logn)-or-simple-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1 = nums1+ nums2 nums1.sort() n = len(nums1) if n % 2 != 0: mid = nums1[n//2] return mid elif n%2 ==0: mid = n//2 avg = (nums1[mid] + (nums1[mid-1])) /2 return avg
median-of-two-sorted-arrays
93% faster | python | O(n logn) | simple solution
TuhinBar
1
99
median of two sorted arrays
4
0.353
Hard
162
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2147954/Python-Solution-oror-short-and-simple-code
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: l=nums1[:]+nums2[:] l.sort() r=0 if len(l)%2 !=0: r=l[len(l)//2] else: r=sum(l[len(l)//2 - 1 : len(l)//2 + 1]) / 2 return r
median-of-two-sorted-arrays
Python Solution || short and simple code
T1n1_B0x1
1
350
median of two sorted arrays
4
0.353
Hard
163
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1810446/Simple-Python3-Sol-O(m%2Bn)
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: len1 = len(nums1) len2 = len(nums2) n = len1+len2 i1,i2 = 0,0 d = [] while i2 < len2 and i1 < len1: if nums2[i2] > nums1[i1]: d.append(nums1[i1]) i1+=1 elif nums2[i2] == nums1[i1]: d.append(nums1[i1]) d.append(nums2[i2]) i1+=1 i2+=1 else: d.append(nums2[i2]) i2+=1 if n%2 == 0 and n//2<len(d): return (d[n//2]+d[n//2 - 1])/2 if n%2==1 and n//2<len(d): return d[n//2] if i1 == len1: d.extend(nums2[i2:]) else: d.extend(nums1[i1:]) if n%2 == 0: return (d[n//2]+d[n//2 - 1])/2 else: return d[n//2]
median-of-two-sorted-arrays
Simple Python3 Sol O(m+n)
shivamm0296
1
318
median of two sorted arrays
4
0.353
Hard
164
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1749839/Python3-or-Simple-or-O(n%2Bm)-or-two-pointers
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: ptr1 = 0 # pointer for nums1 ptr2 = 0 # pointer for nums2 ret = [] # list storing elements ascendingly until median while (ptr1+ptr2 < (len(nums1)+len(nums2)+1)/2): if ptr1 == len(nums1): ret.append(nums2[ptr2]) ptr2 += 1 continue if ptr2 == len(nums2): ret.append(nums1[ptr1]) ptr1 += 1 continue if nums1[ptr1] < nums2[ptr2]: ret.append(nums1[ptr1]) ptr1 += 1 else: ret.append(nums2[ptr2]) ptr2 += 1 if (len(nums1)+len(nums2))%2 == 0: return (ret[-1] + ret[-2]) / 2 else: return ret[-1]
median-of-two-sorted-arrays
Python3 | Simple | O(n+m) | two-pointers
Onlycst
1
634
median of two sorted arrays
4
0.353
Hard
165
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1598799/Self-explanatory-solution-with-almost-constant-space
class Solution: def findKthElement(self, nums1: List[int], nums2: List[int], k: int) -> float: if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1 lowNumSelected = 0 # minimum number of elements can be selected from shorter array highNumSelected = len(nums1) if k > len(nums1) else k # maximum number of elements can be selected from shorter array while(True): if lowNumSelected == highNumSelected: break shortArrCutOff = (lowNumSelected + highNumSelected) // 2 longArrCutOff = k - shortArrCutOff if longArrCutOff > len(nums2): lowNumSelected = shortArrCutOff + 1 else: leftShortLargestElement = nums1[shortArrCutOff - 1] if shortArrCutOff > 0 else -float('inf') rightShortSmallestElement = nums1[shortArrCutOff] if shortArrCutOff < len(nums1) else float('inf') leftLongLargestElement = nums2[longArrCutOff - 1] if longArrCutOff > 0 else -float('inf') rightLongSmallestElement = nums2[longArrCutOff] if longArrCutOff < len(nums2) else float('inf') if leftShortLargestElement > rightLongSmallestElement: highNumSelected = shortArrCutOff - 1 elif leftLongLargestElement > rightShortSmallestElement: lowNumSelected = shortArrCutOff + 1 else: break numSelected = (lowNumSelected + highNumSelected) // 2 if numSelected > 0: if k - numSelected > 0: return max(nums1[numSelected - 1], nums2[k - numSelected - 1]) else: return nums1[numSelected - 1] return nums2[k-1] def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m, n = len(nums1), len(nums2) if (m + n) % 2 == 1: k = (m + n) // 2 return self.findKthElement(nums1, nums2, k + 1) else: k = (m + n) // 2 return (self.findKthElement(nums1, nums2, k + 1) + self.findKthElement(nums1, nums2, k)) / 2
median-of-two-sorted-arrays
Self-explanatory solution with almost constant space
vudat1710
1
270
median of two sorted arrays
4
0.353
Hard
166
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1581195/Short-and-readable-python3-84ms-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: i=0 j=0 m2=0 l=len(nums1)+len(nums2) nums1.append(1000001) nums2.append(1000001) for _i in range(l//2+1): if nums1[i]<nums2[j]: m1,m2=m2,nums1[i] i+=1 else: m1,m2=m2,nums2[j] j+=1 return float(m2) if l%2 else float(m1+m2)/2
median-of-two-sorted-arrays
Short and readable python3 84ms solution
Veanules
1
467
median of two sorted arrays
4
0.353
Hard
167
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1580354/Two-two-two-pointers-as-if-they-were-merged
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n1 = len(nums1) n2 = len(nums2) n = n1 + n2 p1 = 0 p2 = n - 1 a1 = 0 a2 = n1 - 1 b1 = 0 b2 = n2 -1 while p2 - p1 > 1: p1 += 1 p2 -= 1 if a2 < a1: b1 += 1 b2 -= 1 continue if b2 < b1: a1 += 1 a2 -= 1 continue if nums1[a1] <= nums2[b1]: a1 += 1 else: b1 += 1 if nums1[a2] > nums2[b2]: a2 -= 1 else: b2 -= 1 if p1 == p2: return sum(nums1[a1:a2+1]) if len(nums1[a1:a2+1])>0 else sum(nums2[b1:b2+1]) return (sum(nums1[a1:a2+1]) + sum(nums2[b1:b2+1]))/2
median-of-two-sorted-arrays
Two-two-two pointers as if they were merged
hl2425
1
186
median of two sorted arrays
4
0.353
Hard
168
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1530105/Python3-solution-in-time-O(n%2Bm)
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m,n = len(nums1),len(nums2) if m+n<1: return -1 merge = [] i,j = 0,0 while i<len(nums1) and j<len(nums2): if nums1[i]<=nums2[j]: merge.append(nums1[i]) i+=1 elif nums1[i]>=nums2[j]: merge.append(nums2[j]) j+=1 if len(nums1)>i: merge.extend(nums1[i:]) else: merge.extend(nums2[j:]) a = len(merge) if a==1: return merge[0] b = ceil(a/2) if a%2==0: return (merge[b]+merge[b-1])/2 else: return merge[b-1]
median-of-two-sorted-arrays
Python3 solution in time O(n+m)
Abhists
1
300
median of two sorted arrays
4
0.353
Hard
169
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/1530105/Python3-solution-in-time-O(n%2Bm)
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: m,n = len(nums1),len(nums2) if m+n<1: return -1 merge = [] merge = sorted(nums1 + nums2) a = len(merge) if a==1: return merge[0] b = ceil(a/2) if a%2==0: return (merge[b]+merge[b-1])/2 else: return merge[b-1]
median-of-two-sorted-arrays
Python3 solution in time O(n+m)
Abhists
1
300
median of two sorted arrays
4
0.353
Hard
170
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2848110/python-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: complete = nums1 + nums2 complete.sort() if len(complete)%2 ==0: # return sum(complete)/len(complete) return (complete[int((len(complete) - 1)/2)] + complete[int((len(complete) + 1)/2)])/2 else : return complete[int((len(complete) - 1)/2)]
median-of-two-sorted-arrays
python solution
HARMEETSINGH0
0
1
median of two sorted arrays
4
0.353
Hard
171
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2841662/Python-oror-Easily-Understandable
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: for j in nums2: nums1.append(j) nums1.sort() if(len(nums1)%2==0): mid = len(nums1)//2 median = (nums1[mid-1] + nums1[mid])/2 else: mid = len(nums1)//2 median = nums1[mid] return median
median-of-two-sorted-arrays
Python || Easily Understandable
user6374IX
0
4
median of two sorted arrays
4
0.353
Hard
172
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2838883/it-works
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1.extend(nums2) n=len(nums1) nums1.sort() if n%2==0 : m=len(nums1)//2 return ((nums1[m-1]+nums1[m])/2) else: m=(len(nums1)//2)+1 return (nums1[m-1])
median-of-two-sorted-arrays
it works
venkatesh402
0
1
median of two sorted arrays
4
0.353
Hard
173
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2838698/Python-Straight-Forward-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: ptr1, ptr2 = 0, 0 res = [] while ptr1 < len(nums1) and ptr2 < len(nums2): if nums1[ptr1] < nums2[ptr2]: res.append(nums1[ptr1]) ptr1 += 1 else: res.append(nums2[ptr2]) ptr2 += 1 while ptr1 < len(nums1): res.append(nums1[ptr1]) ptr1 += 1 while ptr2 < len(nums2): res.append(nums2[ptr2]) ptr2 += 1 if len(res)%2 == 1: return res[len(res)//2] return (res[len(res)//2] + res[len(res)//2 - 1])/2
median-of-two-sorted-arrays
Python Straight Forward Solution
paul1202
0
3
median of two sorted arrays
4
0.353
Hard
174
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2838657/Python3-Fast-93ms-solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: num = sorted(nums1 + nums2) if len(num) % 2 != 0: return float("%.5f" % num[len(num) // 2]) return float("%.5f" % (num[len(num) // 2] + num[len(num) // 2 - 1])) / 2
median-of-two-sorted-arrays
Python3 Fast 93ms solution
Ki4EH
0
1
median of two sorted arrays
4
0.353
Hard
175
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2838406/2-Python-easy-Solution-with-video-explanation
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: if (len(nums1) > len(nums2)): return self.findMedianSortedArrays(nums2, nums1) start = 0 end = len(nums1) X = len(nums1) Y = len(nums2) while start <= end: division1 = (start + end) // 2 # mid division2 = (X + Y + 1) // 2 - division1 # left of the median of List 1 if (division1 == 0): X1 = float('-inf') else: X1 = nums1[division1 - 1] #right of the median of List 1 if (division1 == len(nums1)): X2 = float('inf') else: X2 = nums1[division1] # left of the median of List 2 if (division2 == 0): Y1 = float('-inf') else: Y1 = nums2[division2 - 1] # right of the median of List 2 if (division2 == len(nums2)): Y2 = float('inf') else: Y2 = nums2[division2] # check if we found the correct division if (X1 <= Y2 and Y1 <= X2): # check if the length of the sum of both lists are even or odd if (X + Y) % 2 == 0: median = ((max(X1, Y1) + min(X2, Y2)) / 2) return median else: #odd median = max(X1, Y1) return median elif Y1 > X2: start = division1 + 1 else: end = division1 - 1
median-of-two-sorted-arrays
2 Python easy Solution โœ”๏ธ with video explanation
CoderrrMan
0
7
median of two sorted arrays
4
0.353
Hard
176
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2832807/Easy-Python-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: merged_list = self.merge_sort(nums1, nums2) len_merged_list = len(merged_list) # middle index and middle - 1 index mid = len_merged_list // 2 # when the size is even if len_merged_list % 2 == 0: return (merged_list[mid] + merged_list[mid - 1]) / 2 # when the size is odd return merged_list[mid] def merge_sort(self, num1: List[int], num2: List[int]): merged_list = [] i = 0 j = 0 len_num1 = len(num1) - 1 len_num2 = len(num2) - 1 while i <= len_num1 and j <= len_num2: if num1[i] < num2[j]: merged_list.append(num1[i]) i += 1 else: merged_list.append(num2[j]) j += 1 while i <= len_num1: merged_list.append(num1[i]) i += 1 while j <= len_num2: merged_list.append(num2[j]) j += 1 return merged_list
median-of-two-sorted-arrays
Easy Python Solution
namashin
0
4
median of two sorted arrays
4
0.353
Hard
177
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2831276/Python3-Solution
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums1.extend(nums2) nums = sorted(nums1) # nums = list(set(nums)) m = len(nums) if m%2==0 and m>1: i = m//2 med = (nums[i-1]+nums[i])/2 elif m%2==1 and m>1: i = m//2 med = nums[i] else: med = nums[0] return med
median-of-two-sorted-arrays
Python3 Solution
sina1
0
2
median of two sorted arrays
4
0.353
Hard
178
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2821932/Maybe-I-am-misunderstanding-why-this-problem-is-'hard'-The-solution-seems-pretty-simple....
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: a = nums1 + nums2 a.sort() b = int(len(a)/2) if len(a) % 2 == 1: return a[b] return (a[b] + a[b-1]) / 2
median-of-two-sorted-arrays
Maybe I am misunderstanding why this problem is 'hard'? The solution seems pretty simple....
walter9388
0
18
median of two sorted arrays
4
0.353
Hard
179
https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2816882/dont-know-bro-its-just-simple
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: sum_list = nums1 + nums2 sum_list.sort() sum_size = len(sum_list) if sum_size % 2 == 0: x = (sum_list[int(sum_size/2)] + sum_list[int((sum_size/2) - 1)]) / 2 else: x = sum_list[int(sum_size/2)] return x
median-of-two-sorted-arrays
dont know bro its just simple
musaidovs883
0
13
median of two sorted arrays
4
0.353
Hard
180
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156659/Python-Easy-O(1)-Space-approach
class Solution: def longestPalindrome(self, s: str) -> str: n=len(s) def expand_pallindrome(i,j): while 0<=i<=j<n and s[i]==s[j]: i-=1 j+=1 return (i+1, j) res=(0,0) for i in range(n): b1 = expand_pallindrome(i,i) b2 = expand_pallindrome(i,i+1) res=max(res, b1, b2,key=lambda x: x[1]-x[0]+1) # find max based on the length of the pallindrome strings. return s[res[0]:res[1]]
longest-palindromic-substring
โœ… Python Easy O(1) Space approach
constantine786
47
6,600
longest palindromic substring
5
0.324
Medium
181
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156659/Python-Easy-O(1)-Space-approach
class Solution: def longestPalindrome(self, s: str) -> str: n=len(s) def expand_center(i,j): while 0<=i<=j<n and s[i]==s[j]: i-=1 j+=1 return (i+1, j) res=max([expand_center(i,i+offset) for i in range(n) for offset in range(2)], key=lambda x: x[1]-x[0]+1) return s[res[0]:res[1]]
longest-palindromic-substring
โœ… Python Easy O(1) Space approach
constantine786
47
6,600
longest palindromic substring
5
0.324
Medium
182
https://leetcode.com/problems/longest-palindromic-substring/discuss/1057629/Python.-Super-simple-and-easy-understanding-solution.-O(n2).
class Solution: def longestPalindrome(self, s: str) -> str: res = "" length = len(s) def helper(left: int, right: int): while left >= 0 and right < length and s[left] == s[right]: left -= 1 right += 1 return s[left + 1 : right] for index in range(len(s)): res = max(helper(index, index), helper(index, index + 1), res, key = len) return res
longest-palindromic-substring
Python. Super simple & easy-understanding solution. O(n^2).
m-d-f
18
2,300
longest palindromic substring
5
0.324
Medium
183
https://leetcode.com/problems/longest-palindromic-substring/discuss/2157014/Python-2-Approaches-with-Explanation
class Solution: def longestPalindrome(self, s: str) -> str: """ Consider each character in s as the centre of a palindrome. Check for the longest possible odd-length and even-length palindrome; store the longest palindrome """ # res is the starting index of the longest palindrome # len_res is the length of the longest palindrome # len_s is the length of the given string res, len_res, len_s = 0, 0, len(s) for i in range(len_s): # check for palindromes with odd number of characters centred around s[i] # i.e., s[i] -> s[i-1:i+2] -> s[i-2:i+3] -> ... # odd is the starting index of the current palindrome with odd number of characters # len_odd is the length of the current palindrome with odd number of characters odd, len_odd = i, 1 for j in range(min(i, len_s-i-1)): # checking indexes [0, i) and [i+1, len_s); take the smaller range if s[i-j-1] != s[i+j+1]: # if the two characters adjacent to the ends of the current palindrome are not equal, break # a longer palindrome does not exist; break out of the loop odd, len_odd = odd-1, len_odd+2 # else, a longer palindrome exists; update odd and len_odd to point to that palindrome # check for palindromes with even number of characters centred around s[i-1:i+1] # i.e., s[i-1:i+1] -> s[i-2:i+2] -> s[i-3:i+3] -> ... # even is the starting index of the current palindrome with even number of characters # len_even is the length of the current palindrome with even number of characters even, len_even = i, 0 for j in range(min(i, len_s-i)): # checking indexes [0, i) and [i, len_s); take the smaller range if s[i-j-1] != s[i+j]: # if the two characters adjacent to the ends of the current palindrome are not equal, break # a longer palindrome does not exist; break out of the loop even, len_even = even-1, len_even+2 # else, a longer palindrome exists; update even and len_even to point to that palindrome # update res and len_res to point to the longest palindrome found so far len_res, res = max((len_res, res), (len_odd, odd), (len_even, even)) return s[res:res+len_res]
longest-palindromic-substring
[Python] 2 Approaches with Explanation
zayne-siew
11
905
longest palindromic substring
5
0.324
Medium
184
https://leetcode.com/problems/longest-palindromic-substring/discuss/2157014/Python-2-Approaches-with-Explanation
class Solution: def longestPalindrome(self, s: str) -> str: """ Manacher's Algorithm for longest palindromic substrings (LPS) """ # Transform S into T # For example, S = "abba", T = "^#a#b#b#a#$" # ^ and $ signs are sentinels appended to each end to avoid bounds checking T = '#'.join('^{}$'.format(s)) n = len(T) P = [0]*n C = R = 0 for i in range (1, n-1): P[i] = (R > i) and min(R-i, P[2*C-i]) # equals to i' = C - (i-C) # Attempt to expand palindrome centered at i while T[i+1+P[i]] == T[i-1-P[i]]: P[i] += 1 # If palindrome centered at i expand past R, # adjust center based on expanded palindrome if i+P[i] > R: C, R = i, i+P[i] # Find the maximum element in P maxLen, centerIndex = max((n, i) for i, n in enumerate(P)) return s[(centerIndex-maxLen)//2: (centerIndex+maxLen)//2]
longest-palindromic-substring
[Python] 2 Approaches with Explanation
zayne-siew
11
905
longest palindromic substring
5
0.324
Medium
185
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156653/PYTHON-oror-DYNAMIC-AND-BRUTE-oror
class Solution: def longestPalindrome(self, s: str) -> str: res=s[0] nn=len(res) n=len(s) for i in range(1,n-1): kk=s[i] z=1 while ((i-z)>=0) and ((i+z)<n) and (s[i-z]==s[i+z]): kk=s[i-z]+kk+s[i-z] z+=1 if len(kk)>nn: res=kk nn=len(res) for i in range(0,n-1): if s[i]==s[i+1]: kk=s[i]+s[i+1] z=1 while ((i-z)>=0) and ((i+z+1)<n) and (s[i-z]==s[i+z+1]): kk=s[i-z]+kk+s[i-z] z+=1 if len(kk)>nn: res=kk nn=len(res) return res
longest-palindromic-substring
โœ”๏ธ PYTHON || DYNAMIC AND BRUTE || ;]
karan_8082
10
734
longest palindromic substring
5
0.324
Medium
186
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156653/PYTHON-oror-DYNAMIC-AND-BRUTE-oror
class Solution: def longestPalindrome(self, s): res = '' dp = [[0]*len(s) for i in range(len(s))] for i in range(len(s)): dp[i][i] = True res = s[i] for i in range(len(s)-1,-1,-1): for j in range(i+1,len(s)): if s[i] == s[j]: if j-i ==1 or dp[i+1][j-1] is True: dp[i][j] = True if len(res) < len(s[i:j+1]): res = s[i:j+1] return res
longest-palindromic-substring
โœ”๏ธ PYTHON || DYNAMIC AND BRUTE || ;]
karan_8082
10
734
longest palindromic substring
5
0.324
Medium
187
https://leetcode.com/problems/longest-palindromic-substring/discuss/368409/Solution-in-Python-3-(-six-lines-)-(-O(n2)-speed-)-(-O(1)-space-)-(With-Explanation)-(beats-~90)
class Solution: def longestPalindrome(self, s: str) -> str: L, M, x = len(s), 0, 0 for i in range(L): for a,b in [(i,i),(i,i+1)]: while a >= 0 and b < L and s[a] == s[b]: a -= 1; b += 1 if b - a - 1 > M: M, x = b - a - 1, a + 1 return s[x:x+M] - Junaid Mansuri (LeetCode ID)@hotmail.com
longest-palindromic-substring
Solution in Python 3 ( six lines ) ( O(n^2) speed ) ( O(1) space ) (With Explanation) (beats ~90%)
junaidmansuri
8
1,600
longest palindromic substring
5
0.324
Medium
188
https://leetcode.com/problems/longest-palindromic-substring/discuss/2718979/Python-Solution-readable-code-with-thorough-explanation.
class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) # Length of the input if n == 1: return s def expandOutwards(start, end): i = start k = end if s[i] != s[k]: return "" while(i-1 >= 0 and k+1 < n and s[i-1] == s[k+1]): i-=1 k+=1 return s[i:k+1] pal1 = "" pal2 = "" longPal = "" for i in range(0, n-1): pal1 = expandOutwards(i, i) pal2 = expandOutwards(i, i+1) # Conditional assignment statement temp = pal1 if len(pal1) > len(pal2) else pal2 if len(temp) > len(longPal): longPal = temp return longPal
longest-palindromic-substring
Python Solution, readable code with thorough explanation.
BrandonTrastoy
6
1,300
longest palindromic substring
5
0.324
Medium
189
https://leetcode.com/problems/longest-palindromic-substring/discuss/2164588/Python3-solution-with-two-pointers
class Solution: indices = [] maxLength = -float("inf") def isPalindrome(self,low,high,s): while low>=0 and high<len(s) and s[low]==s[high]: low-=1 high+=1 if self.maxLength<high-low+1: self.maxLength = high-low+1 self.indices = [low,high] def longestPalindrome(self, s: str) -> str: self.indices = [] self.maxLength = -float("inf") for i in range(len(s)): self.isPalindrome(i,i,s) self.isPalindrome(i,i+1,s) return s[self.indices[0]+1 : self.indices[1]]
longest-palindromic-substring
๐Ÿ“Œ Python3 solution with two pointers
Dark_wolf_jss
5
112
longest palindromic substring
5
0.324
Medium
190
https://leetcode.com/problems/longest-palindromic-substring/discuss/1767684/Clean-Python-Solution
class Solution: def longestPalindrome(self, s: str) -> str: n, max_len, ans = len(s), 0, '' def expand_around_center(l, r): if r < n and s[l] != s[r]: return '' # Index out of range or elements unequal(for even sized palindromes) thus return empty string while l >= 0 and r < n and s[l] == s[r]: # Till the s[l], s[r] elements are in range and same, the palindrome continues to grow l, r = l - 1, r + 1 return s[l + 1:r] # Return the palindrome formed for i in range(n): a, b = expand_around_center(i, i), expand_around_center(i, i + 1) # (i,i) for odd and (i,i+1) for even sized palindromes main = a if len(a) > len(b) else b # Check which one of a, b is larger if len(main) > max_len: # Check if palindrome with i as center is larger than previous entries then update if necessary max_len, ans = len(main), main return ans
longest-palindromic-substring
Clean Python Solution
anCoderr
4
760
longest palindromic substring
5
0.324
Medium
191
https://leetcode.com/problems/longest-palindromic-substring/discuss/2601218/Simple-python-code-with-explanation
class Solution: def longestPalindrome(self, s: str) -> str: #create an empty string res res = "" #store it's length as 0 in resLen resLen = 0 #iterate using indexes in the string for i in range(len(s)): #odd case #create the two pointers pointing at current position l,r = i,i #this while loop works utill it satisfies the following conditions #l pointer should be greater than or equal to 0 #r pointer should be less than length of the string #value at l pointer and r pointer should be same while l >= 0 and r < len(s) and s[l] == s[r]: #if the palindrome substring's length is greater than resLen if (r-l+1) > resLen: #change the res sting to the palindrome substring res = s[l:r+1] #and change the length of the res string to the palindrome substring length resLen = (r-l+1) #decrease the l pointer value by 1 #to see the left side elements l -=1 #increase the r pointer value by 1 #to see the right side elements r +=1 #even case #create a two pointers l is at curr position and r is at next position l,r = i,i+1 #this while loop works utill it satisfies the following conditions #l pointer should be greater than or equal to 0 #r pointer should be less than length of the string #value at l pointer and r pointer should be same while l >= 0 and r < len(s) and s[l] == s[r]: #if the palindrome substring's length is greater than resLen if (r-l+1) > resLen: #change the res sting to the palindrome substring res = s[l:r+1] #and change the length of the res string to the palindrome substring length resLen = (r-l+1) #decrease the l pointer value by 1 #to see the left side elements l -=1 #increase the r pointer value by 1 #to see the right side elements r +=1 #return the palindromic substring stored in the res string return res
longest-palindromic-substring
Simple python code with explanation
thomanani
3
532
longest palindromic substring
5
0.324
Medium
192
https://leetcode.com/problems/longest-palindromic-substring/discuss/2156940/Longest-Palindromic-Substring
class Solution: def longestPalindrome(self, s: str) -> str: long_s = '' n = len(s) for i in range(n) : left = i right = i while left >= 0 and right < n and s[left] == s[right] : # print("left :", left) # print("Right :", right) if len(long_s) < right - left + 1 : long_s = s[left : right + 1] # print("long_s :", long_s) left -= 1 right += 1 left = i right = i + 1 # print("================") # This Loop Is used if substring is in betwwen of two word i.e "bb" while left >= 0 and right < n and s[left ] == s[right] : # print("left 2===:", left) # print("Right 2===:", right) if len(long_s) < right - left + 1 : long_s = s[left : right + 1] # print("long_s 2:", long_s) left -= 1 right += 1 return long_s
longest-palindromic-substring
Longest Palindromic Substring
vaibhav0077
3
312
longest palindromic substring
5
0.324
Medium
193
https://leetcode.com/problems/longest-palindromic-substring/discuss/1504461/Python3-Beats-95.79
class Solution: def longestPalindrome(self, s: str) -> str: longest = "" core_start = 0 while core_start in range(len(s)): # identifying the "core" core_end = core_start while core_end < len(s) - 1: if s[core_end + 1] == s[core_end]: core_end += 1 else: break # expanding the palindrome left and right expand = 0 while (core_start - expand) > 0 and (core_end + expand) < len(s) - 1: if s[core_start - expand - 1] == s[core_end + expand + 1]: expand += 1 else: break # comparing to the longest found so far if (core_end + expand + 1) - (core_start - expand) > len(longest): longest = s[(core_start - expand):(core_end + expand + 1)] # skip through the rest of the "core" core_start = core_end + 1 return longest
longest-palindromic-substring
[Python3] Beats 95.79%
Wallace_W
3
1,700
longest palindromic substring
5
0.324
Medium
194
https://leetcode.com/problems/longest-palindromic-substring/discuss/2337365/EFFICIENT-APPROCH-using-python3
class Solution: def longestPalindrome(self, s: str) -> str: def func(i,j): while(i>=0 and j<len(s) and s[i]==s[j]): i-=1 j+=1 return(s[i+1:j]) r="" for i in range(len(s)): test=func(i,i) if len(r)<len(test): r=test test=func(i,i+1) if len(r)<len(test): r=test return r
longest-palindromic-substring
EFFICIENT APPROCH using python3
V_Bhavani_Prasad
2
88
longest palindromic substring
5
0.324
Medium
195
https://leetcode.com/problems/longest-palindromic-substring/discuss/2311861/Easy-Python3-Two-Pointer-Solution-w-Explanation
class Solution: def longestPalindrome(self, s: str) -> str: res = '' for i in range(len(s)*2-1): # i refers to the "central" (or "mid point" or "pivot") of the palindrome # Uses index 0 as central, uses the middle of index 0 and 1 as central and so on # idx 0 1 2 3 4 ... # l r # l r # l r # l r # ... l, r = i // 2, (i + 1) // 2 # Move the pointers outward to check if they are palidrome while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 res = res if len(res) > len(s[l+1:r]) else s[l+1:r] return res
longest-palindromic-substring
Easy Python3 Two Pointer Solution w/ Explanation
geom1try
2
204
longest palindromic substring
5
0.324
Medium
196
https://leetcode.com/problems/longest-palindromic-substring/discuss/1993958/Python3-Runtime%3A-897ms-81.93-memory%3A-13.9mb-99.78
class Solution: # O(n^2) || space O(n) def longestPalindrome(self, string: str) -> str: if not string or len(string) < 1: return '' start, end = 0, 0 for i in range(len(string)): odd = self.expandFromMiddleHelper(string, i, i) even = self.expandFromMiddleHelper(string, i, i + 1) maxIndex = max(odd, even) if maxIndex > end - start: start = i - ((maxIndex - 1) // 2) end = i + (maxIndex // 2) return string[start:end + 1] def expandFromMiddleHelper(self, string, left, right): while left >= 0 and right < len(string) and string[left] == string[right]: left -= 1 right += 1 currentWindowSize = (right - left - 1) return currentWindowSize
longest-palindromic-substring
Python3 Runtime: 897ms 81.93% memory: 13.9mb 99.78%
arshergon
2
361
longest palindromic substring
5
0.324
Medium
197
https://leetcode.com/problems/longest-palindromic-substring/discuss/1993958/Python3-Runtime%3A-897ms-81.93-memory%3A-13.9mb-99.78
class Solution: # O(n^2) || space O(n) def longestPalindrome(self, string: str) -> str: result = "" for i in range(len(string)): left, right = i, i while left >= 0 and right < len(string) and string[left] == string[right]: currentWindowSize = (right - left + 1) if currentWindowSize > len(result): result = string[left:right + 1] left -= 1 right += 1 left, right = i, i + 1 while left >= 0 and right < len(string) and string[left] == string[right]: currentWindowSize = (right - left + 1) if currentWindowSize > len(result): result = string[left: right + 1] left -= 1 right += 1 return result
longest-palindromic-substring
Python3 Runtime: 897ms 81.93% memory: 13.9mb 99.78%
arshergon
2
361
longest palindromic substring
5
0.324
Medium
198
https://leetcode.com/problems/longest-palindromic-substring/discuss/2614056/Clean-python-solution-expand-from-the-center
class Solution: def longestPalindrome(self, s: str) -> str: res = "" def helper(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left+1 : right] for i in range(len(s)): res = max(helper(i, i), helper(i, i+1), res, key=len) return res
longest-palindromic-substring
Clean python solution expand from the center
miko_ab
1
180
longest palindromic substring
5
0.324
Medium
199