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/intersection-of-two-arrays-ii/discuss/2127122/two-pointer-and-hashmap | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
hmap1, hmap2 = {n: nums1.count(n) for n in set(nums1)}, {n: nums2.count(n) for n in set(nums2)}
res = []
for n in hmap1:
if n in hmap2:
res += [n] * min(hmap1[n], hmap2[n])
return res | intersection-of-two-arrays-ii | two pointer & hashmap | andrewnerdimo | 1 | 234 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,200 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2068093/Easy-to-understand-Python-solution! | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
res=[]
if(len(nums1)>len(nums2)):
biggest_arr = nums1
smallest_arr = nums2
else:
biggest_arr = nums2
smallest_arr = nums1
for num in biggest_arr:
if num in smallest_arr:
res.append(num)
smallest_arr.remove(num)
return res; | intersection-of-two-arrays-ii | Easy to understand Python solution! | TheSkrill | 1 | 149 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,201 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1958430/Python3-Solutions-Two-Pointers-and-Hashmap | # Solution 1: Two-Pointer
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
i = 0
j = 0
res = []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
res += [nums1[i]]
i += 1
j += 1
return res
# Solution 2: Hash Map
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
hashmap = {}
res = []
for x in nums1:
if x not in hashmap:
hashmap[x] = 1
else:
hashmap[x] += 1
for y in nums2:
if y in hashmap and hashmap[y] > 0:
res += [y]
hashmap[y] -= 1
return res | intersection-of-two-arrays-ii | Python3 Solutions Two-Pointers and Hashmap | Mr_Watermelon | 1 | 71 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,202 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1855295/Python-Simple-and-Elegant! | class Solution(object):
def intersect(self, nums1, nums2):
ans = []
d1, d2 = {}, {}
for n in nums1:
if n not in d1:
d1[n] = 1
else:
d1[n] += 1
for n in nums2:
if n not in d2:
d2[n] = 1
else:
d2[n] += 1
for k in d1:
if k in d2:
for i in range(min(d1[k],d2[k])):
ans.append(k)
return ans | intersection-of-two-arrays-ii | Python - Simple and Elegant! | domthedeveloper | 1 | 176 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,203 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1855295/Python-Simple-and-Elegant! | class Solution(object):
def intersect(self, nums1, nums2):
ans = []
c1, c2 = Counter(nums1), Counter(nums2)
for k in c1:
if k in c2:
for i in range(min(c1[k],c2[k])):
ans.append(k)
return ans | intersection-of-two-arrays-ii | Python - Simple and Elegant! | domthedeveloper | 1 | 176 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,204 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1855295/Python-Simple-and-Elegant! | class Solution(object):
def intersect(self, nums1, nums2):
return (Counter(nums1) & Counter(nums2)).elements() | intersection-of-two-arrays-ii | Python - Simple and Elegant! | domthedeveloper | 1 | 176 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,205 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1724336/Python-Easiest-Solutionoror-Beg-to-Adv-oror-Two-pointer | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
res = []
nums1, nums2 = sorted(nums1), sorted(nums2)
p1, p2 = 0 , 0
while p1 < len(nums1) and p2 < len(nums2):
if nums1[p1] < nums2[p2]:
p1 += 1
elif nums1[p1] > nums2[p2]:
p2 += 1
else:
res.append(nums1[p1])
p1 += 1
p2 += 1
return res | intersection-of-two-arrays-ii | Python Easiest Solution|| Beg to Adv || Two pointer | rlakshay14 | 1 | 124 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,206 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1614836/Very-Easy-Short-and-Understandable-Python | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
output = []
for num in nums1:
if num in nums2:
output.append(num)
nums2.remove(num)
return output | intersection-of-two-arrays-ii | Very Easy, Short and Understandable Python | gg21aping | 1 | 184 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,207 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1555931/simple-python-solutioneasy-to-understand | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums=[]
if(len(nums1)<len(nums2)):
n=nums1
k=nums2
else:
n=nums2
k=nums1
for i in n:
if(i in k):
nums.append(i)
k.remove(i)
return nums | intersection-of-two-arrays-ii | simple python solution,easy to understand | srinath1reddy | 1 | 112 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,208 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1471828/Python-5-lines-using-sets | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
sameNums = set(nums1) & set(nums2)
ans = []
for num in sameNums:
ans.extend([num] * min(nums1.count(num), nums2.count(num)))
return ans | intersection-of-two-arrays-ii | Python 5 lines using sets | SmittyWerbenjagermanjensen | 1 | 247 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,209 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1468829/Python3-freq-table | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
return (Counter(nums1) & Counter(nums2)).elements() | intersection-of-two-arrays-ii | [Python3] freq table | ye15 | 1 | 45 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,210 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1468829/Python3-freq-table | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
freq = Counter(nums1) & Counter(nums2)
return sum(([k]*v for k, v in freq.items()), []) | intersection-of-two-arrays-ii | [Python3] freq table | ye15 | 1 | 45 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,211 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1468829/Python3-freq-table | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
freq = defaultdict(int)
for x in nums1: freq[x] += 1
for x in nums2:
if freq[x]:
freq[x] -= 1
ans.append(x)
return ans | intersection-of-two-arrays-ii | [Python3] freq table | ye15 | 1 | 45 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,212 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1468829/Python3-freq-table | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
i = j = 0
ans = []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]: i += 1
elif nums1[i] > nums2[j]: j += 1
else:
ans.append(nums1[i])
i += 1
j += 1
return ans | intersection-of-two-arrays-ii | [Python3] freq table | ye15 | 1 | 45 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,213 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1436940/Python3-oror-EASY-4-LINE-USING-DICTIONARY | class Solution:
from collections import Counter
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1d, nums2d, res = Counter(nums1), Counter(nums2), []
for k, v in nums2d.items():
if k in nums1d: res += [k] * min(v, nums1d[k])
return res | intersection-of-two-arrays-ii | Python3 || EASY 4-LINE USING DICTIONARY | shadowcatlegion | 1 | 114 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,214 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1379042/Two-lines-with-Counter()-99-speed | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
cnt1, cnt2 = Counter(nums1), Counter(nums2)
return sum([[k] * min(n, cnt2[k]) for k, n in cnt1.items()
if k in cnt2], []) | intersection-of-two-arrays-ii | Two lines with Counter(), 99% speed | EvgenySH | 1 | 342 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,215 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1369926/Easy-Fast-Python-O(n)-Solution | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
d = {}
final = []
for i in nums1:
if i not in d:
d[i] = 1
else:
d[i] += 1
for i in nums2:
if i in d:
if d[i] > 1:
d[i] -= 1
else:
del d[i]
final.append(i)
return final | intersection-of-two-arrays-ii | Easy, Fast, Python O(n) Solution | the_sky_high | 1 | 587 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,216 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1220391/Python3easy-and-clear | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
L = []
for i in nums1:
if i in nums2:
L.append(i)
nums2.pop(nums2.index(i))
return L | intersection-of-two-arrays-ii | 【Python3】easy & clear | qiaochow | 1 | 130 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,217 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1178414/Python3-simple-and-easy-to-understand-solution-using-set | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
l = set(nums1).intersection(set(nums2))
res = []
for i in l:
res += [i] * min(nums1.count(i),nums2.count(i))
return res | intersection-of-two-arrays-ii | Python3 simple and easy to understand solution using set | EklavyaJoshi | 1 | 66 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,218 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/930361/Simple!!-6-lines-Runtime%3A-72-ms-faster-than-20.45-of-Python3 | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
for ele in nums1:
if ele in nums2:
stack.append(ele)
nums2.pop(nums2.index(ele))
return stack | intersection-of-two-arrays-ii | Simple!! 6 lines, Runtime: 72 ms, faster than 20.45% of Python3 | wasato89 | 1 | 134 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,219 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/810897/python-Two-pointers-faster-than-99 | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
i, j = 0, 0
n1 = len(nums1)
n2 = len(nums2)
nums1_s = sorted(nums1)
nums2_s = sorted(nums2)
res = []
while i < n1 and j < n2:
if nums1_s[i] < nums2_s[j]:
i += 1
elif nums1_s[i] > nums2_s[j]:
j += 1
else:
res.append(nums1_s[i])
i += 1
j += 1
return res | intersection-of-two-arrays-ii | python Two pointers -- faster than 99% | 221Baker | 1 | 328 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,220 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/428496/Python-Beginner%3A-use-simple-list-methods | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
result = []
for i in nums1:
if i in nums2:
nums2.remove(i)
result.append(i)
return result | intersection-of-two-arrays-ii | Python Beginner: use simple list methods | Mint | 1 | 102 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,221 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/374818/Python-2-Solutions-(Dictionary-No-Dictionary) | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
d = {}
for n in nums1:
if n in d: d[n] += 1
else: d[n] = 1
res = []
nums2.sort()
for n in nums2:
if n in d and d[n] > 0:
d[n] -= 1
res.append(n)
return res | intersection-of-two-arrays-ii | Python - 2 Solutions (Dictionary / No Dictionary) | nuclearoreo | 1 | 425 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,222 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/374818/Python-2-Solutions-(Dictionary-No-Dictionary) | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
i = j = 0
res = []
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]: i += 1
elif nums1[i] > nums2[j]: j += 1
else:
res.append(nums1[i])
j += 1
i += 1
return res | intersection-of-two-arrays-ii | Python - 2 Solutions (Dictionary / No Dictionary) | nuclearoreo | 1 | 425 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,223 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2846109/python3 | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
d = {} # store freq of nums in nums1
# store freq
for n in nums1:
if n in d:
d[n] += 1
else:
d[n] = 1
ans = [] # answer
# compare freq of nums1 to that of nums1
for n in nums2:
# if # of n in nums1 is currently less than that of nums2
if (n in d) and (d[n] > 0):
ans.append(n)
d[n] -= 1
return ans | intersection-of-two-arrays-ii | python3 | wduf | 0 | 2 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,224 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2834150/Time%3A-Beats-99.14-Python-solution | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
h={}
l=[]
for e in nums2:
if e in h:
h[e]+=1
else:
h[e]=1
for e in nums1:
if h.get(e,0)>0:
l.append(e)
h[e]-=1
return l | intersection-of-two-arrays-ii | Time: Beats 99.14% Python solution | sbhupender68 | 0 | 2 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,225 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2832784/The-simplest-way | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
intersect = []
for i in nums1:
if i in nums2:
intersect.append(i)
nums2.remove(i)
return intersect | intersection-of-two-arrays-ii | The simplest way | miko2823 | 0 | 4 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,226 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2829469/Python-simple-and-easy-understanding-solution-with-comments | class Solution(object):
def intersect(self, nums1, nums2):
res = []
# iterate shorter arr
if len(nums1) < len(nums2):
for num in nums1:
if num in nums2:
# append the el in new arr
res.append(num)
# remove the element from the longer array
nums2.remove(num)
else:
for num in nums2:
if num in nums1:
# append the el in new arr
res.append(num)
# remove the element from the longer array
nums1.remove(num)
return res | intersection-of-two-arrays-ii | Python simple and easy-understanding solution with comments | yutoun | 0 | 2 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,227 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2818381/Easy-Python-Solution | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
l=[]
for i in nums1:
if i in nums2:
l.append(i)
nums2.remove(i)
return (l) | intersection-of-two-arrays-ii | Easy Python Solution | sanskrutidube | 0 | 2 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,228 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2815633/Beats-98or-Dictionaryor-Python | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
output = {}
returnarray=[]
for item in nums1:
if item in output.keys():
output[item]=output[item]+1
else:
output[item]=1
for item in nums2:
if item in output.keys() and output[item]!=0:
output[item]=output[item]-1
returnarray.append(item)
return returnarray | intersection-of-two-arrays-ii | Beats 98%| Dictionary| Python | siddharthchoudhary41 | 0 | 3 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,229 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2810224/TC-%3A-97.86-Python-simple-solution | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
i, j = 0, 0
res = []
nums1.sort()
nums2.sort()
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
j += 1
continue
if nums1[i] > nums2[j]:
j += 1
else:
i += 1
return res | intersection-of-two-arrays-ii | 😎 TC : 97.86% Python simple solution | Pragadeeshwaran_Pasupathi | 0 | 5 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,230 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2804634/Easy-solution-Python | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
p=[]
for i in nums1:
if i in nums2:
p.append(i)
nums2.remove(i)
return p | intersection-of-two-arrays-ii | Easy solution Python | priyanshupriyam123vv | 0 | 2 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,231 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2791122/python-solution | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
from collections import Counter
a = Counter(nums1)
b = Counter(nums2)
return list((a & b).elements()) | intersection-of-two-arrays-ii | python solution | radhikapadia31 | 0 | 3 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,232 |
https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/2790248/Easily-Understandable-Solution-by-Python | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums = []
n1 = len(nums1)
n2 = len(nums2)
loc1= []
loc2= []
for i in range(n1):
loc1.append(0)
for j in range(n2):
loc2.append(0)
for i in range(n1):
for j in range(n2):
if nums1[i] == nums2[j] and loc1[i]==0 and loc2[j]==0:
nums.append(nums1[i])
loc1[i] = 1
loc2[j] = 1
return nums | intersection-of-two-arrays-ii | Easily Understandable Solution by Python | fatin_istiaq | 0 | 3 | intersection of two arrays ii | 350 | 0.556 | Easy | 6,233 |
https://leetcode.com/problems/russian-doll-envelopes/discuss/2071626/Python-LIS-based-approach | class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x: (x[0], -x[1]))
res = []
# Perform LIS
for _, h in envelopes:
l,r=0,len(res)-1
# find the insertion point in the Sort order
while l <= r:
mid=(l+r)>>1
if res[mid]>=h:
r=mid-1
else:
l=mid+1
idx = l
if idx == len(res):
res.append(h)
else:
res[idx]=h
return len(res) | russian-doll-envelopes | Python LIS based approach | constantine786 | 19 | 1,800 | russian doll envelopes | 354 | 0.382 | Hard | 6,234 |
https://leetcode.com/problems/russian-doll-envelopes/discuss/2071626/Python-LIS-based-approach | class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x: (x[0], -x[1]))
res = []
for _, h in envelopes:
idx = bisect_left(res, h)
if idx == len(res):
res.append(h)
else:
res[idx]=h
return len(res) | russian-doll-envelopes | Python LIS based approach | constantine786 | 19 | 1,800 | russian doll envelopes | 354 | 0.382 | Hard | 6,235 |
https://leetcode.com/problems/russian-doll-envelopes/discuss/2554573/python-oror-dp-oror-bisect-oror-short-n-sweet-explanation | class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x:(x[0],-x[1]))
dp=[]
for _,h in envelopes:
index = bisect.bisect_left(dp,h)
if index < len(dp):
dp[index] = h
else:
dp.append(h)
return len(dp) | russian-doll-envelopes | python || dp || bisect || short n sweet explanation | Kurdush | 0 | 74 | russian doll envelopes | 354 | 0.382 | Hard | 6,236 |
https://leetcode.com/problems/russian-doll-envelopes/discuss/2182158/LIS-Approach-oror-Binary-Search-oror-Custom-Sorting | class Solution:
def binarySearch(self, array, target):
left = 0
right = len(array) - 1
while left <= right:
mid = left + (right - left)//2
if array[mid] == target:
return mid
elif array[mid] > target:
right = mid - 1
else:
left = mid + 1
return left
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes = sorted(envelopes, key = lambda x : [x[0], -x[1]])
lis = []
for width, height in envelopes:
left = self.binarySearch(lis, height)
if left == len(lis):
lis.append(height)
else:
lis[left] = height
return len(lis) | russian-doll-envelopes | LIS Approach || Binary Search || Custom Sorting | Vaibhav7860 | 0 | 271 | russian doll envelopes | 354 | 0.382 | Hard | 6,237 |
https://leetcode.com/problems/russian-doll-envelopes/discuss/2072168/Python-or-Binary-Search | class Solution:
def maxEnvelopes(self, en: List[List[int]]) -> int:
def bs(t,n,v):
i = 0
j = n-1
while i<=j:
m = (i+j)//2
if t[m][1] == v:
return m
elif v<t[m][1]:
j = m-1
else:
i = m+1
return i
en.sort(key = lambda x:(x[0],-x[1]))
t = [en[0]]
c = 1
for i in range(len(en)):
if t[-1][1] < en[i][1]:
t.append(en[i])
c += 1
else:
x = bs(t,c,en[i][1])
t[x] = en[i]
return len(t) | russian-doll-envelopes | Python | Binary Search | Shivamk09 | 0 | 54 | russian doll envelopes | 354 | 0.382 | Hard | 6,238 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2828071/Python3-Mathematics-approach.-Explained-in-details.-Step-by-step | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
if n == 0: return 1
if n == 1: return 10
res = 91
mult = 8
comb = 81
for i in range(n - 2):
comb *= mult
mult -= 1
res += comb
return res | count-numbers-with-unique-digits | Python3 Mathematics approach. Explained in details. Step-by-step | Alex_Gr | 0 | 2 | count numbers with unique digits | 357 | 0.516 | Medium | 6,239 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2813901/Python-(Simple-Dynamic-Programming) | class Solution:
def countNumbersWithUniqueDigits(self, n):
if n == 0:
return 1
if n == 1:
return 10
dp = [0]*(n+1)
dp[0], dp[1] = 1, 10
for i in range(2,n+1):
dp[i] = (dp[i-1]-dp[i-2])*(10-(i-1)) + dp[i-1]
return dp[-1] | count-numbers-with-unique-digits | Python (Simple Dynamic Programming) | rnotappl | 0 | 5 | count numbers with unique digits | 357 | 0.516 | Medium | 6,240 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2725373/Simple-Math-solution | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
count = 1
for i in range(n):
count += 9*math.factorial(9)/math.factorial(9-i)
return int(count) | count-numbers-with-unique-digits | Simple Math solution | tawaca | 0 | 7 | count numbers with unique digits | 357 | 0.516 | Medium | 6,241 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2407737/Python3-or-Solved-using-Bottom-Up-DP-%2B-Tabulation | class Solution:
#T.C = O(n^2)
#S.C = O(n)
def countNumbersWithUniqueDigits(self, n: int) -> int:
#The reason why this is a dp problem is because it exhibits
#optimal substructure property!
#Take for example n =2, we can take already existing single-digit
#unique numbers and simply add on unused digit in the least significant digit!
# 1-> 12, 13, 14,..., 19
# 2-> 21, 23, 24, 25, ..., 29
#etc.
#Basically, we can take each unique single digit number, whose single digits
#are unique and consider using 9 other numbers in range 0-9 that has not
#already been used -> thus, 10*9 + rem. subproblems from n-2 down to 1!
#Furthermore, we may need to refer to already previously solved subproblems
#for lower n when solving for current larger n-> Exhibits overlapping
#subproblems property to apply dp!
#edge case: n== 0, return 1 to avoid array index out of bounds error!
if(n == 0):return 1
#Take a bottom-up approach!
#we need indices from 0 to n
dp = [0] * (n+1)
#add the dp-base
dp[0] = 1
dp[1] = 10
#iterate through each subproblem or state's single parameter: current n value!
digits_can_use = 9
for i in range(2, n+1, 1):
ans = 0
prev_answer = dp[i-1]
prev_answer *= digits_can_use
ans += prev_answer
#iterate from subproblem i-2 all the way down to subproblem 0 and add
#the subproblem's answers to overall answer: other unaccounted numbers
#in range from 0 to 10^n, not accounted for!
for j in range(i-2, -1, -1):
ans += dp[j]
dp[i] = ans
digits_can_use -= 1
#then, our answer will be last element of dp table!
return dp[n] | count-numbers-with-unique-digits | Python3 | Solved using Bottom-Up DP + Tabulation | JOON1234 | 0 | 56 | count numbers with unique digits | 357 | 0.516 | Medium | 6,242 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/1850741/Python3-or-DP-solution-runtime-35ms | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
dp = [1]*(n+1)
for i in range(1, n+1):
count = 0
for j in range(i):
count += dp[j]*(9-j)
dp[i] = count
return sum(dp) | count-numbers-with-unique-digits | Python3 | DP solution, runtime 35ms | elainefaith0314 | 0 | 105 | count numbers with unique digits | 357 | 0.516 | Medium | 6,243 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/1740318/python-3-simple-dp | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
dp=[1,10]
for i in range(2,n+1):
dp.append(dp[i-1]+9*int(math.factorial(9)/math.factorial(9-i+1)))
return dp[n] | count-numbers-with-unique-digits | python 3 simple dp | ryanzxc34 | 0 | 47 | count numbers with unique digits | 357 | 0.516 | Medium | 6,244 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/1682807/Python-or-Math | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
nums=[9,8,7,6,5,4,3,2,1]
ans=1
for digits in range(1,n+1):
tmp=1
for j in range(digits-1):#for 1 digits this loop won't run, for 2 digits we will only multiply it by 9, for 3 digits it will be like 1*9*8
tmp*=nums[j]
ans+=9*tmp#9 times tmp has to repeat from 1 to 9
return ans
'''
abc
if we select a=1, then we have exactly 9 choices for b(from 0 to 9 excluding a(i.e 1))
and we have exactly 8 choices for c (excluding a and b), similarly we can generate for 4,5,6.. digits by going deeper than 8 like 7,6,5...
''' | count-numbers-with-unique-digits | Python | Math | heckt27 | 0 | 47 | count numbers with unique digits | 357 | 0.516 | Medium | 6,245 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/1416500/Python-3-or-Math-DP-or-Explanation | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
ans = [1]
for k in range(1, n+1):
base = available = 9
for _ in range(k-1):
base *= available
available -= 1
ans.append(base+ans[-1])
return ans[-1] | count-numbers-with-unique-digits | Python 3 | Math, DP | Explanation | idontknoooo | 0 | 273 | count numbers with unique digits | 357 | 0.516 | Medium | 6,246 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/803035/Python3-top-down-and-bottom-up-dp | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
@lru_cache(None)
def fn(i):
"""Return count of integer of i digits with unique digits."""
if i == 0: return 1
if i == 1: return 9
return fn(i-1)*(11-i)
return sum(fn(i) for i in range(n+1)) | count-numbers-with-unique-digits | [Python3] top-down & bottom-up dp | ye15 | 0 | 145 | count numbers with unique digits | 357 | 0.516 | Medium | 6,247 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/803035/Python3-top-down-and-bottom-up-dp | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
ans = [1]
for i in range(1, n+1):
if i in (1, 2): ans.append(ans[-1]*9)
else: ans.append(ans[-1]*(11-i))
return sum(ans) | count-numbers-with-unique-digits | [Python3] top-down & bottom-up dp | ye15 | 0 | 145 | count numbers with unique digits | 357 | 0.516 | Medium | 6,248 |
https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/332471/Solution-in-Python-3-(beats-~98) | class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
if n == 0:
return 1
g, h = 10, 9
for i in range(n-1):
g += 9*h
h *= (8-i)
return(g)
- Python 3
- Junaid Mansuri | count-numbers-with-unique-digits | Solution in Python 3 (beats ~98%) | junaidmansuri | 0 | 373 | count numbers with unique digits | 357 | 0.516 | Medium | 6,249 |
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/2488882/Solution-In-Python | class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
ans = float("-inf")
m, n = len(matrix), len(matrix[0])
for i in range(n):
lstSum = [0] * m
for j in range(i, n):
currSum = 0
curlstSum = [0]
for t in range(m):
lstSum[t] += matrix[t][j]
currSum += lstSum[t]
pos = bisect_left(curlstSum, currSum - k)
if pos < len(curlstSum):
if curlstSum[pos] == currSum - k:
return k
else:
ans = max(ans, currSum - curlstSum[pos])
insort(curlstSum, currSum)
return ans | max-sum-of-rectangle-no-larger-than-k | Solution In Python | AY_ | 8 | 1,200 | max sum of rectangle no larger than k | 363 | 0.441 | Hard | 6,250 |
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/2368438/faster-than-98.18-or-pyrhon-or-Numpy | class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
import numpy as np
matrix = np.array(matrix, dtype=np.int32)
M,N = matrix.shape
ret = float("-inf")
CUM = np.zeros((M,N), dtype=np.int32)
for shift_r in range(M):
CUM[:M-shift_r] += matrix[shift_r:]
_CUM = np.zeros((M-shift_r,N), dtype=np.int32)
for shift_c in range(N):
_CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]
tmp = _CUM[(_CUM<=k) & (_CUM>ret)]
if tmp.size:
ret = tmp.max()
if ret == k:
return ret
return ret
''' | max-sum-of-rectangle-no-larger-than-k | faster than 98.18% | pyrhon | Numpy | vimla_kushwaha | 2 | 493 | max sum of rectangle no larger than k | 363 | 0.441 | Hard | 6,251 |
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/1277586/Python3-insort-and-SortedList | class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(matrix[0]) # dimensions
ans = -inf
rsum = [[0]*(n+1) for _ in range(m)] # row prefix sum
for j in range(n):
for i in range(m): rsum[i][j+1] = matrix[i][j] + rsum[i][j]
for jj in range(j+1):
prefix = 0
vals = [0]
for i in range(m):
prefix += rsum[i][j+1] - rsum[i][jj]
x = bisect_left(vals, prefix - k)
if x < len(vals): ans = max(ans, prefix - vals[x])
insort(vals, prefix)
return ans | max-sum-of-rectangle-no-larger-than-k | [Python3] insort & SortedList | ye15 | 2 | 301 | max sum of rectangle no larger than k | 363 | 0.441 | Hard | 6,252 |
https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/2821776/Kadane's-Algorithm-with-bisect-and-transposition-extension | class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
# initialize rows and columns values and determine transposed flag if needed
rows = len(matrix) # m
cols = len(matrix[0]) # n
transposed_matrix_flag = False
transposed_matrix = list()
# consider a power of 10 as siginficant
# if cols is significantly larger than rows in our implementation
# we will do the significantly larger work^2
# If this were to occur, we should flip our set up
if cols > (10*rows) :
# set transpose flag to true
transposed_matrix_flag = True
# loop over columns amount
for row in range(cols) :
# generate rows
transposed_row = list()
# for column in matrix is actually the rows
for col in matrix :
# append the row item at the row index to the row
transposed_row.append(col[row])
# put the transposed row into the transposed matrix
transposed_matrix.append(transposed_row)
# if transposed flag
if transposed_matrix_flag :
# set the transpose and adjust rows and cols as needed
matrix = transposed_matrix
rows = len(matrix)
cols = len(matrix[0])
# minimum value start for maximal sum
maximum_sum = -math.inf
# loop all columns
for col_index in range(cols) :
# generate a temporary row
temp_row = [0] * rows
# loop columns from col index to cols
# col_index_2 is then our bound column index
for col_index_2 in range(col_index, cols) :
# set that column sums and the column sum
column_sums = [0]
column_sum = 0
# loop every row index in range rows
for row_index in range(rows) :
# temp row at the row index is the matrix at the row and the bound col index
temp_row[row_index] += matrix[row_index][col_index_2]
# column sum gets this valuation added
column_sum += temp_row[row_index]
# difference is determined
difference = column_sum - k
# index is determined by bisection
index = bisect.bisect_left(column_sums, difference)
# if index is in range of column sums so far
if index < len(column_sums) :
# if column sums at that index is the difference
if column_sums[index] == difference :
# this is the maximal result, return it
return k
else :
# otherwise maximum sum is set to maximum of itself and difference of column sum and column sums at index
maximum_sum = max(maximum_sum, column_sum - column_sums[index])
# do an insort of column sum into column sums, at most row times
bisect.insort(column_sums, column_sum)
# if you never returned k, you should return as good as you got
return maximum_sum | max-sum-of-rectangle-no-larger-than-k | Kadane's Algorithm with bisect and transposition extension | laichbr | 0 | 2 | max sum of rectangle no larger than k | 363 | 0.441 | Hard | 6,253 |
https://leetcode.com/problems/water-and-jug-problem/discuss/393886/Solution-in-Python-3-(beats-~100)-(one-line)-(Math-Solution) | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
return False if x + y < z else True if x + y == 0 else not z % math.gcd(x,y)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | water-and-jug-problem | Solution in Python 3 (beats ~100%) (one line) (Math Solution) | junaidmansuri | 5 | 1,300 | water and jug problem | 365 | 0.367 | Medium | 6,254 |
https://leetcode.com/problems/water-and-jug-problem/discuss/804576/Python3-1-line | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
return not z or (z <= x + y and z % gcd(x, y) == 0) | water-and-jug-problem | [Python3] 1-line | ye15 | 3 | 783 | water and jug problem | 365 | 0.367 | Medium | 6,255 |
https://leetcode.com/problems/water-and-jug-problem/discuss/804576/Python3-1-line | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
if not z: return True #edge case
def gcd(x, y):
"""Return greatest common divisor via Euclidean algo"""
if x < y: x, y = y, x
while y: x, y = y, x%y
return x
return z <= x + y and z % gcd(x, y) == 0 | water-and-jug-problem | [Python3] 1-line | ye15 | 3 | 783 | water and jug problem | 365 | 0.367 | Medium | 6,256 |
https://leetcode.com/problems/water-and-jug-problem/discuss/2733181/Python-Solution-using-BFS-traversal | class Solution:
def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
edges=[jug1Capacity,jug2Capacity,abs(jug2Capacity-jug1Capacity)]
lst=[0]
mx=max(jug1Capacity,jug2Capacity,targetCapacity)
visited=[0]*1000001
if targetCapacity>(jug1Capacity+jug2Capacity):
return False
visited[0]=1
while lst:
x=lst.pop(0)
if x==targetCapacity:
return True
for i in edges:
if x+i<=mx and visited[x+i]==0:
lst.append(x+i)
visited[x+i]=1
if x-i>=0 and visited[x-i]==0:
lst.append(x-i)
visited[x-i]=1
return False | water-and-jug-problem | Python Solution using BFS traversal | beneath_ocean | 2 | 184 | water and jug problem | 365 | 0.367 | Medium | 6,257 |
https://leetcode.com/problems/water-and-jug-problem/discuss/2032236/Python-easy-to-read-and-understand-or-bfs | class Solution:
def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
total = jug1Capacity+jug2Capacity
visit = set()
visit.add(0)
q = [0]
while q:
curr = q.pop(0)
if curr == targetCapacity:
return True
for step in [jug1Capacity, -jug1Capacity, jug2Capacity, -jug2Capacity]:
new = curr+step
if new > 0 and new <= jug1Capacity+jug2Capacity and new not in visit:
visit.add(new)
q.append(new)
return False | water-and-jug-problem | Python easy to read and understand | bfs | sanial2001 | 1 | 183 | water and jug problem | 365 | 0.367 | Medium | 6,258 |
https://leetcode.com/problems/water-and-jug-problem/discuss/1814345/python-3-one-line-solution | class Solution:
def canMeasureWater(self, jug1: int, jug2: int, target: int) -> bool:
return jug1 + jug2 >= target and target % math.gcd(jug1, jug2) == 0 | water-and-jug-problem | python 3, one line solution | dereky4 | 1 | 190 | water and jug problem | 365 | 0.367 | Medium | 6,259 |
https://leetcode.com/problems/water-and-jug-problem/discuss/1476818/Python-simple-GCD-solution | class Solution:
def canMeasureWater(self, a: int, b: int, c: int) -> bool:
import math
if a==b:
return c== a
if c> a+b:
return False
return c % math.gcd(a, b) == 0 | water-and-jug-problem | Python simple GCD solution | byuns9334 | 1 | 268 | water and jug problem | 365 | 0.367 | Medium | 6,260 |
https://leetcode.com/problems/water-and-jug-problem/discuss/2725569/Math-GCD-and-simple-logic-explained-(Python3) | class Solution:
def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
if jug1Capacity + jug2Capacity < targetCapacity:
return False
if targetCapacity % math.gcd(jug1Capacity,jug2Capacity) != 0:
return False
return True | water-and-jug-problem | Math GCD and simple logic explained (Python3) | tawaca | 0 | 20 | water and jug problem | 365 | 0.367 | Medium | 6,261 |
https://leetcode.com/problems/water-and-jug-problem/discuss/2538375/Python-Easy-to-understand-math-solution | class Solution:
def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
if jug1Capacity + jug2Capacity == targetCapacity: return True
for i in range(jug1Capacity):
curr = (jug2Capacity*i)%jug1Capacity
if curr == targetCapacity or curr+jug2Capacity == targetCapacity: return True
for i in range(jug2Capacity):
curr = (jug1Capacity*i)%jug2Capacity
if curr == targetCapacity or curr+jug1Capacity == targetCapacity: return True
return False | water-and-jug-problem | [Python] Easy to understand math solution | fomiee | 0 | 80 | water and jug problem | 365 | 0.367 | Medium | 6,262 |
https://leetcode.com/problems/water-and-jug-problem/discuss/534209/Python3-20ms-96-gcd | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
big, small = max(x, y), min(x, y)
if z > big + small or z < 0 or small < 0:
return False
if z == 0 or z == big + small:
return True
if small == 0:
return z == big
gcd = self.gcd(big, small)
return z % gcd == 0
@classmethod
def gcd(cls, x, y) -> int:
while True:
if x % y == 0:
return y
else:
x, y = y, x % y | water-and-jug-problem | Python3 20ms 96% gcd | tjucoder | 0 | 471 | water and jug problem | 365 | 0.367 | Medium | 6,263 |
https://leetcode.com/problems/water-and-jug-problem/discuss/513109/Python3-simple-solution-using-Euclid's-algorithm-faster-than-99.03 | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
def eucid(x,y):
if x<y: x,y=y,x
while x!=y!=0:
remainder=x%y
x,y=y,remainder
return x
e=eucid(x,y)
if not e: return not z
return (x+y)>=z and z%e==0 | water-and-jug-problem | Python3 simple solution using Euclid's algorithm, faster than 99.03% | jb07 | 0 | 415 | water and jug problem | 365 | 0.367 | Medium | 6,264 |
https://leetcode.com/problems/valid-perfect-square/discuss/1063963/100-Python-One-Liner-UPVOTE-PLEASE | class Solution:
def isPerfectSquare(self, num: int) -> bool:
return int(num**0.5) == num**0.5 | valid-perfect-square | 100% Python One-Liner UPVOTE PLEASE | 1coder | 6 | 451 | valid perfect square | 367 | 0.433 | Easy | 6,265 |
https://leetcode.com/problems/valid-perfect-square/discuss/2315548/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def isPerfectSquare(self, num: int) -> bool:
low = 1
high = num
while low <= high:
mid = ( low + high ) //2
if mid * mid == num:
return mid
elif mid * mid < num:
low = mid + 1
elif mid * mid > num:
high = mid - 1
return False | valid-perfect-square | [ Python ] ✅✅ Simple Python Solution Using Two Approach🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 5 | 253 | valid perfect square | 367 | 0.433 | Easy | 6,266 |
https://leetcode.com/problems/valid-perfect-square/discuss/2315548/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if int(num**0.5)*int(num**0.5)==num:
return True
else:
return False | valid-perfect-square | [ Python ] ✅✅ Simple Python Solution Using Two Approach🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 5 | 253 | valid perfect square | 367 | 0.433 | Easy | 6,267 |
https://leetcode.com/problems/valid-perfect-square/discuss/2172531/Python3-extension-of-binary-search | class Solution:
def isPerfectSquare(self, num: int) -> bool:
left,right = 1,num
while left<=right:
middle = (left+right)//2
if middle**2==num:
return True
if middle**2>num:
right = middle-1
else:
left = middle+1
return False | valid-perfect-square | 📌 Python3 extension of binary search | Dark_wolf_jss | 5 | 57 | valid perfect square | 367 | 0.433 | Easy | 6,268 |
https://leetcode.com/problems/valid-perfect-square/discuss/2097406/Python3-from-Brute-force-to-Optimal-O(N)-to-O(logN) | class Solution:
def isPerfectSquare(self, num: int) -> bool:
return self.binarySearchOptimal(num)
return self.bruteForce(num)
# O(logN) || O(1)
# runtime: 33ms 81.46%
# memory: 13.8mb 56.48%
def binarySearchOptimal(self, num):
if not num:return False
left, right = 0, num + 1
while left <= right:
mid = (left + right) // 2
square = mid * mid # mid** 2 # pow(mid, 2)
if square == num:
return True
elif square > num:
right = mid - 1
else:
left = mid + 1
# O(n) || O(1)
# runtime: 68ms 9.28%
def bruteForce(self, num):
if not num:
return False
for i in range(1, num+1):
square = i * i
if square == num:
return True
elif square > num:
return False
return -1 | valid-perfect-square | Python3 from Brute force to Optimal O(N) to O(logN) | arshergon | 2 | 103 | valid perfect square | 367 | 0.433 | Easy | 6,269 |
https://leetcode.com/problems/valid-perfect-square/discuss/1840685/Python-Easiest-Solution-With-Explanation-O(logn)-or-Binary-Search-or-Beg-to-Adv-or | class Solution:
def isPerfectSquare(self, num: int) -> bool:
left = 0 # starting point
right = num # end of the search point
# usually we take it as len(arr) - 1, but for a number len() doesnt work.
# Then I tried with num - 1, it was working fine, though for "1" this algorithm failed.
# So no need to num - 1 , we can take it as num only.
while left <= right:
mid = (right+left)//2 # calculating mid
if mid ** 2 == num: # checking if mid value square is equal to the given number.
return True
if mid ** 2 > num: # if mid square is greater then given number, then we only have to look only in left hand side.
right = mid - 1
elif mid ** 2 < num: # if mid square is lesser then given number, then we only have to look only in right hand side.
left = mid + 1
return False # if its not a Perfect square. | valid-perfect-square | Python Easiest Solution With Explanation O(logn) | Binary Search | Beg to Adv | | rlakshay14 | 2 | 121 | valid perfect square | 367 | 0.433 | Easy | 6,270 |
https://leetcode.com/problems/valid-perfect-square/discuss/2650436/Python3-easy-solution-using-binary-search. | class Solution:
def isPerfectSquare(self, num: int) -> bool:
left, right = 1, num
while left <= right:
middle = (left+right)//2
if middle**2 == num:
return True
if middle**2 > num:
right = middle - 1
else:
left = middle + 1
return False | valid-perfect-square | Python3 easy solution using binary search. | khushie45 | 1 | 53 | valid perfect square | 367 | 0.433 | Easy | 6,271 |
https://leetcode.com/problems/valid-perfect-square/discuss/2346166/Python-One-Line-Solution-or-Faster-than-99.07-or-Memory-Usage-Less-than-96.42 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
return int(num**(1/2))==num**(1/2) | valid-perfect-square | Python One Line Solution | Faster than 99.07% | Memory Usage Less than 96.42% | dhruva3223 | 1 | 68 | valid perfect square | 367 | 0.433 | Easy | 6,272 |
https://leetcode.com/problems/valid-perfect-square/discuss/2136245/Simple-and-Easy-Python-Solution-(with-examples) | class Solution:
def isPerfectSquare(self, num: int) -> bool:
square_root=num ** 0.5 #gives square root of the number
mod_1=square_root%1 #gives remainder
if mod_1==0:
return True
else:
return False | valid-perfect-square | Simple and Easy Python Solution (with examples) | pruthashouche | 1 | 90 | valid perfect square | 367 | 0.433 | Easy | 6,273 |
https://leetcode.com/problems/valid-perfect-square/discuss/1727448/Binary-Search-in-Python3 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
# binary search
# if num == 1:
# return True
left = 1
right = num
while left <= right:
mid = (left+right)//2
if mid**2 == num:
return True
elif mid**2 > num:
right = mid - 1
else:
left = mid + 1
return False | valid-perfect-square | Binary Search in Python3 | hiuiwb | 1 | 41 | valid perfect square | 367 | 0.433 | Easy | 6,274 |
https://leetcode.com/problems/valid-perfect-square/discuss/1726569/Python-one-liner | class Solution:
def isPerfectSquare(self, num: int) -> bool:
return (num**0.5).is_integer() | valid-perfect-square | Python one-liner | denizen-ru | 1 | 56 | valid perfect square | 367 | 0.433 | Easy | 6,275 |
https://leetcode.com/problems/valid-perfect-square/discuss/1528924/Python-96%2B%2B-Faster-Easy-Solution | class Solution:
def isPerfectSquare(self, num: int) -> bool:
x = num ** 0.5
return x - int(x) == False | valid-perfect-square | Python 96%++ Faster Easy Solution | aaffriya | 1 | 71 | valid perfect square | 367 | 0.433 | Easy | 6,276 |
https://leetcode.com/problems/valid-perfect-square/discuss/1456862/Math-oror-Perfect-Square-oror-Easy-to-Understand | class Solution:
def isPerfectSquare(self, num: int) -> bool:
#Case 1 : as we know, 1 is a perfect square
if num == 1:
return True
#Case 2 : Now, we can find out the root using --> num**0.5
#If the number if a perfect square, root must be integral in nature(eg. 16 ** 0.5 = 4.0)
#Else, it will be a floating point number
#So, we will simply check if if we have an integral root or not
root = (num)**0.5
s = str(root)
n = len(s)
#if the second last and last characters are "." and "0", as in "4.0" it means we have a perfect square
if s[n-2] == "." or s[n-1] == "0":
return True
else:
return False | valid-perfect-square | Math || Perfect Square || Easy to Understand | aarushsharmaa | 1 | 112 | valid perfect square | 367 | 0.433 | Easy | 6,277 |
https://leetcode.com/problems/valid-perfect-square/discuss/1352775/Simple-Python-Solution-for-%22Valid-Perfect-Square%22 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while(i*i<=num):
if((num%i==0) and (num//i == i)):
return True
i += 1
return False | valid-perfect-square | Simple Python Solution for "Valid Perfect Square" | sakshikhandare2527 | 1 | 130 | valid perfect square | 367 | 0.433 | Easy | 6,278 |
https://leetcode.com/problems/valid-perfect-square/discuss/2846145/python3 | class Solution:
def isPerfectSquare(self, n: int) -> bool:
if n < 2:
return True
# binary search
l, r = 2, n // 2 # left, right pointer
while l <= r:
m = (l + r) // 2 # mid
if m == (x := (n / m)):
return True
if m > x:
r = m - 1
else:
l = m + 1
return False | valid-perfect-square | python3 | wduf | 0 | 1 | valid perfect square | 367 | 0.433 | Easy | 6,279 |
https://leetcode.com/problems/valid-perfect-square/discuss/2835832/Pen-n-Paper-Solution-oror-2-solutions-oror-Easy-oror-Python | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num<0:
return False
l=0
h=1
while l<num:
l=l+h
h=h+2
return l==num | valid-perfect-square | Pen n Paper Solution || 2 solutions || Easy || Python | user9516zM | 0 | 2 | valid perfect square | 367 | 0.433 | Easy | 6,280 |
https://leetcode.com/problems/valid-perfect-square/discuss/2835832/Pen-n-Paper-Solution-oror-2-solutions-oror-Easy-oror-Python | class Solution:
def isPerfectSquare(self, num: int) -> bool:
low,high=0,num
while low<=high:
mid=(low+high)//2
if mid**2==num:
return True
elif mid**2>num:
high=mid-1
else:
low=mid+1 | valid-perfect-square | Pen n Paper Solution || 2 solutions || Easy || Python | user9516zM | 0 | 2 | valid perfect square | 367 | 0.433 | Easy | 6,281 |
https://leetcode.com/problems/valid-perfect-square/discuss/2835806/Pen | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num<0:
return False
l=0
h=1
while l<num:
l=l+h
h=h+2
return l==num | valid-perfect-square | Pen | user9516zM | 0 | 2 | valid perfect square | 367 | 0.433 | Easy | 6,282 |
https://leetcode.com/problems/valid-perfect-square/discuss/2813465/Simple-Python-solutionororBinary-Search | class Solution:
def isPerfectSquare(self, num: int) -> bool:
low=0
high=num-1
if num==1:
return True
while(low<=high):
mid=(low+high)//2
if (mid*mid)==num:
return True
else:
if(mid)*(mid)>num:
high=mid-1
else:
low=mid+1
return False | valid-perfect-square | Simple Python solution||Binary Search | Ankit_Verma03 | 0 | 5 | valid perfect square | 367 | 0.433 | Easy | 6,283 |
https://leetcode.com/problems/valid-perfect-square/discuss/2809924/Simple-Python-using-Binary-search-beats-80 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
low = 0
high = num
if num == 1 or num == 0:
return True
while(low<high):
mid = (low+high)//2
if mid*mid == num:
return True
if mid*mid>num:
high = mid
else:
low = mid+1
else:
return False | valid-perfect-square | Simple Python using Binary search beats 80% | sudharsan1000m | 0 | 1 | valid perfect square | 367 | 0.433 | Easy | 6,284 |
https://leetcode.com/problems/valid-perfect-square/discuss/2808501/Simple-Python-solution | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1:
return 1
sq = 1
while (sq**2) < num:
sq += 1
return sq**2 == num | valid-perfect-square | Simple Python solution | alangreg | 0 | 2 | valid perfect square | 367 | 0.433 | Easy | 6,285 |
https://leetcode.com/problems/valid-perfect-square/discuss/2782528/Beginners-second-attempt-after-successful-but-slow-for-loop.-Python3 | class Solution:
def isPerfectSquare(self, num: int) -> bool:
start = 1
end = num//2
if num == 1:
return True
while start <= end:
middle = start + (end-start) // 2
sq = middle*middle
if sq == num: return True
if sq < num:
start = middle + 1
if sq > num:
end = middle - 1
return False | valid-perfect-square | Beginners second attempt after successful but slow for loop. Python3 | OGLearns | 0 | 2 | valid perfect square | 367 | 0.433 | Easy | 6,286 |
https://leetcode.com/problems/valid-perfect-square/discuss/2738731/Simple-Python-3-Solution | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if int(num**0.5)*int(num**0.5) == num:
return True
else:
return False | valid-perfect-square | Simple Python 3 Solution | dnvavinash | 0 | 5 | valid perfect square | 367 | 0.433 | Easy | 6,287 |
https://leetcode.com/problems/valid-perfect-square/discuss/2737328/Python-Brute-Force | class Solution:
def isPerfectSquare(self, num: int) -> bool:
for i in range(100000):
if (i ** 2 == num):
return True
return False | valid-perfect-square | Python Brute Force | lucasschnee | 0 | 4 | valid perfect square | 367 | 0.433 | Easy | 6,288 |
https://leetcode.com/problems/valid-perfect-square/discuss/2603430/Python | class Solution:
def isPerfectSquare(self, num: int) -> bool:
left = 0
right = num
while left <= right:
mid = (left + right) // 2
if (sqrt_num := mid ** 2) == num:
return True
elif sqrt_num < num:
left = mid + 1
else:
right = mid - 1
return False | valid-perfect-square | Python答え | namashin | 0 | 31 | valid perfect square | 367 | 0.433 | Easy | 6,289 |
https://leetcode.com/problems/valid-perfect-square/discuss/2531646/Python3-or-Binary-Search-on-Square-Root-Candidates | class Solution:
#Time-Complexity: O(log(2^31 -1)), in worst case where num is highest value possible
#given the constraint on the possible range num input could be! -> O(1)
#Space-Complexity: O(1)
def isPerfectSquare(self, num: int) -> bool:
#Approach: Define search space as positive integers from 1 to num, b/c those are
#the possible candidates that can square itself to equal num!
#Perform binary search on this search space and see if any of the numbers square itself
#equals number input!
L, H = 1, num
#as long as we have one number in search space left to still consider, continue
#binary searching!
while L <= H:
mid = (L + H) // 2
if(mid * mid == num):
return True
elif(mid * mid > num):
H = mid - 1
continue
else:
L = mid + 1
continue
#if we break from while loop without returning T, that implies that number input
#is not perfect square!
return False | valid-perfect-square | Python3 | Binary Search on Square Root Candidates | JOON1234 | 0 | 82 | valid perfect square | 367 | 0.433 | Easy | 6,290 |
https://leetcode.com/problems/valid-perfect-square/discuss/2418747/C%2B%2BPython-best-optimized-solution-using-Binary-Search | class Solution:
def isPerfectSquare(self, num: int) -> bool:
s = 0
e = num
while(s<=e):
mid = (s+e)//2
if mid*mid==num:
return True
elif mid*mid>num:
e = mid-1
else:
s = mid+1
return False | valid-perfect-square | C++/Python best optimized solution using Binary Search | arpit3043 | 0 | 44 | valid perfect square | 367 | 0.433 | Easy | 6,291 |
https://leetcode.com/problems/valid-perfect-square/discuss/2368834/Python-91.32-faster-than-other | class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num==1:return True
start=0
end=num//2
while start<=end:
mid=start+(end-start)//2
if mid**2==num:return True
elif mid**2<num:start=mid+1
else:end=mid-1 | valid-perfect-square | [Python] 91.32% faster than other | pheraram | 0 | 88 | valid perfect square | 367 | 0.433 | Easy | 6,292 |
https://leetcode.com/problems/valid-perfect-square/discuss/2355634/Python-O(log-n)-oror-Iterative-Binary-Search-oror-Well-Documented | class Solution:
def isPerfectSquare(self, num: int) -> bool:
low, high, = 1, num
# Repeat until the pointers low and high meet each other
while low <= high:
mid = (low + high) // 2 # middle point - pivot
if mid * mid == num: return True # found result
elif mid * mid < num: low = mid + 1 # go right side
else: high = mid - 1 # go left side
return False | valid-perfect-square | [Python] O(log n) || Iterative Binary Search || Well Documented | Buntynara | 0 | 15 | valid perfect square | 367 | 0.433 | Easy | 6,293 |
https://leetcode.com/problems/valid-perfect-square/discuss/2324356/CPP-or-Java-or-Python3-or-O(log-n) | class Solution:
def isPerfectSquare(self, num: int) -> bool:
start, end = 0, num/2
if num == 1: return True
while(start <= end):
mid = start + (end - start)//2
if(mid * mid < num): start = mid + 1
elif(mid * mid == num): return True
else: end = mid - 1
return False | valid-perfect-square | CPP | Java | Python3 | O(log n) | devilmind116 | 0 | 32 | valid perfect square | 367 | 0.433 | Easy | 6,294 |
https://leetcode.com/problems/valid-perfect-square/discuss/2299385/Python-binary-search-for-the-square-root | class Solution:
def isPerfectSquare(self, num: int) -> bool:
start, end = 1, 2**16
if num == 1:
return True
while start <= end:
mid = start + (end-start)//2
if (mid**2) == num: return True
elif (mid**2) > num: end = mid - 1
elif (mid**2) < num: start = mid + 1
return False | valid-perfect-square | Python binary search for the square root | zip_demons | 0 | 34 | valid perfect square | 367 | 0.433 | Easy | 6,295 |
https://leetcode.com/problems/valid-perfect-square/discuss/2211170/Easy-python-solution-or-Valid-Perfect-Square | class Solution:
def isPerfectSquare(self, num: int) -> bool:
root = int(num**(1/2))
if root*root == num:
return True
return False | valid-perfect-square | Easy python solution | Valid Perfect Square | nishanrahman1994 | 0 | 31 | valid perfect square | 367 | 0.433 | Easy | 6,296 |
https://leetcode.com/problems/valid-perfect-square/discuss/2148137/python3-or-binary-search | class Solution:
def isPerfectSquare(self, num: int) -> bool:
start = 1
end = num
if num == start:
return True
while start <= end:
mid = start + (end-start)//2
print(mid)
if mid * mid == num:
return True
elif mid * mid > num:
end = mid-1
elif mid * mid < num:
start = mid +1
return False | valid-perfect-square | python3 | binary search | rohannayar8 | 0 | 34 | valid perfect square | 367 | 0.433 | Easy | 6,297 |
https://leetcode.com/problems/valid-perfect-square/discuss/2124620/Python-Easy-solution-with-complexity | class Solution:
def isPerfectSquare(self, num: int) -> bool:
left = 1
right = num//2
if num == 1:
return True
while (right>= left ) :
med = (left +right)//2
if med*med == num:
return True
if med*med > num :
right = med -1
if med*med < num :
left = med +1
return False
# time O(logN)
# space O(1) | valid-perfect-square | [Python] Easy solution with complexity | mananiac | 0 | 76 | valid perfect square | 367 | 0.433 | Easy | 6,298 |
https://leetcode.com/problems/valid-perfect-square/discuss/2119661/Simple-3-line-Python-Solution-using-and-** | class Solution(object):
def isPerfectSquare(self, num):
if num%(num**0.5) == 0:
return True
return False | valid-perfect-square | Simple 3 line Python Solution using % and ** | NathanPaceydev | 0 | 49 | valid perfect square | 367 | 0.433 | Easy | 6,299 |
Subsets and Splits