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/maximum-gap/discuss/2146775/Python-simple-solution
class Solution: def maximumGap(self, n: List[int]) -> int: if len(n) == 1: return 0 n = sorted(n) tmp = n[0] dif = -1 for i in range(1, len(n)): dif = n[i] - tmp if n[i] - tmp > dif else dif tmp = n[i] return dif
maximum-gap
Python simple solution
StikS32
0
79
maximum gap
164
0.428
Hard
2,600
https://leetcode.com/problems/maximum-gap/discuss/2108408/Easy-5-lines-of-code
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums) < 2: return 0 nums.sort() res = 0 for i in range(1, len(nums)): res = max(res, nums[i] - nums[i - 1]) return res
maximum-gap
Easy 5 lines of code
ankurbhambri
0
60
maximum gap
164
0.428
Hard
2,601
https://leetcode.com/problems/maximum-gap/discuss/2068224/Python-(Bucketing-technique-used)
class Solution: def maximumGap(self, arr: List[int]) -> int: min1 = float('inf') max1 = float('-inf') n = len(arr) if (n < 2): return 0 for i in range(0, n): min1 = min(min1, arr[i]) max1 = max(max1, arr[i]) if (max1 == min1): return 0 gap = (max1 - min1) // (n-1) # print((max1-min1)/(n-1), min1, max1, n-1, max1-min1, 8/3) # print(gap) if ((max1 - min1) % (n-1) != 0): gap += 1 # print(gap, min1, max1) # new_arr = [0]*(n+1) # for i in range(0, n+1): # new_arr[i]= [min1 + (i* gap), min1 + (i+1)*gap-1] # print(new_arr) min_bucket = [float('inf')] * (n) max_bucket = [float('-inf')] * (n) # print(min_bucket, max_bucket) for i in range(0, n): bucket_num = (arr[i] - min1) // gap # print(bucket_num) min_bucket[bucket_num] = min(arr[i], min_bucket[bucket_num]) max_bucket[bucket_num] = max(arr[i], max_bucket[bucket_num]) # print(min_bucket, max_bucket) # print(max_bucket[1]) # if (max_bucket[1] == -inf): # print('es') prev = max_bucket[0] ans = float('-inf') for i in range(1, len(min_bucket)): # print("Ok", prev) if (prev == float('-inf') or min_bucket[i] == float('inf')): # print("EXE") continue ans = max(ans, min_bucket[i] - prev) # print("prev",min_bucket[i], ans, prev) prev = max_bucket[i] return ans
maximum-gap
Python (Bucketing technique used)
luffySenpai
0
85
maximum gap
164
0.428
Hard
2,602
https://leetcode.com/problems/maximum-gap/discuss/1834905/Python3-just-a-few-lines
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums) <= 1: return 0 nums_sorted = sorted(nums) num_pairs = {(nums_sorted[i], nums_sorted[i+1]): abs(nums_sorted[i] - nums_sorted[i+1]) for i in range(len(nums_sorted) - 1)} return max(num_pairs.values())
maximum-gap
Python3, just a few lines
markkonnov
0
88
maximum gap
164
0.428
Hard
2,603
https://leetcode.com/problems/maximum-gap/discuss/2425853/Python-oror-Simple-Solution-oror-Faster-than-94
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums) < 2: return 0 nums.sort() max_gap = 0 for i in range(1, len(nums)): max_gap = max(max_gap, nums[i] - nums[i - 1]) return max_gap
maximum-gap
Python || Simple Solution || Faster than 94%
Gyalecta
-1
97
maximum gap
164
0.428
Hard
2,604
https://leetcode.com/problems/maximum-gap/discuss/2313312/Python-Solution-91-Faster.
class Solution: def maximumGap(self, nums: List[int]) -> int: ans = [] difference = 0 nums.sort() if len(nums)<2: x = 0 else: for i in range(len(nums)-1): if i<len(nums): difference = nums[i] - nums[i+1] ans.append(difference) difference = 0 x = min(ans)*(-1) return x
maximum-gap
Python Solution 91% Faster.
Hishamik
-1
86
maximum gap
164
0.428
Hard
2,605
https://leetcode.com/problems/maximum-gap/discuss/945999/less-than-10-lines
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums) < 2: return 0 else: max = 0 nums_s = sorted(nums) for i in range(len(nums_s)-1): if abs(nums_s[i] - nums_s[i+1]) > max: max = abs(nums_s[i] - nums_s[i+1]) return max
maximum-gap
less than 10 lines
yeha_audrey
-3
99
maximum gap
164
0.428
Hard
2,606
https://leetcode.com/problems/maximum-gap/discuss/1155939/simple-logical-solution
class Solution: def maximumGap(self, nums: List[int]) -> int: nums.sort() if (len(nums))<2: return 0 else: max1=nums[1]-nums[0] for i in range (1,len(nums)-1): max1=max(nums[i+1]-nums[i],max1) return(max1)
maximum-gap
simple logical solution
janhaviborde23
-5
219
maximum gap
164
0.428
Hard
2,607
https://leetcode.com/problems/maximum-gap/discuss/1024433/Pythonic-Runtime%3A-44-ms-faster-than-99.16-or-Memory-Usage%3A-14.9-MB-less-than-97.82
class Solution: def maximumGap(self, nums: List[int]) -> int: if len(nums)<2: return 0 nums.sort() return max(map(lambda x:abs(x[0]-x[1]), zip(nums[:-1],nums[1:])))
maximum-gap
[Pythonic] Runtime: 44 ms, faster than 99.16% | Memory Usage: 14.9 MB, less than 97.82%
bhz14
-5
217
maximum gap
164
0.428
Hard
2,608
https://leetcode.com/problems/maximum-gap/discuss/1207020/Why-overthink-when-you-can-do-it-easily-with-3-lines-of-Python-code
class Solution: def maximumGap(self, num): if len(num) < 2: return 0 num.sort() return max(abs(n2 - n1) for n1, n2 in zip(num[1:], num[:-1]))
maximum-gap
Why overthink when you can do it easily with 3 lines of Python code?
A88888
-8
314
maximum gap
164
0.428
Hard
2,609
https://leetcode.com/problems/compare-version-numbers/discuss/1797594/Python3-SOLUTION-Explained
class Solution: def compareVersion(self, v1: str, v2: str) -> int: v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.'))) for rev1, rev2 in zip_longest(v1, v2, fillvalue=0): if rev1 == rev2: continue return -1 if rev1 < rev2 else 1 return 0
compare-version-numbers
✔️ [Python3] SOLUTION, Explained
artod
47
3,400
compare version numbers
165
0.354
Medium
2,610
https://leetcode.com/problems/compare-version-numbers/discuss/1797395/Python3-or-Simple-and-Concise-Solution-orEasy-To-Understand-WExplanation
class Solution: ''' Space complexity: `O(m + n)` Since split operation will be taking extra space to populate the array ''' def compareVersion(self, version1: str, version2: str) -> int: version1, version2 = version1.split('.'), version2.split('.') m, n = len(version1), len(version2) i = j = 0 while(i < m or j < n): revision1 = int(version1[i]) if(i < m) else 0 revision2 = int(version2[j]) if(j < n) else 0 if(revision1 < revision2): return -1 if(revision1 > revision2): return 1 i, j = i + 1, j + 1 return 0
compare-version-numbers
✅ Python3 | Simple and Concise Solution |Easy To Understand W/Explanation
thoufic
8
628
compare version numbers
165
0.354
Medium
2,611
https://leetcode.com/problems/compare-version-numbers/discuss/1798371/Python-Python3-Two-Solutions
class Solution(object): def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ version1 = version1.split(".") version2 = version2.split(".") c = 0 while c < len(version1) and c < len(version2): if int(version1[c])>int(version2[c]): return 1 elif int(version2[c])>int(version1[c]): return -1 else: c += 1 if c < len(version1): for i in version1[c:]: if int(i) > 0: return 1 if c < len(version2): for i in version2[c:]: if int(i) > 0: return -1 return 0
compare-version-numbers
[Python, Python3] Two Solutions
zouhair11elhadi
2
53
compare version numbers
165
0.354
Medium
2,612
https://leetcode.com/problems/compare-version-numbers/discuss/1798371/Python-Python3-Two-Solutions
class Solution: def compareVersion(self, version1: str, version2: str) -> int: import itertools version1 = version1.split('.') version2 = version2.split('.') for v1, v2 in itertools.zip_longest(version1, version2, fillvalue=0): if int(v1)>int(v2): return 1 elif int(v2)>int(v1): return -1 return 0
compare-version-numbers
[Python, Python3] Two Solutions
zouhair11elhadi
2
53
compare version numbers
165
0.354
Medium
2,613
https://leetcode.com/problems/compare-version-numbers/discuss/1797537/Simple-and-Short-Python-Solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = version1.split('.') # Divide string version1 into array seperated by "." v2 = version2.split('.') # Divide string version2 into array seperated by "." m = len(v1) n = len(v2) # Just take strings at index i from v1 &amp; v2, convert them to integer and check which version is larger. # If an array is already traversed then we may consider the version to be 0. for i in range(max(m, n)): i1 = int(v1[i]) if i < m else 0 i2 = int(v2[i]) if i < n else 0 if i1 > i2: return 1 if i1 < i2: return -1 return 0 # Both versions must be same if their was no difference at any point.
compare-version-numbers
Simple & Short Python Solution
anCoderr
2
71
compare version numbers
165
0.354
Medium
2,614
https://leetcode.com/problems/compare-version-numbers/discuss/1205028/Python-with-comments
class Solution: def compareVersion(self, version1: str, version2: str) -> int: ver1l ,ver2l = version1.split('.') , version2.split('.') for i in range(max(len(ver1l), len(ver2l))): a = int(ver1l[i]) if i<len(ver1l) else 0 b = int(ver2l[i]) if i<len(ver2l) else 0 if a>b: return 1 elif a<b: return -1 return 0
compare-version-numbers
Python with comments
vladeremin
2
100
compare version numbers
165
0.354
Medium
2,615
https://leetcode.com/problems/compare-version-numbers/discuss/2412135/Python-or-Easy-to-understand-or-For-Beginner-or-Faster-than-90
class Solution: def compareVersion(self, version1: str, version2: str) -> int: ver1=version1.split('.') ver2=version2.split('.') i=0 maxlen=max(len(ver1),len(ver2)) while i<maxlen: v1=int(ver1[i]) if i<len(ver1) else 0 v2=int(ver2[i]) if i<len(ver2) else 0 if v1<v2: return -1 elif v1>v2: return 1 else: i+=1 return 0
compare-version-numbers
Python | Easy to understand | For Beginner | Faster than 90%
user2559cj
1
53
compare version numbers
165
0.354
Medium
2,616
https://leetcode.com/problems/compare-version-numbers/discuss/1799514/Python3-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: lst1=list(map(int,version1.split("."))) lst2=list(map(int,version2.split("."))) i=0 if len(lst1)!=lst2: if len(lst1)<len(lst2): x=len(lst2)-len(lst1) while x!=0: lst1.append(0) x-=1 if len(lst1)>len(lst2): x=len(lst1)-len(lst2) while x!=0: lst2.append(0) x-=1 while i<len(lst1) and i<len(lst2): if lst1[i]<lst2[i]: return -1 elif lst1[i]>lst2[i]: return 1 i+=1 return 0
compare-version-numbers
Python3 solution
amannarayansingh10
1
24
compare version numbers
165
0.354
Medium
2,617
https://leetcode.com/problems/compare-version-numbers/discuss/1799104/Python3-oror-String-Split-oror-98-Faster-oror-Space-Efficient
class Solution: def compareVersion(self, version1: str, version2: str) -> int: fn = lambda v: list(map(int, v.split("."))) l1, l2 = fn(version1), fn(version2) if len(l1) > len(l2): l2.extend([0] * (len(l1) - len(l2))) elif len(l1) < len(l2): l1.extend([0] * (len(l2) - len(l1))) for i in range(len(l1)): if l1[i] < l2[i]: return -1 elif l1[i] > l2[i]: return 1 return 0
compare-version-numbers
Python3 || String Split || 98% Faster || Space Efficient
cherrysri1997
1
18
compare version numbers
165
0.354
Medium
2,618
https://leetcode.com/problems/compare-version-numbers/discuss/1797858/Explanation-with-Examples-oror-Cover-the-Cases
class Solution: def compareVersion(self, version1: str, version2: str) -> int: l=list(map(int,version1.split('.'))) # convert the version1 into list k=list(map(int,version2.split('.'))) # convert the version2 into list while len(l)<len(k): # to make size same add extra zeros l.append(0) while len(k)<len(l): # to make size same add extra zeros k.append(0) a="".join(str(i) for i in l) # join the list to make number b="".join(str(i) for i in k) # join the list to make number if int(a)>int(b): # Now we got two integer number of version return 1 # just compare and return accordingly if int(a)<int(b): return -1 return 0
compare-version-numbers
Explanation with Examples || Cover the Cases
rushi_javiya
1
12
compare version numbers
165
0.354
Medium
2,619
https://leetcode.com/problems/compare-version-numbers/discuss/1797675/Python-O(1)-Space!
class Solution: def compareVersion(self, version1: str, version2: str) -> int: def isSeperator(i, version): N = len(version) return i == N or i < N and version[i] == '.' def isDigit(i, version): N = len(version) return i < N and version[i].isdigit() N1, N2 = len(version1), len(version2) v1 = v2 = i1 = i2 = 0 while i1 <= N1 or i2 <= N2: if isDigit(i1, version1): v1 = v1 * 10 + int(version1[i1]) i1 += 1 if isDigit(i2, version2): v2 = v2 * 10 + int(version2[i2]) i2 += 1 if isSeperator(i1, version1) and isSeperator(i2, version2) or \ isSeperator(i1, version1) and i2 > N2 or \ isSeperator(i2, version2) and i1 > N1: if v1 < v2: return -1 if v1 > v2: return 1 i1 += 1 i2 += 1 v1 = v2 = 0 return 0
compare-version-numbers
[Python] O(1) Space!
PatrickOweijane
1
56
compare version numbers
165
0.354
Medium
2,620
https://leetcode.com/problems/compare-version-numbers/discuss/1797258/Python-Five-Line-Zip-Solution!
class Solution: def compareVersion(self, version1: str, version2: str) -> int: for a, b in zip_longest(version1.split("."), version2.split("."), fillvalue="0"): a, b = int(a), int(b) if a > b: return 1 elif a < b: return -1 return 0
compare-version-numbers
✅ 🐍 Python Five Line Zip Solution! 🔥 🚀
Cavalier_Poet
1
103
compare version numbers
165
0.354
Medium
2,621
https://leetcode.com/problems/compare-version-numbers/discuss/1715207/Better-Python3-solution-O(1)-space-O(n)-time-two-pointers-no-split-no-list
class Solution: def compareVersion(self, version1: str, version2: str) -> int: # Initialize two pointers p1 = p2 = 0 while p1 < len(version1) and p2 < len(version2): # Find first non-zero char in current chunk in version1 while p1 < len(version1) and version1[p1] == "0": p1 += 1 # Find first non-zero char in current chunk in version2 while p2 < len(version2) and version2[p2] == "0": p2 += 1 if p1 >= len(version1) or p2 >= len(version2): break # Start comparing current chunks assuming they have the same length # We will check their length later compare = 0 while p1 < len(version1) and p2 < len(version2) and version1[p1] != "." and version2[p2] != ".": if compare == 0 and version1[p1] != version2[p2]: if version1[p1] > version2[p2]: compare = 1 if version1[p1] < version2[p2]: compare = -1 p1 += 1 p2 += 1 # We got out of the previous while loop # That means at least one of our pointers found "." or got to the end # If chunk1 is longer if p1 < len(version1) and version1[p1] != ".": return 1 # If chunk2 is longer if p2 < len(version2) and version2[p2] != ".": return -1 # If both chunks have the same length and we found difference in them if compare != 0: return compare # If both chunks are exactly the same so far, keep going p1 += 1 p2 += 1 # We got out of the outermost while loop # That means at least one of our pointers got to the end while p2 < len(version2): # If there is still non-zero numbers in version2 if version2[p2] != "0" and version2[p2] != ".": return -1 p2 += 1 while p1 < len(version1): # If there is still non-zero numbers in version1 if version1[p1] != "0" and version1[p1] != ".": return 1 p1 += 1 return 0
compare-version-numbers
Better Python3 solution, O(1) space, O(n) time, two pointers, no split, no list
qzt474838957
1
64
compare version numbers
165
0.354
Medium
2,622
https://leetcode.com/problems/compare-version-numbers/discuss/2775225/Python-or-iterative-Solution-or-100-or-O(N)
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = list(map(int,version1.split('.'))) v2 = list(map(int,version2.split('.'))) for i in range(min(len(v1),len(v2))): if v1[i]< v2[i]: return -1 elif v1[i]>v2[i]: return 1 if len(v1)> len(v2): i= len(v2) while(i<len(v1)): if v1[i] >0: return 1 i+=1 if len(v1)< len(v2): i= len(v1) while(i<len(v2)): if v2[i] >0: return -1 i+=1 return 0
compare-version-numbers
Python | iterative Solution | 100% | O(N)
utkarshjain
0
5
compare version numbers
165
0.354
Medium
2,623
https://leetcode.com/problems/compare-version-numbers/discuss/2661738/Python-97-Faster-Simple-step-by-step-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: #create Lists of the string lv1 = (version1.split(".")) lv2 = (version2.split(".")) #make them the same length while len(lv1) > len(lv2): lv2.append(0) while len(lv2) > len(lv1): lv1.append(0) #check each number to see if one is higher for idx in list(range(0,len(lv1))): if int(lv1[idx]) > int(lv2[idx]): return(1) elif int(lv1[idx]) < int(lv2[idx]): return(-1) #if they're the same return 0 return(0)
compare-version-numbers
Python 97% Faster - Simple step by step solution
ovidaure
0
10
compare version numbers
165
0.354
Medium
2,624
https://leetcode.com/problems/compare-version-numbers/discuss/2434718/ONE-PASS-NO-SPLIT-Explained-Python-solution-O(max(NM))-No-additional-space
class Solution: def compareVersion(self, version1: str, version2: str) -> int: # make two pointers to memorize position inside a string ptr1 = 0 ptr2 = 0 # while one of the string still has characters left, we need to go on while ptr1 < len(version1) or ptr2 < len(version2): # find the first revision number rev1, ptr1 = get_revision(version1, ptr1) # find second revision number rev2, ptr2 = get_revision(version2, ptr2) # compare the revisions if rev1 < rev2: return -1 elif rev1 > rev2: return 1 # we found no differences return 0 def get_revision(version, start): """ Receives the string and the starting position of a revision (at beginning, or after a point) """ # find the revision. We add numbers until we reach the end of the string # or we reach a seperator (.) rev = 0 while start < len(version) and version[start] != '.': # we need to shift the digit one higer (x10) # and we need to add the current number: ord(char) - ord('0') rev = rev*10 + ( ord(version[start]) - ord('0')) # go to the next character start += 1 # increase the pointer by one (so we get to the next revision) start += 1 # implicitly this returns a revision of zero if the version number is out of characters return rev, start
compare-version-numbers
[ONE PASS NO SPLIT] - Explained Python solution - O(max(N,M)) - No additional space
Lucew
0
20
compare version numbers
165
0.354
Medium
2,625
https://leetcode.com/problems/compare-version-numbers/discuss/2262491/python3-oror-easy-oror-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: i=0 j=0 v1Len=len(version1) v2Len=len(version2) while i<v1Len or j<v2Len: n1=0 n2=0 while i<v1Len and version1[i]!='.': n1=n1*10+int(version1[i]) i+=1 while j<v2Len and version2[j]!='.': n2=n2*10+int(version2[j]) j+=1 if n1<n2: return -1 elif n1>n2: return 1 i+=1 j+=1 return 0
compare-version-numbers
python3 || easy || solution
_soninirav
0
8
compare version numbers
165
0.354
Medium
2,626
https://leetcode.com/problems/compare-version-numbers/discuss/2097707/Python-Solution-O(n)-Time
class Solution: def compareVersion(self, version1: str, version2: str) -> int: list1 = version1.split('.') list2 = version2.split('.') list1 = [int(x) for x in list1] list2 = [int(x) for x in list2] l1 = len(list1) l2 = len(list2) if l1 > l2: for i in range(l1-l2): list2.append(0) else: for i in range(l2-l1): list1.append(0) if list1 > list2: return 1 elif list1 < list2: return -1 else: return 0
compare-version-numbers
Python Solution - O(n) Time
kn_vardhan
0
24
compare version numbers
165
0.354
Medium
2,627
https://leetcode.com/problems/compare-version-numbers/discuss/1970568/python-3-oror-simple-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: version1 = tuple(map(int, version1.split('.'))) version2 = tuple(map(int, version2.split('.'))) for revision1, revision2 in zip(version1, version2): if revision1 < revision2: return -1 if revision1 > revision2: return 1 m, n = len(version1), len(version2) if m < n: for i in range(m, n): if version2[i]: return -1 elif m > n: for i in range(n, m): if version1[i]: return 1 return 0
compare-version-numbers
python 3 || simple solution
dereky4
0
37
compare version numbers
165
0.354
Medium
2,628
https://leetcode.com/problems/compare-version-numbers/discuss/1918611/Python-Explanation-or-Clean-and-Simple-or-String-Split
class Solution: def compareVersion(self, version1, version2): v1, v2 = (list(map(int, v.split('.'))) for v in (version1, version2)) diff = abs(len(v1)-len(v2)) if diff > 0: v = min(v1,v2,key=len) v += [0] * diff return 1 if v1 > v2 else -1 if v2 > v1 else 0
compare-version-numbers
Python - Explanation | Clean and Simple | String Split
domthedeveloper
0
42
compare version numbers
165
0.354
Medium
2,629
https://leetcode.com/problems/compare-version-numbers/discuss/1918611/Python-Explanation-or-Clean-and-Simple-or-String-Split
class Solution: def compareVersion(self, version1, version2): v1, v2 = (list(map(int, v.split('.'))) for v in (version1, version2)) for a,b in zip_longest(v1,v2,fillvalue=0): if a != b: return 1 if a > b else -1 return 0
compare-version-numbers
Python - Explanation | Clean and Simple | String Split
domthedeveloper
0
42
compare version numbers
165
0.354
Medium
2,630
https://leetcode.com/problems/compare-version-numbers/discuss/1803095/Very-fast-Python-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: dot_1 = version1.count('.') dot_2 = version2.count('.') if dot_1 < dot_2: while version1.count('.') != version2.count('.'): version1 += ".0" elif dot_1 > dot_2: while version1.count('.') != version2.count('.'): version2 += ".0" version_1 = version1.split('.') version_2 = version2.split('.') version_1 = list(map(lambda x: int(x), version_1)) version_2 = list(map(lambda x: int(x), version_2)) for i, j in zip(version_1, version_2): if i < j: return -1 elif i > j: return 1 return 0
compare-version-numbers
Very fast Python solution
farhan_kapadia
0
43
compare version numbers
165
0.354
Medium
2,631
https://leetcode.com/problems/compare-version-numbers/discuss/1799416/PYTHON-very-easy-and-simple
class Solution: def compareVersion(self, version1: str, version2: str) -> int: #split by dot an get numbers into array v1 = [int(x) for x in version1.split('.')] v2 = [int(x) for x in version2.split('.')] #get max length m = max(len(v1), len(v2)) # make sure that both arrays would have the same length for x in range(m - len(v1)): v1.append(0) for x in range(m - len(v2)): v2.append(0) # compare numbers for i,x in enumerate(v1): if v1[i] > v2[i]: return 1 elif v1[i] < v2[i]: return -1 return 0
compare-version-numbers
PYTHON very easy and simple
m-s-dwh-bi
0
4
compare version numbers
165
0.354
Medium
2,632
https://leetcode.com/problems/compare-version-numbers/discuss/1799402/Python-Solution-Simple-Fast
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = version1.split('.') v2 = version2.split('.') v1 = [int(i) for i in v1] v2 = [int(i) for i in v2] lv1 = len(v1) lv2 = len(v2) length = min(lv1, lv2) if lv1<lv2: v1+= [0]*(lv2-length) else: v2+= [0]*(lv1-length) cnt = 0 while(cnt<len(v1)): if v1[cnt]<v2[cnt]: return -1 if v1[cnt]>v2[cnt]: return 1 cnt+=1 return 0 ```
compare-version-numbers
Python Solution Simple Fast
0sparsh2
0
6
compare version numbers
165
0.354
Medium
2,633
https://leetcode.com/problems/compare-version-numbers/discuss/1799392/python3-or-98.55-faster-with-proof
class Solution: def compareVersion(self, v1: str, v2: str) -> int: v1=v1.split(".") v2=v2.split(".") if len(v1)!=len(v2): if len(v1)<len(v2): v1.extend('0'*(len(v2)-len(v1))) else: v2.extend('0'*(len(v1)-len(v2))) # print(v1,v2) for i in range(len(v1)): if int(v1[i])<int(v2[i]): return -1 if int(v1[i])>int(v2[i]): return 1 return 0
compare-version-numbers
python3 | 98.55% faster with proof 🔥✔📌
Anilchouhan181
0
15
compare version numbers
165
0.354
Medium
2,634
https://leetcode.com/problems/compare-version-numbers/discuss/1798620/Python3-Solution-with-using-splitting
class Solution: def compareVersion(self, version1: str, version2: str) -> int: arr1 = version1.split('.') arr2 = version2.split('.') if len(arr1) > len(arr2): arr2 += ['0'] * (len(arr1) - len(arr2)) elif len(arr2) > len(arr1): arr1 += ['0'] * (len(arr2) - len(arr1)) for i in range(len(arr1)): part1 = int(arr1[i]) part2 = int(arr2[i]) if part1 < part2: return -1 elif part1 > part2: return 1 return 0
compare-version-numbers
[Python3] Solution with using splitting
maosipov11
0
13
compare version numbers
165
0.354
Medium
2,635
https://leetcode.com/problems/compare-version-numbers/discuss/1798294/Super-easy-Python-solution-EAFP-Style.-95-O(N)-time
class Solution: def compareVersion(self, version1: str, version2: str) -> int: version1 = version1.split('.') version2 = version2.split('.') len1 = len(version1) len2 = len(version2) larger_length = len1 if len1 > len2 else len2 for i in range(larger_length): try: v1 = int(version1[i]) except IndexError: # Default to 0 v1 = 0 try: v2 = int(version2[i]) except IndexError: # Default to 0 v2 = 0 if v1 < v2: return -1 elif v1 > v2: return 1 else: continue return 0
compare-version-numbers
Super easy Python solution, EAFP Style. 95% O(N) time
vineeth_moturu
0
9
compare version numbers
165
0.354
Medium
2,636
https://leetcode.com/problems/compare-version-numbers/discuss/1798100/Beginner-friendly-python3-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = list(map(int, version1.split("."))) v2 = list(map(int, version2.split("."))) for i, j in zip_longest(v1, v2, fillvalue = 0): if i<j: return -1 if i>j: return 1 return 0
compare-version-numbers
Beginner friendly python3 solution
HimanshuBhoir
0
9
compare version numbers
165
0.354
Medium
2,637
https://leetcode.com/problems/compare-version-numbers/discuss/1797596/Python-or-Very-Easy-Solution-or-Beginner-Friendly
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = list(map(int,version1.split('.'))) v2 = list(map(int,version2.split('.'))) v1_len = len(v1) v2_len = len(v2) for index in range(max(v1_len, v2_len)): num1 = v1[index] if index < v1_len else 0 num2 = v2[index] if index < v2_len else 0 if num1 > num2: return 1 elif num1 < num2: return -1 return 0
compare-version-numbers
Python | Very Easy Solution | Beginner Friendly
Call-Me-AJ
0
14
compare version numbers
165
0.354
Medium
2,638
https://leetcode.com/problems/compare-version-numbers/discuss/1797514/Python3-or-Simple-explanation-or-Faster-than-95-Memory-less-than-92.3
class Solution: def compareVersion(self, version1: str, version2: str) -> int: """Approach: First create an array of each version separated by .(dot) and then in case of different lengths of both arrays, append 0 (zeroes) to the smaller array and make both arrays of same length. Then iterate through both arrays and compare value at each index and return results accordingly. """ ## creating arrays by splitting by dot v1 = version1.split('.') v2 = version2.split('.') ## appending zeroes to smaller array till length of both arrays are equal if len(v1) != len(v2): diff = abs(len(v1) - len(v2)) for i in range(diff): if len(v1)> len(v2): v2.append('0') else: v1.append('0') ## Now iterate through both arrays and compare value at each index i = 0 j = 0 while i<len(v1): ## to prevent index out of range error if int(v1[i]) > int(v2[j]): return 1 elif int(v1[i]) < int(v2[j]): return -1 else: i+=1 j+=1 return 0
compare-version-numbers
Python3 | Simple explanation | Faster than 95%, Memory less than 92.3%
abhisheksharma5023
0
12
compare version numbers
165
0.354
Medium
2,639
https://leetcode.com/problems/compare-version-numbers/discuss/1797509/Python3-Split-and-compare
class Solution: def compareVersion(self, version1: str, version2: str) -> int: vr1_list = version1.split('.') vr2_list = version2.split('.') n1, n2 = len(vr1_list), len(vr2_list) if n1 < n2: vr1_list += ['0']*(n2-n1) elif n1 > n2: vr2_list += ['0']*(n1-n2) for x, y in zip(vr1_list, vr2_list): if int(x) < int(y): return -1 if int(x) > int(y): return 1 return 0
compare-version-numbers
[Python3] Split and compare
__PiYush__
0
12
compare version numbers
165
0.354
Medium
2,640
https://leetcode.com/problems/compare-version-numbers/discuss/1797504/Python-Simple-Python-Solution-Using-Iterative-Approach
class Solution: def compareVersion(self, version1: str, version2: str) -> int: version1 = version1.split('.') version2 = version2.split('.') i,j=0,0 length1 = len(version1) length2 = len(version2) while i < length1 or j < length2: revision1 = 0 revision2 = 0 if i < length1: revision1 = int(version1[i]) if j < length2: revision2 = int(version2[j]) if revision1 < revision2: return -1 if revision1 > revision2: return 1 i = i + 1 j = j + 1 return 0
compare-version-numbers
[ Python ] ✔✔ Simple Python Solution Using Iterative Approach 🔥✌
ASHOK_KUMAR_MEGHVANSHI
0
7
compare version numbers
165
0.354
Medium
2,641
https://leetcode.com/problems/compare-version-numbers/discuss/1694958/Python3-accepted-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = [int(i) for i in version1.split(".")] v2 = [int(i) for i in version2.split(".")] if(len(v1) < len(v2)): v1 = v1 + [0]*(len(v2) - len(v1)) elif(len(v2) < len(v1)): v2 = v2 + [0]*(len(v1) - len(v2)) for i in range(len(v1)): if(v1[i]>v2[i]): return 1 elif(v1[i]<v2[i]): return -1 return 0
compare-version-numbers
Python3 accepted solution
sreeleetcode19
0
48
compare version numbers
165
0.354
Medium
2,642
https://leetcode.com/problems/compare-version-numbers/discuss/1412709/easy-to-read-solution
class Solution: def compareVersion(self, version1: str, version2: str) -> int: a = version1.split(".") b = version2.split(".") low = min(len(a), len(b)) for i in range(low): if int(a[i]) >int(b[i]): return 1 if int(a[i]) < int(b[i]): return -1 if len(a)>len(b): for i in range(low, len(a)): if int(a[i]) >0: return 1 if len(b)>len(a): for i in range(low, len(b)): if int(b[i]) >0: return -1 return 0
compare-version-numbers
easy to read solution
Liquid_Snake
0
37
compare version numbers
165
0.354
Medium
2,643
https://leetcode.com/problems/compare-version-numbers/discuss/1191607/9-lines-python3-simple
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = [float(a) for a in version1.split('.')]; v2 = [float(a) for a in version2.split('.')] i = 0 while i < len(v1) or i < len(v2): if i >= len(v1): v1.append(0) if i >= len(v2): v2.append(0) if v1[i] < v2[i]: return -1 if v1[i] > v2[i]: return 1 i += 1 return 0
compare-version-numbers
9 lines python3 simple
mikekaufman4
0
73
compare version numbers
165
0.354
Medium
2,644
https://leetcode.com/problems/compare-version-numbers/discuss/839125/Python3-or-Using-Zip-or-Simplest
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = list(version1.split(".")) v2 = list(version2.split(".")) lv1 = len(v1) lv2 = len(v2) if lv1 > lv2 : for i in range(lv1-lv2): v2.append(str(0)) else: for i in range(lv2-lv1): v1.append(str(0)) for num1, num2 in zip(v1, v2): if int(num1) > int(num2) : return 1 elif int(num1) < int(num2) : return -1 return 0
compare-version-numbers
Python3 | Using Zip | Simplest
djrock007
0
18
compare version numbers
165
0.354
Medium
2,645
https://leetcode.com/problems/compare-version-numbers/discuss/837846/Easyway-Explanation-every-step
class Solution: def compareVersion(self, version1: str, version2: str) -> int: v1 = list(map(int, version1.split("."))) v2 = list(map(int, version2.split("."))) for i in range(max(len(v1),len(v2))): if i<len(v1): v1.append(0) if i<len(v2): v2.append(0) if v1[i] > v2[i]: return 1 elif v1[i] < v2[i]: return -1 return 0
compare-version-numbers
Easyway Explanation every step
paul_dream
0
16
compare version numbers
165
0.354
Medium
2,646
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/998707/Python-solution-with-detail-explanation
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator % denominator == 0: return str(numerator // denominator) prefix = '' if (numerator > 0) != (denominator > 0): prefix = '-' # Operation must be on positive values if numerator < 0: numerator = - numerator if denominator < 0: denominator = - denominator digit, remainder = divmod(numerator, denominator) res = prefix + str(digit) + '.' # EVERYTHING BEFORE DECIMAL table = {} suffix = '' while remainder not in table.keys(): # Store index of the reminder in the table table[remainder] = len(suffix) val, remainder = divmod(remainder*10, denominator) suffix += str(val) # No repeating if remainder == 0: return res + suffix indexOfRepeatingPart = table[remainder] decimalTillRepeatingPart = suffix[:indexOfRepeatingPart] repeatingPart = suffix[indexOfRepeatingPart:] return res + decimalTillRepeatingPart + '(' + repeatingPart + ')' s = Solution() print(s.fractionToDecimal(2, 3))
fraction-to-recurring-decimal
Python solution with detail explanation
imasterleet
3
650
fraction to recurring decimal
166
0.241
Medium
2,647
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/1668331/Python3-with-explanation-(Runtime-around-40ms-65ms)
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: neg = True if numerator/denominator < 0 else False numerator = -numerator if numerator < 0 else numerator denominator = -denominator if denominator < 0 else denominator out = str(numerator//denominator) if numerator % denominator: out += "." remainders = [] quotients = [] numerator %= denominator while numerator: numerator *= 10 if str(numerator) in remainders: duplicateStart = remainders.index(str(numerator)) out += "".join(quotients[:duplicateStart]) out += "("+"".join(quotients[duplicateStart:])+")" return "-"+out if neg else out else: remainders.append(str(numerator)) quotients.append(str(numerator // denominator)) numerator %= denominator out += "".join(quotients) return "-"+out if neg else out
fraction-to-recurring-decimal
Python3 - with explanation (Runtime around 40ms-65ms)
elainefaith0314
2
313
fraction to recurring decimal
166
0.241
Medium
2,648
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/1618999/A-fast-simple-and-easy-to-follow-Python-solution
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: # base case if numerator == 0: return '0' # result res = '' # positive and negative if (numerator > 0 and denominator < 0) or \ (numerator < 0 and denominator > 0): res += '-' # absolute value numerator, denominator = abs(numerator), abs(denominator) # remainder as zero res += str(numerator//denominator) numerator %= denominator if numerator == 0: return res # add a dot . res += '.' # hashmap to write down the starting index of a repeated remainder hashmap = {} hashmap[numerator] = len(res) while numerator != 0: # continue to mutiply by 10 numerator *= 10 res += str(numerator//denominator) numerator %= denominator # check if it finds a repeated pattern if numerator in hashmap: index = hashmap[numerator] res = res[:index] + '(' + res[index:] res += ')' break else: hashmap[numerator] = len(res) return res
fraction-to-recurring-decimal
A fast, simple, and easy-to-follow Python solution
WeixingZ
2
229
fraction to recurring decimal
166
0.241
Medium
2,649
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/2098202/Python-simple-solution
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: pre = "-" if numerator * denominator < 0 else "" numerator, denominator = abs(numerator), abs(denominator) q, r = divmod(numerator, denominator) q = str(q) if r == 0: return pre + q res = pre + q + "." dic = {} idx = len(res) r *= 10 while r > 0: if r in dic: return res[:dic[r]] + f"({res[dic[r]:]})" dic[r] = idx q, r = divmod(r, denominator) res += (q := str(q)) if r == 0: return res idx += len(q) r *= 10
fraction-to-recurring-decimal
Python simple solution
Takahiro_Yokoyama
1
226
fraction to recurring decimal
166
0.241
Medium
2,650
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/389300/Solution-in-Python-3-(beats-~99)-(eight-lines)
class Solution: def fractionToDecimal(self, n: int, d: int) -> str: if n % d == 0: return str(n//d) s, n, d, R, p = int(math.copysign(1,n*d)), abs(n), abs(d), {}, 2 A, (Q,n) = ['-'*(s < 0),str(n//d),'.'], divmod(n,d) while 1: (q,r) = divmod(n*10,d) if n in R: return "".join(A[:R[n]]+['(']+A[R[n]:]+[')']) R[n], n, p, _ = p + 1, r, p + 1, A.append(str(q)) if r == 0: return "".join(A) - Junaid Mansuri (LeetCode ID)@hotmail.com
fraction-to-recurring-decimal
Solution in Python 3 (beats ~99%) (eight lines)
junaidmansuri
1
1,200
fraction to recurring decimal
166
0.241
Medium
2,651
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/2733249/Python-Hashmap-Solution
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: fraction_added = False result = [] after_decimal = [] cur_result = result rem_map = {} rem_pos = 0 num_sign = 1 if numerator > 0 else -1 denom_sign = 1 if denominator > 0 else -1 numerator = abs(numerator) denominator = abs(denominator) current_remainder = numerator while current_remainder != 0: if fraction_added: if current_remainder in rem_map: after_decimal[rem_map[current_remainder]] = "(" + after_decimal[rem_map[current_remainder]] after_decimal[len(after_decimal) - 1] = after_decimal[len(after_decimal) - 1] + ")" break rem_map[current_remainder] = rem_pos if current_remainder < denominator: if len(result) == 0: result.append("0") if not fraction_added: cur_result = after_decimal fraction_added = True else: current_remainder *= 10 if current_remainder < denominator: cur_result.append("0") rem_pos += 1 continue times = current_remainder // denominator current_remainder = current_remainder % denominator cur_result.append(str(times)) if fraction_added: rem_pos += 1 if len(result) == 0 and len(after_decimal) == 0: return "0" if denom_sign * num_sign < 0: result[0] = "-" + result[0] if len(after_decimal) == 0: return "".join(result) return "".join(result) + "." + "".join(after_decimal)
fraction-to-recurring-decimal
Python Hashmap Solution
kummer
0
21
fraction to recurring decimal
166
0.241
Medium
2,652
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/2597256/Python-Readable-solution-with-short-explanation
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: # check whether is has to be negative result = "" if numerator*denominator >= 0 else "-" # make the absolute values numerator = abs(numerator) denominator = abs(denominator) # make the number before the comma number, numerator = divmod(numerator, denominator) result += str(number) # check whether we are finished if not numerator: return result # attach the point and make it a list, as we now will # append a lot of numbers and python is way faster # appending to a list versus adding to a string result += "." result = [result] # now make a dict to save which numbers we already encountered found = {} position = len(result) # now compute the numbers after comma and break, if we have zero # or already encountered the number while numerator and numerator not in found: # put current value in the dict found[numerator] = position # get the new number number, numerator = divmod(numerator*10, denominator) # attach the number result.append(str(number)) # increase digit coutner position += 1 # make the brackets if numerator in found: result.insert(found[numerator], '(') result.append(')') # construct the result return "".join(result)
fraction-to-recurring-decimal
[Python] - Readable solution with short explanation
Lucew
0
111
fraction to recurring decimal
166
0.241
Medium
2,653
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/1159925/Python3-easy-solution-with-explanation-99-efficient
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: ''' 1. If numerator is divisible by denominator, return the string format of numerator/denominator 2. Else, first check if the signs of the numerator and the denominator is opposite. If they are opposite, set the result string initially as "-" 3. Take the absolute values of numerator and denominator 4. Now while the remainder of numerator/denominator>0, add string of integer division (numerator*10)/denominator to result string. In each iteration set numerator=numerator%denominator. 5. Check whether any remainder has been appeared before. Use a map/dictionary to store the occurrence position of each remainder value 6. If any remainder value x has been previously found at index i, then insert "(" in index i-1 of the string and add ")" at the end of the string and return the string ''' if numerator%denominator==0: return str(numerator//denominator) #numerator is divisible by denominator, return string representation of integer division numerator/denominator result="" #stores the integer part if numerator<0 and denominator>0 or numerator>0 and denominator<0: result+="-" #signs are opposite, add "-" to result string numerator = abs(numerator) denominator=abs(denominator) #take absolute of both values result+=str(numerator//denominator)+"." #add integer part to the result string and a decimal sign decimal = "" remainders = {} #stores all the remainder occurrences k=0 #for getting the occurrence position of a remainder repeat_index=-1 #the index where any repeating remainder has first appeared while numerator>0: k+=1 numerator%=denominator #in each step set numerator as the remainder of numerator/denominator if numerator in remainders.keys(): repeat_index=remainders[numerator] #occurred before, get the first occurrence from the dictionary decimal=decimal[0:repeat_index-1]+"("+decimal[repeat_index-1:]+")" #add "(" at the first occurrence and ")" at the end break if numerator==0: break #remainder is divisible by denominator, don't need to check further remainders[numerator]=k #add the index of the remainder occurrence to the dictionary numerator*=10 #in each step numerator should be 10 times the remainder decimal+=str(numerator//denominator) #add string representation of the division to the string representation decimal portion return result+decimal
fraction-to-recurring-decimal
Python3 easy solution with explanation, 99% efficient
bPapan
0
251
fraction to recurring decimal
166
0.241
Medium
2,654
https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/1084845/fast-and-clean-python-code
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator*denominator<0: ans="-" else: ans="" q=abs(numerator)//abs(denominator) r=abs(numerator)%abs(denominator) d=set() decimal=[] if r==0: ans=ans+str(q) return ans else: flag=False while r!=0: if r not in d: n=r*10 q1=n//abs(denominator) d.add(r) decimal.append((q1,r)) r=n%abs(denominator) else: r1=r flag=True break ans+=str(q)+'.' if flag==False: for Q,R in decimal: ans+=str(Q) if flag==True: for i in range(0,len(decimal)): if decimal[i][1]!=r1: ans+=str(decimal[i][0]) else: break ans+='(' for x in range(i,len(decimal)): ans+=str(decimal[x][0]) ans+=')' return ans
fraction-to-recurring-decimal
fast and clean python code
sarthakraheja
0
628
fraction to recurring decimal
166
0.241
Medium
2,655
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2128459/Python-Easy-O(1)-Space
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i = 0 j = len(numbers) -1 while i<j: s = numbers[i] + numbers[j] if s == target: return [i + 1 , j + 1] if s > target: j-=1 else: i+=1 return []
two-sum-ii-input-array-is-sorted
Python Easy O(1) Space
constantine786
51
3,700
two sum ii input array is sorted
167
0.6
Medium
2,656
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2128459/Python-Easy-O(1)-Space
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i = 0 j = len(numbers) -1 while numbers[i] + numbers[j]!=target: s = numbers[i] + numbers[j] if s > target: j-=1 else: i+=1 return [i + 1 , j + 1]
two-sum-ii-input-array-is-sorted
Python Easy O(1) Space
constantine786
51
3,700
two sum ii input array is sorted
167
0.6
Medium
2,657
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {} for i, value in enumerate(nums): #1 remaining = target - nums[i] #2 if remaining in seen: #3 return [i, seen[remaining]] #4 else: seen[value] = i #5
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,658
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: seen = {} for i, value in enumerate(numbers): remaining = target - numbers[i] if remaining in seen: return [seen[remaining]+1, i+1] #4 else: seen[value] = i
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,659
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for left in range(len(numbers) -1): #1 right = len(numbers) - 1 #2 while left < right: #3 temp_sum = numbers[left] + numbers[right] #4 if temp_sum > target: #5 right -= 1 #6 elif temp_sum < target: #7 left +=1 #8 else: return [left+1, right+1] #9
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,660
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] for i in range(len(nums) -2): #1 if i > 0 and nums[i] == nums[i-1]: #2 continue left = i + 1 #3 right = len(nums) - 1 #4 while left < right: temp = nums[i] + nums[left] + nums[right] if temp > 0: right -= 1 elif temp < 0: left += 1 else: res.append([nums[i], nums[left], nums[right]]) #5 while left < right and nums[left] == nums[left + 1]: #6 left += 1 while left < right and nums[right] == nums[right-1]:#7 right -= 1 #8 right -= 1 #9 left += 1 #10
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,661
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue output_2sum = self.twoSum(nums[i+1:], -nums[i]) if output_2sum ==[]: continue else: for idx in output_2sum: instance = idx+[nums[i]] res.append(instance) output = [] for idx in res: if idx not in output: output.append(idx) return output def twoSum(self, nums, target): seen = {} res = [] for i, value in enumerate(nums): #1 remaining = target - nums[i] #2 if remaining in seen: #3 res.append([value, remaining]) #4 else: seen[value] = i #5 return res
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,662
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() results = [] self.helper(nums, target, 4, [], results) return results def helper(self, nums, target, N, res, results): if len(nums) < N or N < 2: #1 return if N == 2: #2 output_2sum = self.twoSum(nums, target) if output_2sum != []: for idx in output_2sum: results.append(res + idx) else: for i in range(len(nums) -N +1): #3 if nums[i]*N > target or nums[-1]*N < target: #4 break if i == 0 or i > 0 and nums[i-1] != nums[i]: #5 self.helper(nums[i+1:], target-nums[i], N-1, res + [nums[i]], results) def twoSum(self, nums: List[int], target: int) -> List[int]: res = [] left = 0 right = len(nums) - 1 while left < right: temp_sum = nums[left] + nums[right] if temp_sum == target: res.append([nums[left], nums[right]]) right -= 1 left += 1 while left < right and nums[left] == nums[left - 1]: left += 1 while right > left and nums[right] == nums[right + 1]: right -= 1 elif temp_sum < target: left +=1 else: right -= 1 return res
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,663
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/737095/Sum-MegaPost-Python3-Solution-with-a-detailed-explanation
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] candidates.sort() self.dfs(candidates, target, [], res) return res def dfs(self, candidates, target, path, res): if target < 0: return if target == 0: res.append(path) return res for i in range(len(candidates)): if i > 0 and candidates[i] == candidates[i-1]: #1 continue #2 self.dfs(candidates[i+1:], target - candidates[i], path+[candidates[i]], res) #3
two-sum-ii-input-array-is-sorted
Sum MegaPost - Python3 Solution with a detailed explanation
peyman_np
15
415
two sum ii input array is sorted
167
0.6
Medium
2,664
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/368501/Python-solution-O(1)-memory
class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ low, high = 0, len(numbers) - 1 while low < high: sum = numbers[low] + numbers[high] if sum > target: high -= 1 elif sum == target: return [low + 1, high + 1] else: low += 1
two-sum-ii-input-array-is-sorted
Python solution O(1) memory
amchoukir
13
1,700
two sum ii input array is sorted
167
0.6
Medium
2,665
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2191053/Python3-simplest-solution-O(log-N)-and-O(1)-space
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start,end = 0, len(numbers)-1 while start<=end: sums = numbers[start]+numbers[end] if(sums == target): return [start+1, end+1] if(sums < target): start+=1 else: end-=1 return [start+1,end+1]
two-sum-ii-input-array-is-sorted
📌 Python3 simplest solution O(log N) and O(1) space
Dark_wolf_jss
6
107
two sum ii input array is sorted
167
0.6
Medium
2,666
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1749544/Python-Simple-and-Clean-Python-Solution-Using-Two-Pointer-Approach
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: low = 0 high = len(numbers)-1 while low < high: if numbers[low]+numbers[high] < target: low = low + 1 elif numbers[low]+numbers[high] > target: high = high - 1 else: return [low+1, high+1]
two-sum-ii-input-array-is-sorted
[ Python ] ✔✔ Simple and Clean Python Solution Using Two Pointer Approach
ASHOK_KUMAR_MEGHVANSHI
6
374
two sum ii input array is sorted
167
0.6
Medium
2,667
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1559850/Python-O(n)-time-and-O(1)-space-explained.-Beats-90
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # hash map: O(n), O(n) # two pointers: O(N), O(1) # binary search: O(nlogn), O(1) left_pointer, right_pointer = 0, len(nums) - 1 # setting left and right pointers while left_pointer < right_pointer: # while the right pointer remains on the right of the left if nums[left_pointer] + nums[right_pointer] == target: # return indexes if corresponding num has been found return left_pointer + 1, right_pointer + 1 else: # check if sum is greater than or less than target if nums[left_pointer] + nums[right_pointer] > target: right_pointer -= 1 # if it is greater than, lowering the right pointer will lower the sum, as the num next to it is guaranteed to be smaller else: left_pointer += 1 # same concept as before, but this time making the sum larger # O(N) time, O(1) aux space # O(N) worst case # O(1) best case
two-sum-ii-input-array-is-sorted
Python O(n) time and O(1) space, explained. Beats 90%
mateoruiz5171
4
504
two sum ii input array is sorted
167
0.6
Medium
2,668
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/440030/Beats-98-in-run-time-and-100-in-memory.
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: dic = {} #collection for i, v in enumerate(numbers): if (target - v) in dic: break #find the pair present in dic. else: dic[v] = i+1 #Making a collection of 1st pair. return sorted([dic[target - v],i+1])
two-sum-ii-input-array-is-sorted
Beats 98% in run time and 100% in memory.
sudhirkumarshahu80
4
503
two sum ii input array is sorted
167
0.6
Medium
2,669
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2331529/Python-Simple-Python-Solution-Using-Two-Approach
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: low = 0 high = len(numbers)-1 while low < high: if numbers[low] + numbers[high] == target: return [low+1, high+1] elif numbers[low] + numbers[high] < target: low = low + 1 elif numbers[low] + numbers[high] > target: high = high - 1
two-sum-ii-input-array-is-sorted
[ Python ] ✅✅ Simple Python Solution Using Two Approach 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
3
158
two sum ii input array is sorted
167
0.6
Medium
2,670
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2331529/Python-Simple-Python-Solution-Using-Two-Approach
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: for i in range(len(numbers)): t=target-numbers[i] if t in numbers[i+1:]: index = numbers[i+1:].index(t) + i + 1 return [i + 1, index + 1]
two-sum-ii-input-array-is-sorted
[ Python ] ✅✅ Simple Python Solution Using Two Approach 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
3
158
two sum ii input array is sorted
167
0.6
Medium
2,671
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1764404/Python-3-(200ms)-or-Binary-Search-Approach-or-Easy-to-Understand
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: k,s,m,e=0,0,0,len(numbers)-1 res=[] for i in range(len(numbers)): k=target-numbers[i] s,e=i+1,len(numbers)-1 while s<=e: m=s+(e-s)//2 if numbers[m]==k: return [i+1,m+1] elif numbers[m]>k: e=m-1 else: s=m+1
two-sum-ii-input-array-is-sorted
Python 3 (200ms) | Binary Search Approach | Easy to Understand
MrShobhit
3
359
two sum ii input array is sorted
167
0.6
Medium
2,672
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1259554/Two-Pointer-Solution-or-O(n2)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start = 0 end = len(numbers) - 1 while start < end: if numbers[start] + numbers[end] < target: start += 1 elif numbers[start] + numbers[end] > target: end -= 1 else: return [start+1, end+1]
two-sum-ii-input-array-is-sorted
Two Pointer Solution | O(n/2)
Shoaib0023
3
233
two sum ii input array is sorted
167
0.6
Medium
2,673
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2129112/Python-Solution-or-Explained-or-For-Beginners
class Solution: def twoSum(self, a: List[int], x: int) -> List[int]: i = 0 j = len(a) - 1 while i < j: if a[i] + a[j] == x: return [i+1, j+1] elif (a[i] + a[j] > x): j -= 1 else: i += 1
two-sum-ii-input-array-is-sorted
Python Solution | Explained | For Beginners
irapandey
2
42
two sum ii input array is sorted
167
0.6
Medium
2,674
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1982058/Efficient-Two-pointers-python-solution-with-explanation
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: l, r = 0, len(nums) - 1 while l < r : currSum = nums[l] + nums [r] if currSum > target: r -= 1 elif currSum < target: l += 1 else: return[l + 1, r + 1]
two-sum-ii-input-array-is-sorted
Efficient Two pointers python solution with explanation
nikhitamore
2
104
two sum ii input array is sorted
167
0.6
Medium
2,675
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1542751/Python-Simple-Solution
class Solution: def twoSum(self, nums: List[int], k: int) -> List[int]: i, j = 0, len(nums)-1 while (nums[i] + nums[j]) != k: if (nums[i] + nums[j]) > k: j-=1 else: i+=1 else: return [i+1, j+1]
two-sum-ii-input-array-is-sorted
Python Simple Solution
aaffriya
2
302
two sum ii input array is sorted
167
0.6
Medium
2,676
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1492584/Python-Two-pointer-solution-99-Faster
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: first = 0 last = len(numbers) - 1 while first <= last: if numbers[first] + numbers[last] == target: return [first+1, last+1] elif numbers[first] + numbers[last] > target: last -= 1 else: first += 1
two-sum-ii-input-array-is-sorted
Python Two pointer solution 99% Faster
yugalshah
2
140
two sum ii input array is sorted
167
0.6
Medium
2,677
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1392564/2-pointer-solution-in-Python-3.8%2B
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: lo, hi = 0, len(numbers)-1 while (s := sum((numbers[lo], numbers[hi]))) != target: if s > target: hi -= 1 else: lo += 1 return [lo+1, hi+1]
two-sum-ii-input-array-is-sorted
2-pointer solution in Python 3.8+
mousun224
2
74
two sum ii input array is sorted
167
0.6
Medium
2,678
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2809648/Python-oror-2-pointers-oror-O(N)
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: i = 0 j = len(nums) - 1 while i < j: if (nums[i] + nums[j]) == target: return [i+1 ,j+1] elif (nums[i] + nums[j]) < target: i += 1 else: j -= 1
two-sum-ii-input-array-is-sorted
Python || 2 pointers || O(N)
chithra-m
1
13
two sum ii input array is sorted
167
0.6
Medium
2,679
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2428054/easy-python-code-or-O(n)-or-Two-Pointer
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i,j = 0,len(numbers)-1 while(True): if numbers[i]+numbers[j] < target: i += 1 elif numbers[i]+numbers[j] > target: j -= 1 else: return [i+1,j+1]
two-sum-ii-input-array-is-sorted
easy python code | O(n) | Two Pointer
dakash682
1
106
two sum ii input array is sorted
167
0.6
Medium
2,680
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2313372/Easy-python3-solution-with-hashset(updated)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: return [l + 1, r + 1]
two-sum-ii-input-array-is-sorted
Easy python3 solution with hashset(updated)
__Simamina__
1
15
two sum ii input array is sorted
167
0.6
Medium
2,681
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2273995/simple-python3-solution
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: return [l + 1, r + 1]
two-sum-ii-input-array-is-sorted
simple python3 solution
__Simamina__
1
48
two sum ii input array is sorted
167
0.6
Medium
2,682
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2131108/Python3-or-Simple-Solution-with-Sets
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: x = list(set(numbers)) x.sort() for i in range(len(x)): y = target - x[i] if y in x[i+1:]: return [numbers.index(x[i]) + 1, numbers.index(y) + 1] elif y == x[i]: return [numbers.index(x[i]) + 1, numbers.index(x[i]) + 2]
two-sum-ii-input-array-is-sorted
Python3 | Simple Solution with Sets
firebat75
1
37
two sum ii input array is sorted
167
0.6
Medium
2,683
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1947460/Python3-Simple-two-pointer-O(1)-space-solution-for-sorted-array
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start = 0 end = len(numbers) - 1 sum = 0 while (start < end): sum = numbers[start] + numbers[end] if (sum == target): return [start+1, end+1] elif (sum < target): start += 1 elif (sum > target): end -= 1 return [-1, -1]
two-sum-ii-input-array-is-sorted
[Python3] Simple two pointer O(1) space solution for sorted array
leqinancy
1
75
two sum ii input array is sorted
167
0.6
Medium
2,684
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1914285/Easy-and-Fast-Solution-in-Python-using-dictHashMap-T.C-greaterO(n)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: h={} for i in range(len(numbers)): if numbers[i] in h: return h[numbers[i]]+1,i+1 else: h[target-numbers[i]]=i return -1
two-sum-ii-input-array-is-sorted
Easy and Fast Solution in Python using dict/HashMap T.C->O(n)
karansinghsnp
1
76
two sum ii input array is sorted
167
0.6
Medium
2,685
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1883715/Python3-Two-Pointers-Approach
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start, end = 0, len(numbers) - 1 numsSum = 0 while start != end: numsSum = numbers[start] + numbers[end] if numsSum == target: return [start+1, end+1] elif numsSum > target: end -= 1 else: start += 1
two-sum-ii-input-array-is-sorted
Python3 - Two Pointers Approach
eliasroodrigues
1
60
two sum ii input array is sorted
167
0.6
Medium
2,686
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1804665/Two-pointer-Solution-Python
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start = 0 end = len(numbers)-1 while (start<end): curr_sum = numbers[start]+numbers[end] if curr_sum == target: return [start+1, end+1] elif curr_sum >target: end-=1 else: start+=1
two-sum-ii-input-array-is-sorted
Two pointer Solution Python
Tobi_Akin
1
90
two sum ii input array is sorted
167
0.6
Medium
2,687
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1760418/Easy-Two-Pointers-Solution
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: left,right = 0,len(numbers)-1 while left<right: sum = numbers[left]+numbers[right] if sum==target: return [left+1,right+1] elif sum>target: right -= 1 else: left += 1
two-sum-ii-input-array-is-sorted
Easy Two-Pointers Solution
lior1509
1
80
two sum ii input array is sorted
167
0.6
Medium
2,688
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1526000/super-fast-hashmap-solution-(better-than-2-pointers)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: dict_ = {} for i, num in enumerate(numbers): delta = target - num if delta in dict_.keys(): return [dict_[delta]+1, i+1] dict_[num] = i
two-sum-ii-input-array-is-sorted
super fast hashmap solution (better, than 2 pointers)
alcherniaev
1
146
two sum ii input array is sorted
167
0.6
Medium
2,689
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/1421255/my-py-sol
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d={} for i in range(0,len(nums)): s=(target-nums[i]) if s in d: if d[s]>i: return [i+1,d[s]] else: return [d[s],i+1] else: d[nums[i]]=i+1
two-sum-ii-input-array-is-sorted
my py sol
minato_namikaze
1
104
two sum ii input array is sorted
167
0.6
Medium
2,690
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/965360/My-Simple-Python-Go-Solution
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: if len(numbers) == 2: return [1,2] s = 0 e = len(numbers)-1 res = 0 while True: res = numbers[s]+numbers[e] if target == res: return [s+1,e+1] elif target < res: e-=1 elif target > res: s+=1
two-sum-ii-input-array-is-sorted
My Simple Python , Go Solution
miryang
1
390
two sum ii input array is sorted
167
0.6
Medium
2,691
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/770624/Python3-Beats-93-O(n)-where-n-len(num)-index2-%2B-index1
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i = 0 l = len(numbers) - 1 while i < l: n = numbers[i] + numbers[l] if n < target: i += 1 if n > target: l -= 1 if n == target: return [i+1,l+1]
two-sum-ii-input-array-is-sorted
Python3 - Beats 93% O(n) where n = len(num)-index2 + index1
yestannn
1
281
two sum ii input array is sorted
167
0.6
Medium
2,692
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/520458/Python-two-idx-solution
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # initialize our indices left = 0 right = len(numbers) - 1 # iterate through the array while left < right: sum = numbers[left] + numbers[right] if sum == target: # if two elements are equal, # we found the solution! return [left+1, right+1] elif sum > target: # if the sum is bigger than the target, # we decrease the right index by one right -= 1 elif sum < target: # if the sum is less than the target, # we increase the left index by one left += 1
two-sum-ii-input-array-is-sorted
Python two idx solution
biostat527
1
317
two sum ii input array is sorted
167
0.6
Medium
2,693
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2843017/two-pointers
class Solution: def twoSum(self, a: List[int], t: int) -> List[int]: i=0;j=len(a)-1 while(i<j): if(a[i]+a[j]<t): i+=1 elif(a[i]+a[j]>t): j-=1 else: return [i+1,j+1]
two-sum-ii-input-array-is-sorted
two pointers
harshitatangudu20
0
2
two sum ii input array is sorted
167
0.6
Medium
2,694
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2839987/Two-Sum-II-Input-Array-Is-Sorted-or-Pythin-3.x-or-Two-pointers
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: head = 0 tail = len(numbers) - 1 while tail != head: summ = numbers[head] + numbers[tail] if summ == target: return [head + 1, tail + 1] if summ > target: tail -= 1 else: head += 1
two-sum-ii-input-array-is-sorted
Two Sum II - Input Array Is Sorted | Pythin 3.x | Two pointers
SnLn
0
2
two sum ii input array is sorted
167
0.6
Medium
2,695
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2839435/Python-Easy-Approach
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: prev = {} for i,n in enumerate(numbers): diff = target - n if diff in prev: return [prev[diff]+1, i+1] prev[n] = i
two-sum-ii-input-array-is-sorted
Python Easy Approach
aryanzzzz
0
1
two sum ii input array is sorted
167
0.6
Medium
2,696
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2838106/two-pointer-solution-time-O(n)-space-O(1)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: i = 0 j = len(numbers) - 1 while i < j: if numbers[i] + numbers[j] == target: return [i+1, j+1] if numbers[i] + numbers[j] < target: i += 1 else: j -= 1
two-sum-ii-input-array-is-sorted
two pointer solution time O(n) , space O(1)
sintin1310
0
3
two sum ii input array is sorted
167
0.6
Medium
2,697
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2838093/python-solution-with-comments-and-time-O(n)-space-O(1)
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: pos_hash=[[0 , -1] for i in range(1002)] neg_hash=[[0 , -1] for i in range(1002)] for i in range(len(numbers)): left=target-numbers[i] //checking if the left over is a nev then neg_hash // if positive then checking in pos_hash if left<0: if neg_hash[left][0]>0: return [neg_hash[left][1]+1 , i+1] else: if pos_hash[left][0]>0: return [pos_hash[left][1]+1 , i+1] // this is putting the -ve numbers[i] in neg_hash // and +ve number[i] in pos_hash if numbers[i]<0: neg_hash[numbers[i]][0]+=1 neg_hash[numbers[i]][1]=i else: pos_hash[numbers[i]][0]+=1 pos_hash[numbers[i]][1]=i return -1
two-sum-ii-input-array-is-sorted
python solution with comments and time O(n) space O(1)
sintin1310
0
3
two sum ii input array is sorted
167
0.6
Medium
2,698
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2836961/Python-or-2-Pointer-or-Comments
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers)-1 while l < r: # they can never equal each other as that means that it is using the same element left = numbers[l] right = numbers[r] total = left + right if total == target: return [l+1, r+1] if total > target: # if the sum we calculated is too large, decrement right pointer (since it's sorted we can do this) r -= 1 else: # if total < target. if the sum we calc'd is too little, incrementing the left pointer will make the sum bigger (which is what we need to do) l += 1
two-sum-ii-input-array-is-sorted
🎉Python | 2 Pointer | Comments
Arellano-Jann
0
1
two sum ii input array is sorted
167
0.6
Medium
2,699