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/sum-of-unique-elements/discuss/2048863/Python-simple-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
ans = []
for i in set(nums):
if nums.count(i) == 1:
ans.append(i)
return sum(ans) if ans else 0 | sum-of-unique-elements | Python simple solution | StikS32 | 1 | 114 | sum of unique elements | 1,748 | 0.757 | Easy | 25,100 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1254475/Python3-faster-than-94.28 | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d = dict()
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] += 1
result = 0
for item in d.items():
if item[1] == 1:
result += item[0]
return result | sum-of-unique-elements | Python3 - faster than 94.28% | CC_CheeseCake | 1 | 219 | sum of unique elements | 1,748 | 0.757 | Easy | 25,101 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1228238/PythonnPython3-solution-with-explanation | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
sumUnique = 0 #To store the sum of unique values
for i in set(nums): #taking set(nums) to reduce the number of iterations
if nums.count(i) == 1: #If i's count is equal to 1 then we will increase the sum
sumUnique += i
return sumUnique | sum-of-unique-elements | Pythonn/Python3 solution with explanation | prasanthksp1009 | 1 | 188 | sum of unique elements | 1,748 | 0.757 | Easy | 25,102 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1104574/python-one-liner-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum(filter(lambda x: nums.count(x) == 1, nums)) | sum-of-unique-elements | python one liner solution | n_inferno | 1 | 135 | sum of unique elements | 1,748 | 0.757 | Easy | 25,103 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1096002/Simple-Solution-Python3-with-Explanation | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
ans = 0
length = len(nums)
occurred = False
if length == 1:
return nums[0]
nums.sort()
for i in range(0, length-1):
if nums[i] != nums[i+1]:
if not occurred:
ans += nums[i]
occurred = False
else:
occurred = True
if nums[-1] != nums[length-2]:
ans += nums[-1]
return ans | sum-of-unique-elements | Simple Solution Python3 with Explanation | nematov_olimjon | 1 | 164 | sum of unique elements | 1,748 | 0.757 | Easy | 25,104 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1052609/python-implementation-using-set(naive-solution) | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
uni=set()
result=0
stack=set()
for i in range(len(nums)):
if nums[i] in stack:
if nums[i] in uni :
uni.remove(nums[i])
result-=nums[i]
else:
if nums[i] not in stack:
stack.add(nums[i])
uni.add(nums[i])
result+=nums[i]
return result
` | sum-of-unique-elements | python implementation using set(naive solution) | YashMistry | 1 | 98 | sum of unique elements | 1,748 | 0.757 | Easy | 25,105 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2828894/Easy-python-solution-using-dictionary | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d = {}
for i in nums:
d[i]=d.get(i, 0) + 1
a = [x for x, v in d.items() if v==1]
return sum(a) | sum-of-unique-elements | Easy python solution using dictionary | _debanjan_10 | 0 | 1 | sum of unique elements | 1,748 | 0.757 | Easy | 25,106 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2823522/Python-3-oror-6-lines-of-code-oror-Beginner-Friendly | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
counts={}
for i in nums: counts[i]=counts.get(i,0) + 1
c=0
for i,j in counts.items():
if(j==1): c+=i
return c | sum-of-unique-elements | Python 3 🔥 || 6 lines of code✅ || Beginner Friendly ✌🏼 | jhadevansh0809 | 0 | 2 | sum of unique elements | 1,748 | 0.757 | Easy | 25,107 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2817719/simple-python-solution-oror-using-count()-oror-O(N)-Time-complexity | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
ans=0
for i in nums:
if nums.count(i)==1:
ans+=i
return ans | sum-of-unique-elements | simple python solution || using count() || O(N) Time complexity | Nikhil2532 | 0 | 1 | sum of unique elements | 1,748 | 0.757 | Easy | 25,108 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2803114/Python3-TypeScript-Solution-using-Hashmap | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
temp = [0] * 101
ans = 0
for i in nums:
if temp[i] == 0:
ans += i
temp[i] = 1
elif temp[i] == 1:
ans -= i
temp[i] = -1
return ans | sum-of-unique-elements | [Python3, TypeScript] Solution using Hashmap | BLOCKS | 0 | 3 | sum of unique elements | 1,748 | 0.757 | Easy | 25,109 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2755797/Basic-Dictionary-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d={}
for i in nums:
if i not in d:
d[i]=1
else:
d[i]+=1
ans=0
for k,v in d.items():
if v == 1:
ans+=k
return ans | sum-of-unique-elements | Basic Dictionary solution | beingab329 | 0 | 2 | sum of unique elements | 1,748 | 0.757 | Easy | 25,110 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2734613/easiest-way-in-python | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
p={}
s=0
for i in nums:
if i in p:
p[i]+=1
else:
p[i]=1
for ke,val in p.items():
if val==1:
s=s+ke
return s | sum-of-unique-elements | easiest way in python | sindhu_300 | 0 | 8 | sum of unique elements | 1,748 | 0.757 | Easy | 25,111 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2655102/Sum-of-unique-elements | class Solution:
def sumOfUnique(self, arr: List[int]) -> int:
d = dict ()
for i in range(len (arr)):
if arr[i] in d:
d[arr[i]] += 1
else:
d[arr[i]] = 1
s=0
for key, val in d.items():
if val==1:
s+=key
return s | sum-of-unique-elements | Sum of unique elements | shivansh2001sri | 0 | 34 | sum of unique elements | 1,748 | 0.757 | Easy | 25,112 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2645377/Python-One-liner-Solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum(num for num, freq in collections.Counter(nums).items() if freq == 1) | sum-of-unique-elements | Python One-liner Solution | kcstar | 0 | 16 | sum of unique elements | 1,748 | 0.757 | Easy | 25,113 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2606318/simple-solution-in-python-or-O(n) | class Solution(object):
def sumOfUnique(self, nums):
summation=0
for i in nums:
if nums.count(i)==1:
summation+=i
return summation | sum-of-unique-elements | simple solution in python | O(n) | msherazedu | 0 | 32 | sum of unique elements | 1,748 | 0.757 | Easy | 25,114 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2605427/Python-accepted-O(N)-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
unique_list = []
removedlist=[]
for x in nums:
# check if exists in unique_list or not
if(x not in removedlist):
if x not in unique_list:
unique_list.append(x)
else:
removedlist.append(x)
unique_list.remove(x)
return sum(unique_list) | sum-of-unique-elements | Python accepted O(N) solution | mjk22071998 | 0 | 33 | sum of unique elements | 1,748 | 0.757 | Easy | 25,115 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2515222/Simple-python-solution-using-hashmap | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
sum = 0
dic = collections.Counter(nums)
for k,v in dic.items():
if v == 1:
sum += k
return sum | sum-of-unique-elements | Simple python solution using hashmap | aruj900 | 0 | 30 | sum of unique elements | 1,748 | 0.757 | Easy | 25,116 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2466537/Fast-python-solution-using-collections | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
nums_dict = collections.Counter(nums)
total_unique_some = 0
for k in nums_dict:
if nums_dict[k] == 1:
total_unique_some += k
return total_unique_some | sum-of-unique-elements | Fast python solution using collections | samanehghafouri | 0 | 20 | sum of unique elements | 1,748 | 0.757 | Easy | 25,117 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2401814/Python-solution-O(N) | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
res = 0
for i in nums:
if nums.count(i) < 2:
res += i
return res | sum-of-unique-elements | Python solution O(N) | YangJenHao | 0 | 41 | sum of unique elements | 1,748 | 0.757 | Easy | 25,118 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2277663/python3-oror-single-pass-oror-O(N)-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
sum=0
temp={}
for i in nums:
if temp.get(i):
if temp.get(i)!=2:
sum-=i
temp[i]=2
else:
sum+=i
temp[i]=True
return sum | sum-of-unique-elements | python3 || single pass || O(N) solution | _soninirav | 0 | 43 | sum of unique elements | 1,748 | 0.757 | Easy | 25,119 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2260956/Sum-of-Unique-Elements-Python-Solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
x={}
#maintain a dictionary wher key =>number and value =>frequency
UniqueSum=0
#initialize The unique sum to zero
for i in nums:
#iterate over nums array and populate dictionary x
if i in x:
x[i]+=1
else:
x[i]=1
for i in nums:
#iterate over the nums array and check if frequency of number is equal to one
if x[i]==1:
UniqueSum+=i
#increment the uniQue sum if frequency is one
return UniqueSum | sum-of-unique-elements | Sum of Unique Elements Python Solution | dhananjayaduttmishra | 0 | 13 | sum of unique elements | 1,748 | 0.757 | Easy | 25,120 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2208413/Python-1-Liner | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum([i for i in collections.Counter(nums).keys() if collections.Counter(nums)[i]==1]) | sum-of-unique-elements | Python 1-Liner | XRFXRF | 0 | 54 | sum of unique elements | 1,748 | 0.757 | Easy | 25,121 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/2127108/Runtime-beats-95-or-Python | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
final_list = []
dup_list = []
s=0
for i in nums:
if i not in final_list and i not in dup_list:
final_list.append(i)
else:
dup_list.append(i)
if i in final_list:
final_list.remove(i)
for i in final_list:
s +=i
return s | sum-of-unique-elements | Runtime beats 95% | Python | NiketaM | 0 | 54 | sum of unique elements | 1,748 | 0.757 | Easy | 25,122 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1980561/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
nums.sort(reverse = True)
print(nums)
unique = []
ans = 0
for i in nums:
freq = nums.count(i)
if freq == 1:
unique.append(i)
print(unique)
for i in unique:
ans = ans + i
return ans | sum-of-unique-elements | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 60 | sum of unique elements | 1,748 | 0.757 | Easy | 25,123 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1962203/Python3-98-faster-with-explanation | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
mapper = {}
for x in nums:
if x in mapper:
mapper[x] += 1
else:
mapper[x] = 1
rsum = 0
for x in mapper:
if mapper[x] == 1:
rsum += x
return rsum | sum-of-unique-elements | Python3, 98% faster with explanation | cvelazquez322 | 0 | 95 | sum of unique elements | 1,748 | 0.757 | Easy | 25,124 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1928269/easy-python-code | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
x = {}
sum = 0
for i in nums:
if i in x:
x[i] += 1
else:
x[i] = 1
for i in x:
if x[i] == 1:
sum += i
return sum | sum-of-unique-elements | easy python code | dakash682 | 0 | 60 | sum of unique elements | 1,748 | 0.757 | Easy | 25,125 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1899338/Python-One-Liner-x2-Clean-and-Simple! | class Solution:
def sumOfUnique(self, nums):
return sum(map(lambda x:x[0],filter(lambda x:x[1]==1,Counter(nums).items()))) | sum-of-unique-elements | Python - One-Liner x2 - Clean and Simple! | domthedeveloper | 0 | 49 | sum of unique elements | 1,748 | 0.757 | Easy | 25,126 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1899338/Python-One-Liner-x2-Clean-and-Simple! | class Solution:
def sumOfUnique(self, nums):
return sum(x for x,y in Counter(nums).items() if y == 1) | sum-of-unique-elements | Python - One-Liner x2 - Clean and Simple! | domthedeveloper | 0 | 49 | sum of unique elements | 1,748 | 0.757 | Easy | 25,127 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1884342/Python-simple-solution-faster-than-79 | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
res = 0
for i in set(nums):
if nums.count(i) == 1:
res += i
return res | sum-of-unique-elements | Python simple solution faster than 79% | alishak1999 | 0 | 64 | sum of unique elements | 1,748 | 0.757 | Easy | 25,128 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1828103/1-Line-Python-Solution-oror-90-Faster-(36ms)-oror-Memory-less-than-50 | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum([x for x,y in Counter(nums).items() if y==1]) | sum-of-unique-elements | 1-Line Python Solution || 90% Faster (36ms) || Memory less than 50% | Taha-C | 0 | 36 | sum of unique elements | 1,748 | 0.757 | Easy | 25,129 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1633544/Python3-One-line-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
return sum(i for i in nums if nums.count(i) == 1) | sum-of-unique-elements | Python3 One-line solution | y-arjun-y | 0 | 121 | sum of unique elements | 1,748 | 0.757 | Easy | 25,130 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1513875/Train-of-Thoughts-while-solving-greater-Build-Intuition | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
#Time Consumed - O(N) and Space Consumed - O(N)
#In comments, we have taken the first test case
from collections import Counter
frequency = Counter(nums) #Counter({2: 2, 1: 1, 3: 1})
add = 0
for i in frequency:
if frequency[i] == 1:
#we will retrieve all elements whose frequency is 1
#and add it to our "add" variable
add += i
return add
#Let us try to optimise it - Since Time Complexity looks decent, let us try to reduce the space to O(1)
#Basic idea is to retrieve all the elements that appeared only once and find their sum
#To do so, we can use 1 for loop and fix nums[i] from 0th index till last index one by one.
#Now, we can check for each nums[i] by searching the entire array to see if it appears again or not
#Time Consumed - O(N^2) and Space Consumed - O(1)
n = len(nums)
answer = 0
for i in range(0, n): #nums[i] will be our fixed character at each iteration
count = 0 #this will count the number of characters not similar to the fixed character
for j in range(0, n): #we will check if nums[i] == nums[j] at any point
if i != j:
if nums[i] != nums[j]:
count += 1
if count == n - 1:
answer += nums[i]
return answer
#As we can see, Space Complexity reduced but Time Complexity shot up. So, Lets try to think harder. | sum-of-unique-elements | Train of Thoughts while solving --> Build Intuition | aarushsharmaa | 0 | 83 | sum of unique elements | 1,748 | 0.757 | Easy | 25,131 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1416145/Python3-Faster-then-93-of-Python3-Solutions | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
s = {}
for i in nums:
if i not in s:
s[i] = 1
else:
s[i] += 1
s1 = 0
for k,v in s.items():
if v == 1:
s1 = s1 + k
return s1 | sum-of-unique-elements | Python3 - Faster then 93% of Python3 Solutions | harshitgupta323 | 0 | 133 | sum of unique elements | 1,748 | 0.757 | Easy | 25,132 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1363129/Python3-Simple-hashmap-Solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d = dict()
k = 0
for i in range(0, len(nums)):
d[nums[i]] = nums.count(nums[i])
for i,j in d.items():
if d.get(i) == 1:
k += i
return k | sum-of-unique-elements | Python3 Simple hashmap Solution | jayswal | 0 | 94 | sum of unique elements | 1,748 | 0.757 | Easy | 25,133 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1183724/python-sol-faster-than-93-less-mem-than-91-O(nlog(n)-%2B-2n) | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
nums.sort()
j = 0
while (j < len(nums) - 1):
cnt = 1
start = j
while(j < len(nums) - 1 and nums[j] == nums[j + 1]):
cnt += 1
j += 1
if (cnt > 1):
nums = nums[0:start] + nums[start + cnt: len(nums)]
j = start - 1
j += 1
return sum(nums) | sum-of-unique-elements | python sol faster than 93% , less mem than 91% [O(nlog(n) + 2n)] | elayan | 0 | 147 | sum of unique elements | 1,748 | 0.757 | Easy | 25,134 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1179261/Python3-simple-solution-faster-than-90-users | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
l = 0
for i in nums:
if nums.count(i) == 1:
l += i
return l | sum-of-unique-elements | Python3 simple solution faster than 90% users | EklavyaJoshi | 0 | 85 | sum of unique elements | 1,748 | 0.757 | Easy | 25,135 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1144006/Python-Easy-Solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
counts=0
final=0
for i in range(len(nums)):
counts = nums.count(nums[i])
if counts==1:
final= final+nums[i]
return(final) | sum-of-unique-elements | Python Easy Solution | YashashriShiral | 0 | 119 | sum of unique elements | 1,748 | 0.757 | Easy | 25,136 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1129999/Python-Solution-Faster-than-96 | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
d = dict()
for i in nums:
if i not in d:
d[i] = 1
else:
d[i] += 1
s = 0
for k, v in d.items():
if d[k] == 1:
s += k
return s | sum-of-unique-elements | Python Solution Faster than 96% | Annushams | 0 | 130 | sum of unique elements | 1,748 | 0.757 | Easy | 25,137 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1113805/Python-clear-pythonic-solution | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
dct = {}
for value in nums:
dct[value] = dct.get(value, 0) + 1
return sum(key for key, value in dct.items() if value == 1) | sum-of-unique-elements | [Python] clear pythonic solution | cruim | 0 | 95 | sum of unique elements | 1,748 | 0.757 | Easy | 25,138 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1067199/Python3-solution-using-count-function | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
sum_ = 0
for i in nums:
if nums.count(i) == 1:
sum_ += i
return sum_ | sum-of-unique-elements | Python3 solution using count function | shreyasdamle2017 | 0 | 75 | sum of unique elements | 1,748 | 0.757 | Easy | 25,139 |
https://leetcode.com/problems/sum-of-unique-elements/discuss/1066076/Python-Counter | class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
c = Counter(nums)
return sum(n for n, c in c.items() if c == 1) | sum-of-unique-elements | Python, Counter | blue_sky5 | 0 | 104 | sum of unique elements | 1,748 | 0.757 | Easy | 25,140 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1056653/Python3-Kadane's-algo | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
ans = mx = mn = 0
for x in nums:
mx = max(mx + x, 0)
mn = min(mn + x, 0)
ans = max(ans, mx, -mn)
return ans | maximum-absolute-sum-of-any-subarray | [Python3] Kadane's algo | ye15 | 10 | 329 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,141 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1157176/Python3-Double-Kadane's | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
min_sum = nums[0]
curr_min = nums[0]
max_sum = nums[0]
curr_max = max_sum
for i in range(1, len(nums)):
curr_max = max(nums[i], curr_max + nums[i])
max_sum = max(curr_max, max_sum)
for i in range(1, len(nums)):
curr_min = min(nums[i], curr_min + nums[i])
min_sum = min(curr_min, min_sum)
return max(abs(max_sum), abs(min_sum)) | maximum-absolute-sum-of-any-subarray | Python3 Double Kadane's | victor72 | 5 | 246 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,142 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1597152/Greedy-and-Easy-Approach | class Solution:
def maxAbsoluteSum(self, A):
ma,mi,res = 0,0,0
for a in A:
ma = max(0,ma+a)
mi = min(0,mi+a)
res = max(res,ma,-mi)
return res | maximum-absolute-sum-of-any-subarray | 📌📌 Greedy and Easy Approach 🐍 | abhi9Rai | 4 | 175 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,143 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1120050/Python3-or-Short-and-Simple-or-Two-passes-to-the-function-to-find-maximum-sum-of-any-subarray | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
def maxSum(nums: List[int]) -> int:
result, total = nums[0], 0
for num in nums:
total += num
if total < 0: total = 0
result = max(result, total)
return result
invNums = [-num for num in nums]
return max(maxSum(nums), maxSum(invNums)) | maximum-absolute-sum-of-any-subarray | Python3 | Short and Simple | Two passes to the function to find maximum sum of any subarray | wind_pawan | 1 | 89 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,144 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1053133/Python-O(1)-Space-O(n)-Time-Clean-and-Simple! | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
max_sub = max_min = max_pos = 0
for n in nums:
max_min = min(n, max_min + n)
max_pos = max(n, max_pos + n)
max_sub = max(max_sub, max_pos, abs(max_min))
return max_sub | maximum-absolute-sum-of-any-subarray | Python O(1) Space, O(n) Time, Clean and Simple! | Cavalier_Poet | 1 | 101 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,145 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/2847271/MAXIMUM-ABSOLUTE-SUM-OF-ANY-SUBARRAY | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
ans = 0
maxi=0
mini=0
for x in nums:
maxi = max(maxi + x, 0)
mini = min(mini + x, 0)
ans = max(ans, maxi, -mini)
return ans | maximum-absolute-sum-of-any-subarray | MAXIMUM ABSOLUTE SUM OF ANY SUBARRAY | avinashsingh29 | 0 | 1 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,146 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/2845347/Python3-or-Maximum-and-Minimum-or-Explanation | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
currMax,currMin = nums[0],nums[0]
ans = max(0,abs(nums[0]))
n = len(nums)
for i in range(1,n):
currMax = max(currMax + nums[i],nums[i])
currMin = min(currMin + nums[i],nums[i])
ans = max(ans,abs(currMax),abs(currMin))
return ans | maximum-absolute-sum-of-any-subarray | [Python3] | Maximum and Minimum | Explanation | swapnilsingh421 | 0 | 1 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,147 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/2754825/Python-O(1)-space-Solution | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
mx=nums[0]
s=0
for i in nums:
s+=i
mx=max(s,mx)
if s<0:
s=0
mn=nums[0]
s=0
for i in nums:
s+=i
mn = min(mn,s)
if s>0:
s=0
return max(mx,abs(mn)) | maximum-absolute-sum-of-any-subarray | Python O(1) space Solution | prateekgoel7248 | 0 | 6 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,148 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/2747440/Python3-or-O(n)-Solution | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
minNumber = 0
maxNumber = 0
acc = 0
for i in range(len(nums)):
acc += nums[i]
minNumber = min(minNumber,acc)
maxNumber = max(maxNumber,acc)
return abs(maxNumber-minNumber) | maximum-absolute-sum-of-any-subarray | Python3 | O(n) Solution | ty2134029 | 0 | 1 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,149 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/2622660/Simple-Kadane-Algo-or-python-or-Simple-to-understand | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
max_far=-10**12
max_end=0
## Finding maximum subarray sum
for i in range(0,len(nums)):
max_end+=nums[i]
max_far=max(max_far,max_end)
if max_end<0:
max_end=0
min_far=10**12
min_end=0
##finding minimum subarray sum
for i in range(0,len(nums)):
min_end+=nums[i]
min_far=min(min_far,min_end)
if min_end>0:
min_end=0
return max(max_far,abs(min_far)) | maximum-absolute-sum-of-any-subarray | Simple Kadane Algo | python | Simple to understand | Mom94 | 0 | 10 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,150 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1479439/Python-3-or-Kadane's-Algorithm-DP-or-Explanation | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
ans = neg = pos = 0
for num in nums:
pos = max(pos + num, num)
neg = min(neg + num, num)
ans = max(ans, -neg, pos)
return ans | maximum-absolute-sum-of-any-subarray | Python 3 | Kadane's Algorithm, DP | Explanation | idontknoooo | 0 | 151 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,151 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1479439/Python-3-or-Kadane's-Algorithm-DP-or-Explanation | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
neg = pos = 0
return max(max(pos:=max(pos + num, num), abs(neg:=min(neg + num, num))) for num in nums) | maximum-absolute-sum-of-any-subarray | Python 3 | Kadane's Algorithm, DP | Explanation | idontknoooo | 0 | 151 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,152 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1098376/Easy-Solution | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
maxi=0
sumPos=0
sumNeg=0
mini=0
for i in range(len(nums)):
sumPos=max(nums[i],sumPos+nums[i])
sumNeg=min(nums[i],sumNeg+nums[i])
mini=min(mini,sumNeg)
maxi=max(maxi,sumPos,abs(mini))
return maxi | maximum-absolute-sum-of-any-subarray | Easy Solution | coder1311 | 0 | 95 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,153 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1052543/Python-Easy-Solution | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
mini,maxi = 0,0
positiveSum,negativeSum = 0,0
for num in nums:
positiveSum += num
maxi = max(positiveSum,maxi)
if positiveSum < 0:
positiveSum = 0
negativeSum += num
mini = min(negativeSum,mini)
if negativeSum > 0:
negativeSum = 0
return max(abs(mini),maxi) | maximum-absolute-sum-of-any-subarray | Python Easy Solution | idebdeep | 0 | 85 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,154 |
https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1052573/Kadane's-Algorithm | class Solution:
def maxAbsoluteSum(self, nums: List[int]) -> int:
def kadane(x):
cmax = 0
gmax = 0
for i in x:
if cmax < 0:
cmax = i
else:
cmax+=i
gmax = max(cmax, gmax)
return gmax
return max(kadane(nums), kadane(-i for i in nums)) | maximum-absolute-sum-of-any-subarray | Kadane's Algorithm | lokeshsenthilkumar | -5 | 90 | maximum absolute sum of any subarray | 1,749 | 0.583 | Medium | 25,155 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1056664/Python3-3-approaches | class Solution:
def minimumLength(self, s: str) -> int:
dd = deque(s)
while len(dd) >= 2 and dd[0] == dd[-1]:
ch = dd[0]
while dd and dd[0] == ch: dd.popleft()
while dd and dd[-1] == ch: dd.pop()
return len(dd) | minimum-length-of-string-after-deleting-similar-ends | [Python3] 3 approaches | ye15 | 2 | 74 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,156 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1056664/Python3-3-approaches | class Solution:
def minimumLength(self, s: str) -> int:
while len(s) >= 2 and s[0] == s[-1]:
s = s.strip(s[0])
return len(s) | minimum-length-of-string-after-deleting-similar-ends | [Python3] 3 approaches | ye15 | 2 | 74 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,157 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1056664/Python3-3-approaches | class Solution:
def minimumLength(self, s: str) -> int:
lo, hi = 0, len(s)-1
while lo < hi and s[lo] == s[hi]:
ch = s[lo]
while lo <= hi and s[lo] == ch: lo += 1
while lo <= hi and s[hi] == ch: hi -= 1
return hi - lo + 1 | minimum-length-of-string-after-deleting-similar-ends | [Python3] 3 approaches | ye15 | 2 | 74 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,158 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/2846330/Python-oror-96.67-Faster-oror-Two-Pointers-oror-O(n)-Solution | class Solution:
def minimumLength(self, s: str) -> int:
i,j=0,len(s)-1
while i<j and s[i]==s[j]:
t=s[i]
while i<len(s) and s[i]==t:
i+=1
while j>=0 and s[j]==t:
j-=1
if j<i:
return 0
return j-i+1 | minimum-length-of-string-after-deleting-similar-ends | Python || 96.67% Faster || Two Pointers || O(n) Solution | DareDevil_007 | 1 | 2 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,159 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1490796/Python-3-or-Two-Pointers-or-Explanation | class Solution:
def minimumLength(self, s: str) -> int:
l, r = 0, len(s) - 1
while l < r:
if s[l] == s[r]: c = s[l] # find the same char
else: break
while l < r and s[l] == c: # exhaust left side
l += 1
while l < r and s[r] == c: # exhaust right side
r -= 1
if s[r] == c: # if pattern like 'aa' is happening, return 0
return 0
return r - l + 1 | minimum-length-of-string-after-deleting-similar-ends | Python 3 | Two Pointers | Explanation | idontknoooo | 1 | 80 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,160 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1052592/Python-Simple-Solution | class Solution:
def minimumLength(self, s: str) -> int:
d = collections.deque(s)
while len(d) > 1 and d[0] == d[-1]:
current = d[0]
while len(d) > 0 and d[0] == current:
d.popleft()
while len(d) > 0 and d[-1] == current:
d.pop()
return len(d) | minimum-length-of-string-after-deleting-similar-ends | [Python] Simple Solution | lokeshsenthilkumar | 1 | 55 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,161 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1898067/Python-easy-to-read-and-understand-or-two-pointers | class Solution:
def minimumLength(self, s: str) -> int:
n = len(s)
i, j = 0, n-1
while i < j and s[i] == s[j]:
ch = s[i]
while i < n and s[i] == ch:
i += 1
while j > 0 and s[j] == ch:
j -= 1
ans = j-i+1
return 0 if ans < 0 else ans | minimum-length-of-string-after-deleting-similar-ends | Python easy to read and understand | two-pointers | sanial2001 | 0 | 31 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,162 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1296950/Python-3-Solutions-(Easy) | class Solution:
def minimumLength(self, s: str) -> int:
'''
#Brute Force Solution -- O(N^2) & O(N) ~2880ms
#Using array ( Naive Approach )
arr = list(s)
while len(arr)>1:
i = 0
j = len(arr)-1
if arr[i]!=arr[j]:
break
temp = arr[i]
while len(arr)>0 and i<=j and arr[i]==temp:
arr.pop(0) #Rearranging array takes O(N)
j = len(arr)-1
while len(arr)>0 and j>=i and arr[j]==temp:
arr.pop()
j-=1
#print("".join(arr))
return len(arr)
'''
'''
#10 times Faster than previous Solution ~216ms
#Using Deque -- Level 1 Optimisation
#O(N) due to O(1) in popleft -- Time & O(N) -- Space
arr = collections.deque()
for i in s:
arr.append(i)
while len(arr)>1:
i = 0
j = len(arr)-1
if arr[i]!=arr[j]:
break
temp = arr[i]
while len(arr)>0 and i<=j and arr[i]==temp:
arr.popleft() #O(1)
j = len(arr)-1
while len(arr)>0 and j>=i and arr[j]==temp:
arr.pop()
j-=1
return len(arr)
'''
#O(N) and O(1) -- Beating 95% in speed ~ 85ms
#Using 2 Pointers -- Max Optimisation
if len(s)==1:
return 1
i=0
j = len(s)-1
while i<j:
if s[i]!=s[j]:
break
temp = s[i]
while i<=j and s[i]==temp:
i+=1
while j>=i and s[j]==temp:
j-=1
#print(j,i)
return j-i+1 | minimum-length-of-string-after-deleting-similar-ends | Python 3 Solutions (Easy) | iamkshitij77 | 0 | 60 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,163 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1052627/Two-pointer-or-O(N)-Time-or-O(1)-Space | class Solution:
def minimumLength(self, s: str) -> int:
if len(s) == 1:
return 1
i = 0
j = len(s) - 1
while i < j:
if s[i] == s[j]:
while i < j and s[i] == s[i + 1]:
i += 1
while i < j and s[j] == s[j - 1]:
j -= 1
i += 1
j -= 1
else:
return j - i + 1
if i == j:
return 1
return 0 | minimum-length-of-string-after-deleting-similar-ends | Two pointer | O(N) Time | O(1) Space | rohanmathur91 | 0 | 53 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,164 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1052600/Python-or-Two-Pointer-or | class Solution:
def minimumLength(self, s: str) -> int:
s=list(s)
i,j =0,len(s)-1
while i<j:
s1 = s[i]
s2 = s[j]
if s1!=s2:
return j-i+1
if s[i]==s[j]:
while i<j and s[i]==s[i+1]:
i+=1
while j>i and s[j]==s[j-1] :
j-=1
i+=1
j-=1
if i==j:
return j-i+1
else:
return 0 | minimum-length-of-string-after-deleting-similar-ends | Python | Two Pointer | | rajsinxh | 0 | 24 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,165 |
https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1052555/Python-or-O(n)-timeor-O(1)-Space-or-Easy-Solution | class Solution:
def minimumLength(self, s: str) -> int:
left = 0
right = len(s)-1
if len(s) == 1:
return 1
while left < right and s[left] == s[right] :
while left < right and s[left] == s[left + 1]:
left+=1
if left == right:
return 0
left+=1
while left < right and s[right] == s[right - 1]:
right-=1
right-=1
return right - left + 1
`` | minimum-length-of-string-after-deleting-similar-ends | Python | O(n) time| O(1) Space | Easy Solution | idebdeep | 0 | 28 | minimum length of string after deleting similar ends | 1,750 | 0.436 | Medium | 25,166 |
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1103634/Python3-(DP)-Simple-Solution-Explained | class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
# The number of events
n = len(events)
# Sort the events in chronological order
events.sort()
# k is the number of events we can attend
# end is the last event we attended's END TIME
# event_index is the current event we are checking
@lru_cache(None)
def dp(end: int, event_index: int, k: int):
# No more events left or we have checked all possible events
if k == 0 or event_index == n:
return 0
event = events[event_index]
event_start, event_end, event_value = event
# Can we attend this event?
# Does its start time conflict with the previous events end time?
# If the start time is the same as the end time we cannot end as well (view example 2)
if event_start <= end:
# Could not attend, check the next event
return dp(end, event_index + 1, k)
# We made it here, so we can attend!
# Two possible options, we either attend (add the value) or do not attend this event
# Value for attending versus the value for skipping
attend = event_value + dp(event_end, event_index + 1, k - 1)
skip = dp(end, event_index + 1, k)
# Get the best option
return max(attend, skip)
# Clear cache to save memory
dp.cache_clear()
return dp(0, 0, k) | maximum-number-of-events-that-can-be-attended-ii | [Python3] (DP) Simple Solution Explained | scornz | 11 | 637 | maximum number of events that can be attended ii | 1,751 | 0.56 | Hard | 25,167 |
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1056655/Python3-knapsack | class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events.sort()
starts = [i for i, _, _ in events]
@cache
def fn(i, k):
"""Return max score of attending k events from events[i:]."""
if i == len(events) or k == 0: return 0
ii = bisect_left(starts, events[i][1]+1)
return max(fn(i+1, k), events[i][2] + fn(ii, k-1))
return fn(0, k) | maximum-number-of-events-that-can-be-attended-ii | [Python3] knapsack | ye15 | 2 | 249 | maximum number of events that can be attended ii | 1,751 | 0.56 | Hard | 25,168 |
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1055283/Python-3-simple-DP-with-memorization | class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events.sort()
starts = [x[0] for x in events]
@lru_cache(None)
def dp(i, k):
if k == 0 or i >= len(events):
return 0
return max(events[i][-1] + dp(bisect.bisect_right(starts, events[i][1]), k - 1), dp(i+1, k))
return dp(0, k) | maximum-number-of-events-that-can-be-attended-ii | [Python 3] simple DP with memorization | chestnut890123 | 2 | 227 | maximum number of events that can be attended ii | 1,751 | 0.56 | Hard | 25,169 |
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1059715/Python3-O(n*k-%2B-n*log(n))-explained-no-bisect-no-recursion | class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
events,n=sorted(events, key=lambda e:e[1]), len(events)
events_start_sorted = sorted([(e[0], i) for i,e in enumerate(events)])
preceding,j = [-1]*n,0
for start, index in events_start_sorted:
while events[j][1]<start:
j+=1
preceding[index]=j-1
dp,res = [0]*n,0
for j in range(1, k+1):
max_value=-1
dp_next=[-1]*n
for i in range(n):
if j==1:
max_value=max(max_value, events[i][2])
elif preceding[i]>=0 and dp[preceding[i]]>=0:
max_value=max(max_value, dp[preceding[i]]+events[i][2])
dp_next[i]=max_value
dp=dp_next
res=max(res, max_value)
return res | maximum-number-of-events-that-can-be-attended-ii | [Python3] O(n*k + n*log(n)) explained; no bisect; no recursion | vilchinsky | 1 | 251 | maximum number of events that can be attended ii | 1,751 | 0.56 | Hard | 25,170 |
https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/2671321/Python3-or-DP-%2B-Binary-Search | class Solution:
def maxValue(self, events: List[List[int]], k: int) -> int:
n=len(events)
events.sort()
@lru_cache(None)
def dfs(ind,k):
if ind==n or k==0:
return 0
ans=dfs(ind+1,k)
nextInd=bisect.bisect_left(events,[events[ind][1]+1])
ans=max(ans,events[ind][2]+dfs(nextInd,k-1))
return ans
return dfs(0,k) | maximum-number-of-events-that-can-be-attended-ii | [Python3] | DP + Binary Search | swapnilsingh421 | 0 | 24 | maximum number of events that can be attended ii | 1,751 | 0.56 | Hard | 25,171 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053871/Python-Slicing-(easy-to-understand) | class Solution:
def check(self, nums: List[int]) -> bool:
i = 0
while i<len(nums)-1:
if nums[i]>nums[i+1]: break # used to find the rotated position
i+=1
rotated = nums[i+1:]+nums[:i+1]
for i,e in enumerate(rotated):
if i<len(rotated)-1 and e>rotated[i+1]: # check that rerotated array sorted or not
return False
return True | check-if-array-is-sorted-and-rotated | Python - Slicing (easy to understand) | qwe9 | 12 | 966 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,172 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053534/Python3-count-O(N) | class Solution:
def check(self, nums: List[int]) -> bool:
cnt = 0
for i in range(1, len(nums)):
if nums[i-1] > nums[i]: cnt += 1
return cnt == 0 or cnt == 1 and nums[-1] <= nums[0] | check-if-array-is-sorted-and-rotated | [Python3] count O(N) | ye15 | 11 | 885 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,173 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053534/Python3-count-O(N) | class Solution:
def check(self, nums: List[int]) -> bool:
cnt = 0
for i in range(len(nums)):
if nums[i-1] > nums[i]: cnt += 1
return cnt <= 1 | check-if-array-is-sorted-and-rotated | [Python3] count O(N) | ye15 | 11 | 885 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,174 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1060138/Python-Solution | class Solution:
def check(self, nums: List[int]) -> bool:
# sort the list
numsSorted = sorted(nums)
# iterate over all list elements
for i in range(len(nums)):
# check every rotate option with the sorted list
# if found return True
if nums[i:] + nums[:i] == numsSorted:
return True
return False | check-if-array-is-sorted-and-rotated | Python Solution | rushirg | 7 | 473 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,175 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1859852/Python3-or-Easy-and-Concise | class Solution:
def check(self, num: List[int]) -> bool:
ct=0
for i in range(1,len(num)):
if num[i-1]>num[i]:
ct+=1
if num[len(num)-1]>num[0]:
ct+=1
return ct<=1 | check-if-array-is-sorted-and-rotated | Python3 | Easy and Concise | Anilchouhan181 | 2 | 161 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,176 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1753831/Easy-Python-Solution | class Solution:
def check(self, nums: List[int]) -> bool:
for i in range(len(nums)):
if nums[i:] + nums[:i] == sorted(nums):
return True
return False | check-if-array-is-sorted-and-rotated | Easy Python Solution | MengyingLin | 1 | 72 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,177 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1707223/python3-esasy-solution | class Solution:
def check(self, nums: List[int]) -> bool:
res = 0
for i in range(1,len(nums)):
if nums[i-1] > nums[i]:
res += 1
if nums[-1] > nums[0]:
res += 1
return res <= 1 | check-if-array-is-sorted-and-rotated | python3 esasy solution | fobos_hero | 1 | 89 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,178 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1138921/99-speed-80-memory | class Solution:
def check(self, nums: List[int]) -> bool:
if nums == sorted(nums):
return True
idx = 0
for i in range(1, len(nums)):
if nums[i] < nums[idx]:
idx = i
break
idx += 1
return nums[idx:] + nums[:idx] == sorted(nums) | check-if-array-is-sorted-and-rotated | 99% speed, 80% memory | JulianaYo | 1 | 139 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,179 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1069214/Python3-simple-solution | class Solution:
def check(self, nums: List[int]) -> bool:
original = sorted(nums)
for i in range(0,len(nums)):
a = nums[i-1:] + nums[:i-1]
if a == original:
return True
return False | check-if-array-is-sorted-and-rotated | Python3 simple solution | EklavyaJoshi | 1 | 130 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,180 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1066102/Python-ONE-LINER!-Time%3A-O(N)-Space-O(1). | class Solution:
def check(self, nums: List[int]) -> bool:
return sum(nums[i] < nums[i-1] for i in range(len(nums))) <= 1 | check-if-array-is-sorted-and-rotated | Python ONE LINER! Time: O(N), Space O(1). | blue_sky5 | 1 | 105 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,181 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2840280/Python3-Beats-92.17-2-liner-(technically...) | class Solution:
def check(self, nums, cnt=0):
for i in range(len(nums)): cnt += nums[i]<nums[i-1]
return cnt<2 | check-if-array-is-sorted-and-rotated | [Python3] [Beats 92.17%] 2-liner (technically...) | U753L | 0 | 1 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,182 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2829047/Python-Solution-Only-check-2-conditions-oror-explained | class Solution:
def check(self, nums: List[int]) -> bool:
c=0
#FIRST CONDITION
for i in range(1,len(nums)):
#if array is sorted and rotated then only one nums[i-1]>nums[i] will be true
#and c will equal to 1
if nums[i-1]>nums[i]:
c+=1
#SECOND CONDITION
#if nums[first]>=nums[last] that means array is rotated and sorted otherwise c will increment
if nums[0]<nums[len(nums)-1]:
c+=1
#c==0 when all elements of nums are same
#c==1 when only one element is greater than other in whole nums(for loop will give)
if c==0 or c==1:
return True
else:
return False | check-if-array-is-sorted-and-rotated | Python Solution - Only check 2 conditions || explained✔ | T1n1_B0x1 | 0 | 1 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,183 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2718523/Easy-python-code-or-99.6-time-and-96.3-space-complexity | class Solution:
def check(self, nums: List[int]) -> bool:
l=[]
for i in range(0,len(nums)):
l.append(nums[i])
l.sort()
l1=l
for i in range(0,len(nums)):
l2=l1[len(nums)-1:]+l1[0:-1]
if l2==nums:
return True
else:
l1=l2
return False | check-if-array-is-sorted-and-rotated | Easy python code | 99.6% time and 96.3% space complexity | vishwas1451 | 0 | 8 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,184 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2690982/Easy-To-Understand-Python-Solution | class Solution:
def check(self, nums: List[int]) -> bool:
numsSorted = "A".join([str(x) for x in sorted(nums)])
nums = "A".join([str(x) for x in nums])
return numsSorted in nums + "A" + nums | check-if-array-is-sorted-and-rotated | Easy To Understand Python Solution | scifigurmeet | 0 | 5 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,185 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2623765/using-helper-function-(slow) | class Solution:
def check(self, nums: List[int]) -> bool:
# create a helper that rotates by a width x
# create a second array using sorted()
# rotate sorted arr from 0 to the size of the array
# if nums equals that return True
# otherwise return False after iteration
# time O(n) space O(n)
ascending = sorted(nums)
n = len(nums)
def rotate(x, arr):
rotated = arr.copy()
for i in range(n):
rotated[i] = arr[(i + x) % n]
return rotated
for i in range(n):
if rotate(i, ascending) == nums:
return True
return False | check-if-array-is-sorted-and-rotated | using helper function (slow) | andrewnerdimo | 0 | 4 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,186 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2284192/Beginner-Friendly-Solution-oror-28ms-Faster-Than-99-oror-Python | class Solution:
def check(self, nums: List[int]) -> bool:
bruh = 0
# For each iteration of the for-loop below, it could be in one of two states:
# bruh == 0 --> Our array is in non-descending order so far. This is good.
# bruh == 1 --> An anomaly (rotation point) has been found in the previous iteration.
# However, if another is found while bruh == 1, then we must return False.
for i in range(1, len(nums)):
if bruh == 0:
if nums[i] < nums[i - 1]:
if nums[i] > nums[0]:
return False
bruh += 1
elif bruh == 1:
if nums[i] < nums[i - 1] or nums[i] > nums[0]:
return False
return True | check-if-array-is-sorted-and-rotated | Beginner Friendly Solution || 28ms, Faster Than 99% || Python | cool-huip | 0 | 91 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,187 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2154707/Python-or-Easy-Beginner-approach-92-faster | class Solution:
def check(self, nums: List[int]) -> bool:
'''
If it is sorted and rotated then only at one position it will fails to follow up a condition:=>
nums[i] > nums[i+1]. And if it is not then that means it is not (sorted and rotated).
'''
count = 0
n = len(nums)
for i in range(n):
if nums[i] > nums[(i+1) % n]:
count += 1
if count > 1:
return False
return True | check-if-array-is-sorted-and-rotated | Python | Easy Beginner approach 92% faster | __Asrar | 0 | 86 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,188 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/2000703/Python-Simple-and-Concise!-Flag | class Solution:
def check(self, nums):
flag = False
for a,b in pairwise(nums):
if a > b:
if flag: return False
else: flag = True
return not flag or nums[len(nums)-1] <= nums[0] | check-if-array-is-sorted-and-rotated | Python - Simple and Concise! Flag | domthedeveloper | 0 | 79 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,189 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1984837/Python3-97-faster-with-explanation | class Solution:
def check(self, nums: List[int]) -> bool:
prev = nums[0]
for i in range(1, len(nums)):
if nums[i] < prev:
nums[:] = nums[i:] + nums[:i]
break
prev= nums[i]
prev = nums[0]
for i in range(1, len(nums)):
if prev > nums[i]:
return False
prev = nums[i]
return True | check-if-array-is-sorted-and-rotated | Python3, 97% faster with explanation | cvelazquez322 | 0 | 108 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,190 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1910403/Python-Solution | class Solution:
def check(self, nums: List[int]) -> bool:
return str(sorted(nums))[1:-1] in str(nums + nums)[1:-1] | check-if-array-is-sorted-and-rotated | Python Solution | hgalytoby | 0 | 55 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,191 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1852806/Python-dollarolution | class Solution:
def check(self, nums: List[int]) -> bool:
n = 2*nums
for i in range(len(nums)):
if n[i] == min(nums):
flag = sorted(nums) == n[i:i+len(nums)]
if flag:
return flag
return flag | check-if-array-is-sorted-and-rotated | Python $olution | AakRay | 0 | 39 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,192 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1591951/Python-3-O(n)-time | class Solution:
def check(self, nums: List[int]) -> bool:
flag = False
for i in range(1, len(nums)):
if nums[i-1] > nums[i]:
if flag:
return False
flag = True
if flag and nums[i] > nums[0]:
return False
return True | check-if-array-is-sorted-and-rotated | Python 3 O(n) time | dereky4 | 0 | 142 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,193 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1555042/Literal-Python-no-tricks | class Solution:
def check(self, nums: List[int]) -> bool:
if len(nums) < 2:
return True
x = 1
while nums[x - 1] <= nums[x]:
x += 1
if x == len(nums):
return True
while x + 1 < len(nums):
if nums[x] > nums[x + 1]:
return False
x += 1
return nums[-1] <= nums[0] | check-if-array-is-sorted-and-rotated | Literal Python, no tricks | mousun224 | 0 | 100 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,194 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1441791/Python3-Faster-Than-98.52 | class Solution:
def check(self, n: List[int]) -> bool:
if n == sorted(n):
return True
i, mx = 0, max(n)
while i < len(n) - 1:
if mx == n[i]:
i += 1
continue
if n[i] > n[i + 1]:
return False
i += 1
if n[-1] != max:
if n[-1] <= n[0]:
return True
return False | check-if-array-is-sorted-and-rotated | Python3 Faster Than 98.52% | Hejita | 0 | 84 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,195 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1363101/Python-fast-and-simple-O(n)-time-1-pass-O(1)-space | class Solution:
def check(self, nums: List[int]) -> bool:
ngaps = 0
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
ngaps += 1
if ngaps > 1:
return False
return ngaps == 0 or nums[0] >= nums[-1] | check-if-array-is-sorted-and-rotated | Python, fast and simple, O(n) time 1 pass, O(1) space | MihailP | 0 | 143 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,196 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1264384/Python-3-Using-pivot-element | class Solution:
def check(self, nums: List[int]) -> bool:
if len(nums)<2:
return True
pivot, n= 0, len(nums)
# For roated array there should be a pivot element which is greater than the elements in right.
# Once we found pivot we know how many times array was rotated.
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
pivot = i+1
break
if pivot == 0:
return True
for i in range(1,len(nums)):
if nums[(i+pivot)%n-1] > nums[(i+pivot)%n]:
return False
return True | check-if-array-is-sorted-and-rotated | Python 3- Using pivot element | swatishukla | 0 | 92 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,197 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1255211/python-solution-using-slicing | class Solution:
def check(self, nums: List[int]) -> bool:
p=sorted(nums)
num= list(filter(lambda x: p[x] == nums[0], range(len(nums))))
if nums.count(nums[0])>1:
for m in num:
if p[m:]+p[:m]==nums:
return(True)
return(False)
else:
m=p.index(nums[0])
return( p[m:]+p[:m]==nums) | check-if-array-is-sorted-and-rotated | python solution using slicing | janhaviborde23 | 0 | 105 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,198 |
https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1187501/python-sol-faster-than-92-less-mem-than-92-O(n)-time | class Solution:
def check(self, nums: List[int]) -> bool:
j = 0
while (j < len(nums) - 1 and nums[j] <= nums[j + 1]):
j += 1
res = nums[j + 1 : len(nums)] + nums[0:j + 1]
for i in range(len(res) - 1):
if res[i] > res[i + 1]:
return False
return True | check-if-array-is-sorted-and-rotated | python sol faster than 92% , less mem than 92% O(n) time | elayan | 0 | 155 | check if array is sorted and rotated | 1,752 | 0.493 | Easy | 25,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.