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/gas-station/discuss/1706695/Python-Greedy-solution
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 start_point, total = 0, 0 for i in range(len(cost)): total += gas[i] - cost[i] if total < 0: total = 0 start_point = i+1 return start_point
gas-station
Python , Greedy solution
pradeep288
0
85
gas station
134
0.451
Medium
1,700
https://leetcode.com/problems/gas-station/discuss/1706240/Simple-Python-Solution-in-O(N)-Time
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: l=len(gas) totalgas=0 currentgas=0 start=0 for i in range(l): currentgas = currentgas + gas[i] - cost[i] totalgas = totalgas + gas[i] - cost[i] if currentgas<0: currentgas=0 start=i+1 if totalgas>=0: return start else: return -1
gas-station
🚗🚗 Simple [Python] ✅ Solution in O(N) Time ⛽⛽ 🔥✔✔
ASHOK_KUMAR_MEGHVANSHI
0
32
gas station
134
0.451
Medium
1,701
https://leetcode.com/problems/gas-station/discuss/1705783/python3-ez-greedy-solution
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas) < sum(cost): return -1 gas.append(gas[0]) cost.append(cost[0]) cache = [] for i in range(len(gas)): cache.append(gas[i] - cost[i]) gas_in_car = 0 max_gas_seen = 0 output = 0 for i in range(len(cache)): num = cache[i] if gas_in_car + num < 0: gas_in_car = 0 output = i + 1 else: gas_in_car += num if gas_in_car > max_gas_seen: max_gas_seen = gas_in_car return output % (len(cache)-1)
gas-station
python3 ez greedy solution
yingziqing123
0
91
gas station
134
0.451
Medium
1,702
https://leetcode.com/problems/gas-station/discuss/1669794/Python-one-pass
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(cost) > sum(gas): return -1 amt = 0 min_amt = gas[0] min_idx = 0 for i in range(len(gas)): amt += gas[i] - cost[i] if amt < min_amt: min_amt = amt min_idx = i return (min_idx + 1) % len(gas)
gas-station
Python, one pass
blue_sky5
0
125
gas station
134
0.451
Medium
1,703
https://leetcode.com/problems/gas-station/discuss/1571412/Sliding-Window-Python3-beginner-level-solution-with-helper-function-beats-62-submissions
class Solution: def forwarding(self, stops: list, costs: list, length: int) -> object: # var reservation tank = 0 # enumerate for var in range(length): tank += stops[var] - costs[var] if tank < 0: return var return True def canCompleteCircuit(self, stops: List[int], costs: List[int]) -> int: # check if impossible to achieve significantly if sum(stops) < sum(costs): return -1 # var reservation driving, length = 0, len(costs) # validate by each start`1```` while driving < length: # if start fill can not converage cost, step forward if stops[driving] < costs[driving]: driving += 1 continue # re-create route sequence add, use = stops[driving:] + stops[:driving + 1], costs[driving:] + costs[:driving + 1] x = self.forwarding(add, use, length) if type(x) == int: driving += x else: return driving # catch infeasible return -1
gas-station
Sliding Window, Python3 - beginner level solution with helper function, beats 62% submissions
kaijCH
0
158
gas station
134
0.451
Medium
1,704
https://leetcode.com/problems/gas-station/discuss/1077348/Python%3A-Brute-Force-Solution-Easy-to-Understand
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: for i in range(0,len(gas)): crossed=0 balance=gas[i] current=i while(crossed<len(gas)): if(balance<cost[current]): break else: crossed+=1 current+=1 if(current>=len(gas)): current=0+len(gas)-current if(current==0): balance=balance-cost[len(gas)-1]+gas[current] else: balance=balance-cost[current-1]+gas[current] # print(balance) if(crossed==len(gas)): return i return -1
gas-station
Python: Brute Force Solution Easy to Understand
smjayasurya1997
0
128
gas station
134
0.451
Medium
1,705
https://leetcode.com/problems/gas-station/discuss/685992/O(N)-Python3-Solution
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if sum(gas)<sum(cost): return -1 n=len(gas) minn=float('inf') #Variable to track the largest cumulative gas deficit debt=0 #Variable indicating the gas deficit at each station for i in range(n): debt+=gas[i]-cost[i] if debt<minn: minn=debt index=i return index+1 if index <n-1 else 0 #return the station right after the one with the largest cumulative deficit
gas-station
O(N) Python3 Solution
Uyiosa
0
89
gas station
134
0.451
Medium
1,706
https://leetcode.com/problems/candy/discuss/2234828/Python-oror-Two-pass-oror-explanation-oror-intuition-oror-greedy
class Solution: def candy(self, ratings: List[int]) -> int: n=len(ratings) temp = [1]*n for i in range(1,n): if(ratings[i]>ratings[i-1]): temp[i]=temp[i-1]+1 if(n>1): if(ratings[0]>ratings[1]): temp[0]=2 for i in range(n-2,-1,-1): if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]): temp[i]=temp[i+1]+1 return sum(temp)
candy
Python || Two pass || explanation || intuition || greedy
palashbajpai214
11
1,200
candy
135
0.408
Hard
1,707
https://leetcode.com/problems/candy/discuss/2235501/Easy-Python-Solution-or-Candy
class Solution: def candy(self, ratings: List[int]) -> int: length = len(ratings) candies = [1] * length for i in range(1, length): if ratings[i] > ratings[i-1] and candies[i] <= candies[i-1]: candies[i] = candies[i-1] + 1 for i in range(length - 2, -1, -1): if ratings[i] > ratings[i + 1] and candies[i] <= candies[i+1]: candies[i] = candies[i+1] + 1 return sum(candies)
candy
Easy Python Solution | Candy
nishanrahman1994
8
739
candy
135
0.408
Hard
1,708
https://leetcode.com/problems/candy/discuss/1301339/Candy-Python-144ms-runtime-2-solutions
class Solution: def candy(self, ratings: List[int]) -> int: lenratings = len(ratings) # call len only once. It is used 3 times ans = [1] * lenratings for i in range(1, lenratings): if ratings[i] > ratings[i-1]: ans[i] = ans[i-1] + 1 for i in range(lenratings-2, -1, -1): a = i+1 # a is used 2 times in if # compare rantings and candys is faster than use "max" to calculate. if ratings[i] > ratings[a] and ans[i] <= ans[a]: ans[i] = ans[a] + 1 return sum(ans)
candy
Candy [Python] 144ms runtime 2 solutions
argoida
7
209
candy
135
0.408
Hard
1,709
https://leetcode.com/problems/candy/discuss/1301339/Candy-Python-144ms-runtime-2-solutions
class Solution: def candy(self, ratings: list) -> int: lenratings = len(ratings) # call len only once. It is used 3 times ans = [1] * lenratings b = [] for i in range(1, lenratings): if ratings[i] > ratings[i-1]: ans[i] = ans[i-1] + 1 else: b.append(i-1) b.reverse() for i in b: a = i+1 # a is used 2 times in if # compare rantings and candys is faster than use "max" to calculate. if ratings[i] > ratings[a] and ans[i] <= ans[a]: ans[i] = ans[a] + 1 return sum(ans)
candy
Candy [Python] 144ms runtime 2 solutions
argoida
7
209
candy
135
0.408
Hard
1,710
https://leetcode.com/problems/candy/discuss/636991/Simple-Python-Solution-Runtime-O(n)
class Solution: def candy(self, ratings: List[int]) -> int: left=[1]*(len(ratings)) right=[1]*len(ratings) for i in range(1,len(ratings)): if ratings[i]>ratings[i-1]: left[i]=left[i-1]+1 for i in range(len(ratings)-2, -1,-1): if ratings[i]>ratings[i+1]: right[i]=right[i+1]+1 total=[0]*len(ratings) for i in range(len(ratings)): total[i]=max(left[i], right[i]) return sum(total)
candy
Simple Python Solution Runtime- O(n)
Ayu-99
3
119
candy
135
0.408
Hard
1,711
https://leetcode.com/problems/candy/discuss/503279/Python3-simple-solution-O(n)-time-and-space-complexity
class Solution: def candy(self, ratings: List[int]) -> int: if not ratings: return 0 candies=[1]*len(ratings) for i in range(1,len(ratings)): if ratings[i]>ratings[i-1]: candies[i]=candies[i-1]+1 for i in range(len(candies)-2,-1,-1): if ratings[i]>ratings[i+1]: candies[i]=max(candies[i],candies[i+1]+1) return sum(candies)
candy
Python3 simple solution O(n) time and space complexity
jb07
2
153
candy
135
0.408
Hard
1,712
https://leetcode.com/problems/candy/discuss/2237963/Python3-Easy-Peesy
class Solution: def candy(self, ratings: List[int]) -> int: if ratings == []: return 0 if len(ratings) == 1: return 1 candy = [1]*len(ratings) for i in range (len(ratings)-2,-1,-1): if ratings[i] > ratings[i+1]: candy[i] = candy[i+1]+1 for i in range (1,len(ratings)): if ratings[i] > ratings[i-1] and candy[i] <= candy[i-1]: candy[i] = candy[i-1]+1 return sum(candy) ```
candy
Python3 Easy Peesy
iishipatel
1
38
candy
135
0.408
Hard
1,713
https://leetcode.com/problems/candy/discuss/2237634/EASY-PYTHON-SOLYTION-(GREEDY)-BEATS-93.51-in-RUNTIME-AND-96.8-in-SPACE
class Solution: def candy(self, arr: List[int]) -> int: n=len(arr) candy=[1]*n #Here we are allocating atleast one candy to each student for i in range(1,n): #here we just have to insure that if ith student has greater rating than i-1th student #then give more candies to ith student as compared to i-1th student if arr[i]>arr[i-1]: candy[i]=candy[i-1]+1 sum=candy[n-1] for i in range(n-2,-1,-1): #here we just have to insure that if ith student has greater rating than i+1th student #then give more candies to ith student as compared to i+1th student if arr[i]>arr[i+1] and candy[i]<=candy[i+1]: candy[i]=candy[i+1]+1 #here we also have an option to maintain the sum sum+=candy[i] return sum
candy
EASY PYTHON 💥💥SOLYTION (GREEDY) BEATS 93.51 % in RUNTIME AND 96.8% in SPACE😈😈
ChinnaTheProgrammer
1
43
candy
135
0.408
Hard
1,714
https://leetcode.com/problems/candy/discuss/2235307/Simple-Approach-oror-Clean-Code
class Solution: def candy(self, ratings: List[int]) -> int: n= len(ratings) left = [1]*n right = [1]*n for i in range(1, n): if ratings[i] > ratings[i - 1]: left[i] = left[i - 1] + 1 for j in range(n - 2, -1, -1): if ratings[j] > ratings[j + 1]: right[j] = right[j + 1] + 1 minimumCandies = 0 for i in range(n): minimumCandies += max(left[i], right[i]) return minimumCandies
candy
Simple Approach || Clean Code
Vaibhav7860
1
45
candy
135
0.408
Hard
1,715
https://leetcode.com/problems/candy/discuss/2234639/python3-or-basic-and-simple-approach-or-explained-or-easy-or-O(n)
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candies = [1]*n # giving 1 candie to each child if n==1: return 1 # comparing if rating of 1st child with 2nd # assigning the candie to 1st child if rating is more than 2nd if ratings[0] > ratings[1]: candies[0] = 2 # comparison and candies are assigned with this loop for i in range(1, n-1): if ratings[i] > ratings[i-1]: candies[i] = candies[i-1]+1 if ratings[i] > ratings[i+1]: candies[i] = candies[i+1]+1 # again comparing and assigning the candies with this loop for i in range(n-2, 0, -1): if ratings[i] > ratings[i-1] and candies[i] <= candies[i-1]: candies[i] = candies[i-1]+1 if ratings[i] > ratings[i+1] and candies[i] <= candies[i+1]: candies[i] = candies[i+1]+1 if ratings[0] > ratings[1] and candies[0]<=candies[1]: candies[0] = candies[1]+1 if ratings[n-1] > ratings[n-2]: candies[n-1] = candies[n-2]+1 return sum(candies)
candy
python3 | basic and simple approach | explained | easy | O(n)
H-R-S
1
122
candy
135
0.408
Hard
1,716
https://leetcode.com/problems/candy/discuss/1437979/Python-two-pass-slow-but-intuitive
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candies = [1]*n for i in range(1, n): if ratings[i] > ratings[i-1]: candies[i] = candies[i-1]+1 for i in range(n-2, -1, -1): if ratings[i] > ratings[i+1]: candies[i] = max(candies[i], candies[i+1]+1) return sum(candies)
candy
Python two pass slow but intuitive
Charlesl0129
1
103
candy
135
0.408
Hard
1,717
https://leetcode.com/problems/candy/discuss/1301091/Python-144ms-9848-Two-solutions
class Solution: def candy(self, ratings: List[int]) -> int: lenratings = len(ratings) # call len only once. It is used 3 times ans = [1] * lenratings for i in range(1, lenratings): if ratings[i] > ratings[i-1]: ans[i] = ans[i-1] + 1 for i in range(lenratings-2, -1, -1): a = i+1 # a is used 2 times in if # compare rantings and candys is faster than use "max" to calculate. if ratings[i] > ratings[a] and ans[i] <= ans[a]: ans[i] = ans[a] + 1 return sum(ans)
candy
Python 144ms 98,48%, Two solutions
argoida
1
53
candy
135
0.408
Hard
1,718
https://leetcode.com/problems/candy/discuss/1301091/Python-144ms-9848-Two-solutions
class Solution: def candy(self, ratings: list) -> int: lenratings = len(ratings) # call len only once. It is used 3 times ans = [1] * lenratings b = [] for i in range(1, lenratings): if ratings[i] > ratings[i-1]: ans[i] = ans[i-1] + 1 else: b.append(i-1) b.reverse() for i in b: a = i+1 # a is used 2 times in if # compare rantings and candys is faster than use "max" to calculate. if ratings[i] > ratings[a] and ans[i] <= ans[a]: ans[i] = ans[a] + 1 return sum(ans)
candy
Python 144ms 98,48%, Two solutions
argoida
1
53
candy
135
0.408
Hard
1,719
https://leetcode.com/problems/candy/discuss/1300283/Python-O(n)-runtime-faster-than-84.94-and-space-less-than-91.16
class Solution: def candy(self, ratings: List[int]) -> int: n=len(ratings) dp=[1]*n #left to right for i in range(1,n): if ratings[i]>ratings[i-1]: dp[i]=dp[i-1]+1 #right to left for i in range(n-2,-1,-1): if ratings[i]>ratings[i+1]: dp[i]=max(dp[i],dp[i+1]+1) return sum(dp)
candy
Python O(n), runtime faster than 84.94% and space less than 91.16%
code-fanatic
1
102
candy
135
0.408
Hard
1,720
https://leetcode.com/problems/candy/discuss/713867/Python3-O(N)-time-O(1)-space
class Solution: def candy(self, ratings: List[int]) -> int: ans = down = up = 0 for i in range(len(ratings)): if not i or ratings[i-1] < ratings[i]: if down: down, up = 0, 1 up += 1 ans += up elif ratings[i-1] == ratings[i]: down, up = 0, 1 ans += 1 else: down += 1 ans += down if down < up else down+1 return ans
candy
[Python3] O(N) time O(1) space
ye15
1
141
candy
135
0.408
Hard
1,721
https://leetcode.com/problems/candy/discuss/2829608/Python-oror-Intuitive-Solution-oror-Find-%22Bottoms%22-and-move-from-there
class Solution: def candy(self, ratings: List[int]) -> int: if len(ratings) == 1: return 1 association = [None] * len(ratings) current = 1 def climb(position, left): # if left == True climb to the left, otherwise to the right # position is the bottom element prev = ratings[position] factor = -1 if left else 1 shift = 1 while 0 <= position + factor * shift < len(ratings) and prev < ratings[position + factor * shift]: if association[position + factor * shift] == None or association[position + factor * shift] < shift + 1: association[position + factor * shift] = shift + 1 prev = ratings[position + factor * shift] shift += 1 for i in range(len(ratings)): if i == 0: if ratings[i] <= ratings[i+1]: association[i] = 1 current = 1 climb(i, False) continue if i == len(ratings) - 1: if ratings[i] <= ratings[i-1]: association[i] = 1 current = 1 climb(i, True) continue if ratings[i] <= ratings[i+1] and ratings[i] <= ratings[i-1]: association[i] = 1 current = 1 climb(i, True) climb(i, False) return sum(association)
candy
Python || Intuitive Solution || Find "Bottoms" and move from there
nicobarteam
0
5
candy
135
0.408
Hard
1,722
https://leetcode.com/problems/candy/discuss/2804211/Sliding-Window-with-Forward-and-Back-Loop
class Solution: def candy(self, ratings: List[int]) -> int: if len(ratings) == 1 : return 1 else : # sliding window problem # iterate over the list but start with an array of matching size # iterate once forward and once backward # each child gets one # check as you go along to get more # at the end, sum n = len(ratings) child_array = [1]*n # forward loop for index in range(n) : # edge case checks if index == 0 : if ratings[index] > ratings[index+1] : child_array[index] = child_array[index+1] + 1 elif index == n - 1 : if ratings[index] > ratings[index-1] : child_array[index] = child_array[index-1] + 1 else : # 0 < index < n - 1 # figure out if you need to modify if ratings[index] > ratings[index+1] or ratings[index] > ratings[index-1] : # figure out which to modify child_on_left = child_array[index - 1] child_on_right = child_array[index + 1] # modify as appropriate if ratings[index] > ratings[index+1] and ratings[index] > ratings[index-1] : child_array[index] = max(child_on_left, child_on_right) + 1 elif ratings[index] > ratings[index+1] and ratings[index] <= ratings[index-1] : child_array[index] = child_on_right + 1 elif ratings[index] > ratings[index-1] and ratings[index] <= ratings[index+1] : child_array[index] = child_on_left + 1 # 2nd time go backwards for index in range(n-1, -1, -1) : if index == 0 : if ratings[index] > ratings[index+1] : child_array[index] = child_array[index+1] + 1 elif index == n-1 : if ratings[index] > ratings[index-1] : child_array[index] = child_array[index-1] + 1 else : if ratings[index] > ratings[index+1] or ratings[index] > ratings[index-1] : child_on_left = child_array[index-1] child_on_right = child_array[index+1] if ratings[index] > ratings[index+1] and ratings[index] > ratings[index-1] : child_array[index] = max(child_on_left, child_on_right) + 1 elif ratings[index] > ratings[index+1] and ratings[index] <= ratings[index-1] : child_array[index] = child_on_right + 1 elif ratings[index] > ratings[index-1] and ratings[index] <= ratings[index+1] : child_array[index] = child_on_left + 1 # print for sanity check # print(child_array) # return summation of array return sum(child_array)
candy
Sliding Window with Forward and Back Loop
laichbr
0
2
candy
135
0.408
Hard
1,723
https://leetcode.com/problems/candy/discuss/2801684/Simple-Python-Solution-(Easy-Intuitive-Efficient)
class Solution: def candy(self, ratings: List[int]) -> int: ''' intialize a list recording the amount of candy of each children ''' candy = [1] * len(ratings) ''' from left to right, if rating of current children is greater than the left one #let current children have one more than children on the left ''' for i in range(1,len(ratings)): if ratings[i] > ratings[i-1]: candy[i] = candy[i-1] + 1 ''' from right to left, do the same thing except for that if current children already has one more candy than the children to the right, let the children keep it ''' for i in range(len(ratings)-2,-1,-1): if ratings[i] > ratings[i+1]: candy[i] = max(candy[i],candy[i+1]+1) return sum(candy) ''' Space: O(n) Time: O(n) '''
candy
Simple Python Solution (Easy, Intuitive, Efficient)
bobbyxq
0
3
candy
135
0.408
Hard
1,724
https://leetcode.com/problems/candy/discuss/2798340/Python3-%3A-Two-pass-solution-with-explanation.
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candies = [1] * n ## Left to right pass, assign candies to candies where rating increases for i in range(1,n) : if ratings[i] > ratings[i-1] : candies[i] = candies[i-1] + 1 for i in reversed(range(n-1)) : if ratings[i] > ratings[i+1] : candies[i] = max(candies[i],candies[i+1] + 1) return sum(candies)
candy
Python3 : Two pass solution with explanation.
vishaltime
0
2
candy
135
0.408
Hard
1,725
https://leetcode.com/problems/candy/discuss/2734275/Python-Solution
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candies = [1]*n for i in range(1,n): if ratings[i]>ratings[i-1]: candies[i] = candies[i-1]+1 for i in reversed(range(n-1)): if ratings[i]>ratings[i+1]: candies[i] = max(candies[i],candies[i+1]+1) return sum(candies)
candy
Python Solution
Akshit-Gupta
0
6
candy
135
0.408
Hard
1,726
https://leetcode.com/problems/candy/discuss/2650221/python-6-liner-DP-solution-oror-80-faster
class Solution: def candy(self, A: List[int]) -> int: candy = [1] * (len(A)) for i in range(1,len(A)): if A[i-1]<A[i]: candy[i] =candy[i-1]+1 for i in range(len(A)-1,0,-1): if A[i] < A[i-1]: candy[i-1] = max(candy[i] + 1, candy[i-1]) return sum(candy)
candy
python 6 liner DP solution || 80% faster
Akash_chavan
0
9
candy
135
0.408
Hard
1,727
https://leetcode.com/problems/candy/discuss/2644716/Simple-python-code-with-explantion
class Solution: def candy(self, ratings: List[int]) -> int: #create a list candy of size len(rating) with all 1 #because we have give minimum 1 candy to every child candy = [1] * (len(ratings)) #iterate over the ratings from index 1 to end for i in range(1,len(ratings)): #if the rating of current child is greater than the previous child if ratings[i] > ratings[i-1]: #then change the values of candy to current child as the #maximum of (prev child candies + 1 , his candies) candy[i] = max(candy[i-1] + 1, candy[i]) #iterate over the ratings from last but one index to 0th index in reverse order for i in range(len(ratings)-2,-1,-1): #if the raring of current child is greater then the next child if ratings[i] > ratings[i+1]: #then change the values of candy to current child as the #maximum of (next child candies + 1, his candies) candy[i] = max(candy[i+1] + 1, candy[i]) #return the sum of candies #which is the minimum no. of candies you need to have to distribute the candies to the children return sum(candy)
candy
Simple python code with explantion
thomanani
0
50
candy
135
0.408
Hard
1,728
https://leetcode.com/problems/candy/discuss/2238381/Python-oror-O(n)-Greedy-Solution-Faster-than-98
class Solution: def candy(self, ratings: [int]) -> int: if len(ratings) == 0: return 0 # initial condition: 1 children trend = "down" temp = 1 total_candy_num = 1 peak_candy_num = -1 # use greedy for i in range(1, len(ratings)): if trend == "down": if ratings[i] < ratings[i - 1]: temp += 1 if temp == peak_candy_num: temp += 1 elif ratings[i] == ratings[i - 1]: temp = 1 peak_candy_num = -1 else: trend = "up" temp = 2 peak_candy_num = -1 else: if ratings[i] > ratings[i - 1]: temp += 1 elif ratings[i] == ratings[i - 1]: trend = "down" temp = 1 peak_candy_num = -1 else: trend = "down" peak_candy_num = temp temp = 1 total_candy_num += temp return total_candy_num
candy
Python || O(n) Greedy Solution Faster than 98%
XixiangLiu
0
15
candy
135
0.408
Hard
1,729
https://leetcode.com/problems/candy/discuss/2237600/python-solution-oror-come-up-by-myself
class Solution: def candy(self, ratings: List[int]) -> int: ratings = [ratings[0]+1] + ratings + [ratings[-1]+1] candy = [0] * len(ratings) # middle for i in range(1, len(ratings) - 1): # if we found a local min if candy[i] == 0 and ratings[i] <= ratings[i-1] and ratings[i] <= ratings[i+1]: # print(f'local min at {i}') candy[i] = 1 if ratings[i] < ratings[i-1]: candy[i-1] = max(candy[i-1], 2) else: candy[i-1] = max(candy[i-1], 1) if ratings[i] < ratings[i+1]: candy[i+1] = max(candy[i+1], 2) else: candy[i+1] = max(candy[i+1], 1) # to the left for j in range(i-1, 0, -1): if ratings[j] < ratings[j-1]: if candy[j-1] != 0: candy[j-1] = max(candy[j-1], candy[j] + 1) else: candy[j-1] = candy[j] + 1 else: break # to the right for j in range(i+1, len(ratings) - 1): if ratings[j] < ratings[j+1]: if candy[j+1] != 0: candy[j+1] = max(candy[j+1], candy[j] + 1) else: candy[j+1] = candy[j] + 1 else: break # print(candy) # print(candy) return sum(candy[1:-1])
candy
python solution || come up by myself
lamricky11
0
26
candy
135
0.408
Hard
1,730
https://leetcode.com/problems/candy/discuss/2237600/python-solution-oror-come-up-by-myself
class Solution: def candy(self, ratings: List[int]) -> int: ratings = [ratings[0]+1] + ratings + [ratings[-1]+1] candy = [0] * len(ratings) # middle for i in range(1, len(ratings) - 1): # if we found a local min if candy[i] == 0 and ratings[i] <= ratings[i-1] and ratings[i] <= ratings[i+1]: # print(f'local min at {i}') candy[i] = 1 if ratings[i] < ratings[i-1]: candy[i-1] = max(candy[i-1], 2) else: candy[i-1] = max(candy[i-1], 1) if ratings[i] < ratings[i+1]: candy[i+1] = max(candy[i+1], 2) else: candy[i+1] = max(candy[i+1], 1) # to the left j = i-1 while 0 < j and ratings[j] < ratings[j-1]: candy[j-1] = max(candy[j-1], candy[j] + 1) j -= 1 # to the right j = i+1 while j < len(ratings) - 1 and ratings[j] < ratings[j+1]: candy[j+1] = max(candy[j+1], candy[j] + 1) j += 1 # print(candy) # print(candy) return sum(candy[1:-1])
candy
python solution || come up by myself
lamricky11
0
26
candy
135
0.408
Hard
1,731
https://leetcode.com/problems/candy/discuss/2237379/Python3-oror-easy-to-understanding
class Solution: def candy(self, ratings: List[int]) -> int: left = [1] for i in range(1, len(ratings)): if ratings[i] > ratings[i-1]: left.append(left[-1] + 1) else: left.append(1) right = [1] * len(ratings) for i in range(len(ratings)-2, -1, -1): if ratings[i] > ratings[i+1]: right[i] = right[i+1] + 1 return sum([max(l, r) for l, r in zip(left, right)])
candy
Python3 || easy to understanding
sagarhasan273
0
8
candy
135
0.408
Hard
1,732
https://leetcode.com/problems/candy/discuss/2237230/Python-Simple-Solution
class Solution: def candy(self, ratings: List[int]) -> int: if len(ratings)==1: return 1 else: candies=[1 for i in range(len(ratings))] for i in range(1,len(ratings)): if ratings[i]>ratings[i-1]: candies[i]=candies[i-1]+1 for i in range(len(ratings)-2,-1,-1): if ratings[i]>ratings[i+1]: candies[i]=max(candies[i],candies[i+1]+1) if ratings[0]>ratings[1]: candies[0]=max(candies[0],candies[1]+1) return sum(candies)
candy
Python Simple Solution
creativerahuly
0
9
candy
135
0.408
Hard
1,733
https://leetcode.com/problems/candy/discuss/2236141/Python3-Priority-Queue-Work-From-Lowest-Rated-Child-Explained
class Solution: def candy(self, ratings: List[int]) -> int: # Analogy: # \ / \ # \ / \ / \ / # v v v v # # Distribute candies such that it looks # like a bunch of troughs of varying heights aligned # side by side. Where the base of the troughs (v) are # the lowest rated children, and the heights of its # sides (\ or /) are the children with incrementally better # ratings # Problem is essentially looking for the next lowest ratings # and distributing candies in larger increments to the left # side and the right side IF their current rating is # greater than their previous rating # Use a priority queue to identify the lowest ratings heapq = [(ratings[i], i) for i in range(len(ratings))] heapify(heapq) # Array of candies parallel to the array of ratings of the child # where candies[i] represents the amount of candies the child at # ratings[i] will have candies = [1 for _ in range(len(ratings))] while(heapq): base = heappop(heapq) # Get next lowest rating # If the candy count has been modified, then it indicates # that this child isn't part of the lowest rating. We # only work with the lowest rating child (candy == 1), so skip if candies[base[1]] != 1: continue # Distribute candies to the left, when applicable curr = base[0] for i in range(base[1] - 1, -1, -1): # Give more candies when the current child has a greater # rating than the previous child AND when the current child # has fewer than or equal to the amount of candies than the # previous child # # The second condition is important since it will solve the # problem where the current child has already been # distributed candies, but may become overwritten in this new # distribution: # # Distribute from lowest starting from left to right ========> # index: 0 1 2 3 4 0 1 2 3 4 # ratings: [1, 4, 3, 2, 1] OR [1, 2, 3, 4, 1] # candies: [1, 2, 3, 2, 1] [1, 2, 3, 4, 1] # ^ ^ # Solution: Let it overwrite WITH the larger amount of candies if ratings[i] > curr and candies[i] <= candies[i + 1]: curr = ratings[i] candies[i] = candies[i + 1] + 1 else: break # Distribute candies to the right, when applicable curr = base[0] for i in range(base[1] + 1, len(ratings)): # See line 41, same principle if ratings[i] > curr and candies[i] <= candies[i - 1]: curr = ratings[i] candies[i] = candies[i - 1] + 1 else: break return sum(candies)
candy
[Python3] Priority Queue, Work From Lowest Rated Child Explained
betaRobin
0
5
candy
135
0.408
Hard
1,734
https://leetcode.com/problems/candy/discuss/2235570/O(n)-Python-solution-with-O(1)-space-and-one-pass
class Solution: def candy(self, ratings: List[int]) -> int: candies = 0 i = 0 while i < len(ratings): up, down = 1, 1 if i == len(ratings) - 1 or ratings[i] == ratings[i+1]: candies += 1 i += 1 continue while i < len(ratings) - 1 and ratings[i] < ratings[i+1]: up += 1 i += 1 while i < len(ratings) - 1 and ratings[i] > ratings[i+1]: down += 1 i += 1 # Given the up and down slopes, the peak value will come from the longer slope candies += max(up,down) * (max(up,down) + 1) // 2 candies += (min(up, down) * (min(up,down) - 1) // 2) # Subtract one to allow for proper calculation of the next slope candies -= 1 return candies
candy
O(n) Python solution with O(1) space and one pass
JoshuaY359
0
23
candy
135
0.408
Hard
1,735
https://leetcode.com/problems/candy/discuss/2235564/Simple-Python-Solution-oror-Python3-oror-Two-Arrays
class Solution: def candy(self, ratings: List[int]) -> int: leftToright = [1] rightToleft = [1] candyGiven = 1 for i in range(len(ratings)-1): if(ratings[i] < ratings[i+1]): candyGiven += 1 elif(ratings[i] >= ratings[i+1]): candyGiven = 1 leftToright.append(candyGiven) # print(leftToright) candyGiven = 1 for i in range(len(ratings) - 1, 0, -1): if(ratings[i-1] > ratings[i]): candyGiven += 1 else: candyGiven = 1 rightToleft.append(candyGiven) rightToleft.reverse() # print(rightToleft) res = [] for i in range(len(rightToleft)): temp = max(rightToleft[i], leftToright[i]) res.append(temp) return sum(res)
candy
Simple Python Solution || Python3 || Two Arrays
irapandey
0
7
candy
135
0.408
Hard
1,736
https://leetcode.com/problems/candy/discuss/2235199/GoGolangPython-O(N)-Solution
class Solution: def candy(self, ratings: List[int]) -> int: candies = [1 for _ in ratings] for i in range(1,len(ratings)): curr_candies = candies[i] prev_candies = candies[i-1] curr_rating = ratings[i] prev_rating = ratings[i-1] if curr_rating > prev_rating and curr_candies <= prev_candies: candies[i] = prev_candies+1 for i in range(len(ratings)-2,-1,-1): curr_candies = candies[i] prev_candies = candies[i+1] curr_rating = ratings[i] prev_rating = ratings[i+1] if curr_rating > prev_rating and curr_candies <= prev_candies: candies[i] = prev_candies+1 return sum(candies)
candy
Go/Golang/Python O(N) Solution
vtalantsev
0
14
candy
135
0.408
Hard
1,737
https://leetcode.com/problems/candy/discuss/2234984/Python-or-Greedy-or-Time%3A-O(n)-Space%3A-O(n)
class Solution: def candy(self, rat: List[int]) -> int: l1 = [] l2 = [] n = len(rat) for i in range(n): if i==0: l1.append(1) l2.append(1) else: if rat[i]>rat[i-1]: l1.append(l1[-1]+1) else: l1.append(1) if rat[n-1-i+1]<rat[n-1-i]: l2.append(l2[-1]+1) else: l2.append(1) s = 0 for i in range(n): s += max(l1[i],l2[n-1-i]) return s
candy
Python | Greedy | Time: O(n) Space: O(n)
Shivamk09
0
10
candy
135
0.408
Hard
1,738
https://leetcode.com/problems/candy/discuss/2234430/Simple-O(n)-solution
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) m = max(ratings) candies = [1 for i in ratings] partition = [[] for i in range(m+1)] for i in range(n): partition[ratings[i]].append(i) for y in partition: for i in y: if i - 1 >= 0 and ratings[i-1] < ratings[i]: candies[i] = candies[i-1] + 1 if i + 1 < n and ratings[i+1] < ratings[i]: candies[i] = max(candies[i], candies[i+1] + 1) return sum(candies)
candy
Simple O(n) solution
soundsflyout
0
17
candy
135
0.408
Hard
1,739
https://leetcode.com/problems/candy/discuss/2152274/Python-easy-to-read-and-understand-or-greedy
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) left = [1 for _ in range(n)] right = [1 for _ in range(n)] for i in range(1, n): if ratings[i] > ratings[i-1]: left[i] = left[i-1]+1 for i in range(n-2, -1, -1): if ratings[i] > ratings[i+1]: right[i] = right[i+1]+1 ans = 0 for i in range(n): ans += max(left[i], right[i]) return ans
candy
Python easy to read and understand | greedy
sanial2001
0
94
candy
135
0.408
Hard
1,740
https://leetcode.com/problems/candy/discuss/2035790/Python-or-Very-easy-explanation-with-comments
class Solution: def candy(self, ratings: List[int]) -> int: ''' One of the simplest idea here is distribut candy one directionally from both the direction and final candy for the ith person would be the max of it. how? The approach is pretty intutive if you just consider ratings of size 3, in this case when we distribute candies form either direction we observe that it is the max of these two (leftdirection_candy,rightdirection_candy) Down below code is pretty self explanatory ''' # ///////// distributing candies from left direction irrespective of right-side condition c_left = [1] * len(ratings) for i in range(1,len(ratings)): if ratings[i] > ratings[i-1]: c_left[i] = c_left[i-1] + 1 # ///////// distributing candies from right direction irrespective of left-side condition c_right = [1] * len(ratings) for i in range(len(ratings)-2,-1,-1): if ratings[i] > ratings[i+1]: c_right[i] = c_right[i+1] + 1 # taking the max candies out of the two res = [1] * len(ratings) for i in range(len(ratings)): res[i] = max(c_left[i],c_right[i]) return sum(res)
candy
Python | Very easy explanation with comments
__Asrar
0
62
candy
135
0.408
Hard
1,741
https://leetcode.com/problems/candy/discuss/2031014/Python3-oror-Greedy-Solutionoror-O(n)-time-O(n)-space
class Solution: def candy(self, ratings: List[int]) -> int: n = len(ratings) candy_left, candy_right = [1] * n, [1] * n #assign candies based on left neighbors for idx in range(1,n): if ratings[idx] > ratings[idx-1]: candy_left[idx] = candy_left[idx-1] + 1 else: candy_left[idx] = 1 #assign candies based on right neighbors for idx in range(n-2,-1,-1): if ratings[idx] > ratings[idx+1]: candy_right[idx] = candy_right[idx+1] + 1 else: candy_right[idx] = 1 total_candies = 0 #find max of both the arrays and assign those many candies to the concerned candidate and finda total for val1,val2 in zip(candy_left,candy_right): total_candies += max(val1,val2) return total_candies #TC: O(n) || SC:O(n)
candy
Python3 || Greedy Solution|| O(n) time, O(n) space
s_m_d_29
0
56
candy
135
0.408
Hard
1,742
https://leetcode.com/problems/candy/discuss/1617394/O(n)-idea-based-on-bucket-sort-and-iterative-BFS
class Solution: def candy(self, ratings: List[int]) -> int: sorted_list = [[] for _ in range(max(ratings)+1)] candy_arr = [0]*len(ratings) for i, rate in enumerate(ratings): sorted_list[rate].append(i) flatten_list = [] for item in sorted_list: flatten_list += item print(flatten_list) for val in flatten_list: max_val = 0 if val>=1 and ratings[val-1]!=ratings[val]: max_val = max(max_val, candy_arr[val-1]) if val<len(ratings)-1 and ratings[val+1]!=ratings[val]: max_val = max(max_val, candy_arr[val+1]) candy_arr[val] = max_val + 1 print(candy_arr) return sum(candy_arr)
candy
O(n) idea based on bucket sort and iterative BFS
throwawayleetcoder19843
0
65
candy
135
0.408
Hard
1,743
https://leetcode.com/problems/candy/discuss/1459567/Python3-O(n)-time-O(n)-space-solution-with-results
class Solution: def candy(self, ratings: List[int]) -> int: arr = [1] * len(ratings) for idx in range(len(ratings) - 1): if ratings[idx] < ratings[idx + 1]: arr[idx + 1] = arr[idx] + 1 for idx in range(len(ratings) - 1, 0, -1): if ratings[idx] < ratings[idx - 1]: arr[idx - 1] = max(arr[idx - 1], arr[idx] + 1) return sum(arr)
candy
[Python3] O(n) time, O(n) space solution with results
maosipov11
0
103
candy
135
0.408
Hard
1,744
https://leetcode.com/problems/candy/discuss/1300342/Python-Solution-O(N)-Time-and-O(N)-space
class Solution: def candy(self, ratings: List[int]) -> int: candies = [1]*len(ratings) if len(ratings) == 1: return 1 if ratings[0]>ratings[1] and candies[0] == candies[1]: candies[0]+=1 for i in range(1,len(ratings)): if ratings[i]>ratings[i-1] and candies[i] <=candies[i-1]: candies[i]=candies[i-1]+1 for i in range(len(ratings)-2,-1,-1): if ratings[i]>ratings[i+1] and candies[i] <=candies[i+1]: candies[i]=candies[i+1]+1 return sum(candies)
candy
Python Solution O(N) Time and O(N) space
Ayu-99
0
38
candy
135
0.408
Hard
1,745
https://leetcode.com/problems/candy/discuss/1169253/Python3-Simple-Solution-with-comments
class Solution: def candy(self, ratings: List[int]) -> int: ''' 1. According to solution 2, use two arrays initialized by n 1's where n is length of ratings array, - one to check whether ratings[i]<ratings[i+1] starting from the leftmost position, if so then in the array set the value of index (i+1) = 1 + the value of index i - other to check whether ratings[i+1]<ratings[i] starting from the rightmost position, if so then in the array set the value of index i = 1 + the value of index (i+1) 2. If those two arrays are LeftToRight and RightToLeft respectively, then the result will be sum of all maximum(LeftToRight[i], RightToLeft[i]) for 0<=i<=n-1. ''' res_1 = [1]*len(ratings) #array for LeftToRight checking res_2 = [1]*len(ratings) #array for RightToLeft checking res=0 #initial value of minimum no. of candies #we can check whether ratings[0]<ratings[1] and ratings[n-1]<ratings[n-2] in the same iteration #in the following way we can change the values of index i of both LeftToRight array and RightToLeft array in single iteration for i in range(0,len(ratings)-1): if ratings[i+1]>ratings[i] and res_1[i+1]<=res_1[i]: res_1[i+1]=res_1[i]+1 if ratings[len(ratings)-1-i]<ratings[len(ratings)-1-i-1] and res_2[len(ratings)-1-i]>=res_2[len(ratings)-1-i]: res_2[len(ratings)-1-i-1]=res_2[len(ratings)-1-i]+1 for i in range(0,len(ratings)): res+=max(res_1[i], res_2[i]) #getting the maximum of LeftToRight[i] and RightToLeft[i] and adding it to the minimum value return res
candy
Python3 Simple Solution with comments
bPapan
0
91
candy
135
0.408
Hard
1,746
https://leetcode.com/problems/single-number/discuss/2438883/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3)
class Solution(object): def singleNumber(self, nums): # Initialize the unique number... uniqNum = 0; # TRaverse all elements through the loop... for idx in nums: # Concept of XOR... uniqNum ^= idx; return uniqNum; # Return the unique number...
single-number
Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3)
PratikSen07
24
2,100
single number
136
0.701
Easy
1,747
https://leetcode.com/problems/single-number/discuss/2438883/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3)
class Solution: def singleNumber(self, nums: List[int]) -> int: # Initialize the unique number... uniqNum = 0; # TRaverse all elements through the loop... for idx in nums: # Concept of XOR... uniqNum ^= idx; return uniqNum; # Return the unique number...
single-number
Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3)
PratikSen07
24
2,100
single number
136
0.701
Easy
1,748
https://leetcode.com/problems/single-number/discuss/1771869/Python-Simple-Python-Solution-With-Two-Approach
class Solution: def singleNumber(self, nums: List[int]) -> int: result = 0 for i in nums: result = result ^ i return result
single-number
[ Python ] ✔✔ Simple Python Solution With Two Approach 🔥✌
ASHOK_KUMAR_MEGHVANSHI
21
2,100
single number
136
0.701
Easy
1,749
https://leetcode.com/problems/single-number/discuss/1771869/Python-Simple-Python-Solution-With-Two-Approach
class Solution: def singleNumber(self, nums: List[int]) -> int: frequency={} for i in nums: if i not in frequency: frequency[i]=1 else: frequency[i]=frequency[i]+1 for i in frequency: if frequency[i]==1: return i
single-number
[ Python ] ✔✔ Simple Python Solution With Two Approach 🔥✌
ASHOK_KUMAR_MEGHVANSHI
21
2,100
single number
136
0.701
Easy
1,750
https://leetcode.com/problems/single-number/discuss/2641351/Python-3-Easy-solution-in-ONE-line-without-using-XOR!
class Solution: def singleNumber(self, nums: List[int]) -> int: return sum(list(set(nums)) * 2) - sum(nums)
single-number
Python 3 - Easy solution in ONE line without using XOR!
doridoriae86
15
1,200
single number
136
0.701
Easy
1,751
https://leetcode.com/problems/single-number/discuss/1075088/Simplest-Solution-for-beginners
class Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: if(nums.count(i) == 1): return(i)
single-number
Simplest Solution for beginners
parasgarg395
12
1,200
single number
136
0.701
Easy
1,752
https://leetcode.com/problems/single-number/discuss/1541621/Updated%3A-Python-XOR-explained-%2B-resources
class Solution: def singleNumber(self, nums: List[int]) -> int: result = 0 for num in nums: result ^= num return result
single-number
Updated: Python XOR explained + resources
SleeplessChallenger
11
333
single number
136
0.701
Easy
1,753
https://leetcode.com/problems/single-number/discuss/955161/Python-or-1-liner-maths-logic-without-using-libraries-beats-97
class Solution(object): def singleNumber(self, nums): return ((2*(sum(set(nums))))-(sum(nums)))
single-number
Python | 1 liner maths logic without using libraries beats 97%
rachitsxn292
6
540
single number
136
0.701
Easy
1,754
https://leetcode.com/problems/single-number/discuss/2547758/EASY-PYTHON3-SOLUTION
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = 0 for num in nums: xor ^= num return xor
single-number
✅✔ EASY PYTHON3 SOLUTION ✅✔
rajukommula
4
337
single number
136
0.701
Easy
1,755
https://leetcode.com/problems/single-number/discuss/1772420/Python-3-(100ms)-or-BIT-Manipulation-Linear-Approach-or-Easy-to-Understand-XOR
class Solution: def singleNumber(self, nums: List[int]) -> int: r = 0 for i in nums: r ^= i return r
single-number
Python 3 (100ms) | BIT Manipulation Linear Approach | Easy to Understand XOR
MrShobhit
4
339
single number
136
0.701
Easy
1,756
https://leetcode.com/problems/single-number/discuss/1688254/Python3-simplest-XOR-fastest-solution.
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ n = nums[0] for i in range(1, len(nums)): n = n^nums[i] return n `If this solution is helpful to you, pls upvote this. `
single-number
Python3 simplest XOR fastest solution.
sourav-saha
4
156
single number
136
0.701
Easy
1,757
https://leetcode.com/problems/single-number/discuss/2684839/Python-solution-using-Xor-bitwise-operation
class Solution: def singleNumber(self, nums: List[int]) -> int: number = nums[0] for i in range(1, len(nums)): number ^= nums[i] return number
single-number
Python solution using Xor bitwise operation
SmouSCode
3
270
single number
136
0.701
Easy
1,758
https://leetcode.com/problems/single-number/discuss/2094555/Python3-O(n)-oror-O(1)-runtime%3A-129ms-97.29
class Solution: def singleNumber(self, nums: List[int]) -> int: return self.singleNumberOptimal(nums) # O(n) || O(1) # runtime: 129ms 97.29% def singleNumberOptimal(self, array): if not array: return None res = 0 for num in array: res ^= num return res # O(n^2) || O(1) def singleNumberBruteForceOne(self, array): if not array: return array for i in range(len(array)): change = 0 for j in range(len(array)): if i == j: continue if array[i] == array[j]: change = 1 break if change == 0: return array[i] # O(n) || O(n) def singleNumberBruteForceTwo(self, array): if not array: return array hashMap = dict() for i in array: hashMap[i] = 1 + hashMap.get(i, 0) for key in hashMap: if hashMap[key] == 1:return key return -1
single-number
Python3 O(n) || O(1) runtime: 129ms 97.29%
arshergon
3
265
single number
136
0.701
Easy
1,759
https://leetcode.com/problems/single-number/discuss/1826053/Python-3-Simple-XOR-Python-Solution-or-Beats-99.73
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = nums[0] for i in range(1, len(nums)): xor = xor^nums[i] return xor
single-number
[Python 3] Simple XOR Python Solution | Beats 99.73%
hari19041
3
170
single number
136
0.701
Easy
1,760
https://leetcode.com/problems/single-number/discuss/2580369/SIMPLE-PYTHON3-SOLUTION
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = 0 for num in nums: xor ^= num return xor
single-number
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔
rajukommula
2
287
single number
136
0.701
Easy
1,761
https://leetcode.com/problems/single-number/discuss/2570869/SIMPLE-PYTHON3-SOLUTION-FASTEr-LINEAR-TIME
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = 0 for num in nums: xor ^= num return xor
single-number
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ FASTEr LINEAR TIME
rajukommula
2
163
single number
136
0.701
Easy
1,762
https://leetcode.com/problems/single-number/discuss/2319076/Python-2-Easy-Solutions
class Solution: def singleNumber(self, nums: List[int]) -> int: sol = 0 for b in nums: sol ^= b return sol
single-number
✅ Python 2 Easy Solutions
Skiper228
2
166
single number
136
0.701
Easy
1,763
https://leetcode.com/problems/single-number/discuss/2319076/Python-2-Easy-Solutions
class Solution: def singleNumber(self, nums: List[int]) -> int: dic = {} for j in nums: if j not in dic: dic[j] = 1 else: dic[j] +=1 for j in dic: if dic[j] == 1: return j
single-number
✅ Python 2 Easy Solutions
Skiper228
2
166
single number
136
0.701
Easy
1,764
https://leetcode.com/problems/single-number/discuss/1828732/Python-Clear-and-Simple!-Multiple-Solutions!-Time-and-Space-Complexity
class Solution: def singleNumber(self, nums): s = set() for num in nums: if num not in s: s.add(num) else: s.remove(num) return s.pop()
single-number
Python - Clear and Simple! Multiple Solutions! Time and Space Complexity
domthedeveloper
2
155
single number
136
0.701
Easy
1,765
https://leetcode.com/problems/single-number/discuss/1828732/Python-Clear-and-Simple!-Multiple-Solutions!-Time-and-Space-Complexity
class Solution: def singleNumber(self, nums): x = 0 for num in nums: x ^= num return x
single-number
Python - Clear and Simple! Multiple Solutions! Time and Space Complexity
domthedeveloper
2
155
single number
136
0.701
Easy
1,766
https://leetcode.com/problems/single-number/discuss/1828732/Python-Clear-and-Simple!-Multiple-Solutions!-Time-and-Space-Complexity
class Solution: def singleNumber(self, nums): return reduce(operator.xor, nums)
single-number
Python - Clear and Simple! Multiple Solutions! Time and Space Complexity
domthedeveloper
2
155
single number
136
0.701
Easy
1,767
https://leetcode.com/problems/single-number/discuss/1768909/Python-XOR-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: xor =0 for i in nums: xor^=i return xor
single-number
Python XOR solution
Wicked_Sunny
2
109
single number
136
0.701
Easy
1,768
https://leetcode.com/problems/single-number/discuss/1653680/Python3-2-solutions-or-1-Liner-Bit-Manipulation-or-O(1)-Space-or-O(n)-Time-or-XOR
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = 0 for n in nums: xor ^= n return xor
single-number
[Python3] 2 solutions | 1-Liner Bit Manipulation | O(1) Space | O(n) Time | XOR
PatrickOweijane
2
397
single number
136
0.701
Easy
1,769
https://leetcode.com/problems/single-number/discuss/1653680/Python3-2-solutions-or-1-Liner-Bit-Manipulation-or-O(1)-Space-or-O(n)-Time-or-XOR
class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(lambda x, y: x ^ y, nums)
single-number
[Python3] 2 solutions | 1-Liner Bit Manipulation | O(1) Space | O(n) Time | XOR
PatrickOweijane
2
397
single number
136
0.701
Easy
1,770
https://leetcode.com/problems/single-number/discuss/1050989/Python3-simple-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: for i,j in enumerate(nums): if j not in nums[i+1:] and j not in nums[:i]: return j
single-number
Python3 simple solution
EklavyaJoshi
2
170
single number
136
0.701
Easy
1,771
https://leetcode.com/problems/single-number/discuss/366744/Python-linear-solutions-with-O(n)-memory-and-O(1)-memory
class Solution: def singleNumber(self, nums: List[int]) -> int: cache = {} for num in nums: if num in cache: del cache[num] else: cache[num] = 1 return list(cache.keys())[0]
single-number
Python linear solutions with O(n) memory and O(1) memory
amchoukir
2
703
single number
136
0.701
Easy
1,772
https://leetcode.com/problems/single-number/discuss/366744/Python-linear-solutions-with-O(n)-memory-and-O(1)-memory
class Solution: def singleNumber(self, nums: List[int]) -> int: return 2 * sum(set(nums)) - sum(nums)
single-number
Python linear solutions with O(n) memory and O(1) memory
amchoukir
2
703
single number
136
0.701
Easy
1,773
https://leetcode.com/problems/single-number/discuss/366744/Python-linear-solutions-with-O(n)-memory-and-O(1)-memory
class Solution: def singleNumber(self, nums: List[int]) -> int: accumulator = 0 for num in nums: accumulator ^= num return accumulator
single-number
Python linear solutions with O(n) memory and O(1) memory
amchoukir
2
703
single number
136
0.701
Easy
1,774
https://leetcode.com/problems/single-number/discuss/1997029/Python-O(n)-solution-without-using-extra-space
class Solution: def singleNumber(self, nums: List[int]) -> int: ans = None for ele in nums: if ans == None: ans = ele else: ans = ans ^ ele return ans
single-number
Python O(n) solution without using extra space
dbansal18
1
90
single number
136
0.701
Easy
1,775
https://leetcode.com/problems/single-number/discuss/1909477/3-Python-Solutions-O(nlogn)-O(n)-with-Explaination
class Solution: def singleNumber(self, nums: List[int]) -> int: # Sorting method # Time: O(nlogn) Space: O(1) # Here, we'll simply sort the list and then check if the next element == current element # if yes, then we'll continue # else we'll return the element if len(nums) == 1: return nums[0] nums.sort() for i in range(1,len(nums),2): if nums[i] != nums[i-1]: return nums[i-1] return nums[len(nums)-1] # Using Dictionary # Time: O(n) Space:O(n) # Here, we'll simply traverse through the list and # insert the element and it's count as (key,value) pair # then we'll start iterating through the dictionary # and if we find any element having count 1 # we'll return the element res = {} for el in nums: if el in res: res[el] += 1 else: res[el] = 1 for key in res.keys(): if res[key] == 1: return key # XOR method # Time: O(n) Space: O(1) # If you know how XOR operation works then it's pretty straight forward for you. for i in range(1,len(nums)): nums[0] ^= nums[i] return nums[0]
single-number
3 Python Solutions O(nlogn) O(n) with Explaination
introvertednerd
1
87
single number
136
0.701
Easy
1,776
https://leetcode.com/problems/single-number/discuss/1676549/Python-sort-and-find
class Solution: def singleNumber(self, nums: List[int]) -> int: nums.sort() i = 0 while i < len(nums): if i == len(nums)-1: return nums[i] else: if nums[i] not in nums[i+1:]: return nums[i] else: i += 2
single-number
Python - sort and find
flora_1888
1
349
single number
136
0.701
Easy
1,777
https://leetcode.com/problems/single-number/discuss/1624021/Python-Solution-or-Bit-Manipulation-or-O(n)-or-99-Faster-or-One-Liner
class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(lambda x, y: x^y, nums)
single-number
Python Solution | Bit Manipulation | O(n) | 99% Faster | One Liner
avi-arora
1
302
single number
136
0.701
Easy
1,778
https://leetcode.com/problems/single-number/discuss/1624021/Python-Solution-or-Bit-Manipulation-or-O(n)-or-99-Faster-or-One-Liner
class Solution: def singleNumber(self, nums: List[int]) -> int: xor = 0 for n in nums: xor ^= n return xor
single-number
Python Solution | Bit Manipulation | O(n) | 99% Faster | One Liner
avi-arora
1
302
single number
136
0.701
Easy
1,779
https://leetcode.com/problems/single-number/discuss/1380460/Python-or-Single-Line-or-XOR-or-T.C-O(n)-or-S.C-O(1)
class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(lambda x,y:x^y,nums)
single-number
Python | Single Line | XOR | T.C = O(n) | S.C = O(1)
shraddhapp
1
188
single number
136
0.701
Easy
1,780
https://leetcode.com/problems/single-number/discuss/931106/Python-4-different-solutions
class Solution: # O(n) time, O(n) space def singleNumber1(self, nums: List[int]) -> int: s = set() for el in nums: if el in s: s.remove(el) else: s.add(el) return list(s)[0] # O(nlogn) time, O(1) space def singleNumber2(self, nums): if len(nums) == 1: return nums[0] nums.sort() i,j = 0,1 while j < len(nums): if nums[i] != nums[j]: return nums[i] i+=2 j+=2 return nums[-1] # O(n) time, O(1) space def singleNumber(self, nums): s = 0 for el in nums: s ^= el return s # O(n) time, O(1) space but more concise def singleNumber(self, nums): return reduce(lambda x,y: x^y, nums)
single-number
Python, 4 different solutions
modusV
1
269
single number
136
0.701
Easy
1,781
https://leetcode.com/problems/single-number/discuss/840618/Python-3-dictionary
class Solution: def singleNumber(self, nums: List[int]) -> int: hash_table = {} for num in nums: if num not in hash_table: hash_table[num] = 1 else: hash_table[num] += 1 for num in hash_table: if hash_table[num] == 1: return num
single-number
Python 3 dictionary
meilinz
1
579
single number
136
0.701
Easy
1,782
https://leetcode.com/problems/single-number/discuss/809772/Python3%3A-Faster-than-99.82Very-Easy-Logic
class Solution: def singleNumber(self, nums: List[int]) -> int: ans=0 for i in nums: ans=ans^i return ans
single-number
Python3: Faster than 99.82%,,Very Easy Logic
171220050
1
169
single number
136
0.701
Easy
1,783
https://leetcode.com/problems/single-number/discuss/762103/Python-3%3A-Using-Counter
class Solution: def singleNumber(self, nums: List[int]) -> int: for k,v in Counter(nums).items(): if v == 1: return k
single-number
Python 3: Using Counter
shraddha-an
1
91
single number
136
0.701
Easy
1,784
https://leetcode.com/problems/single-number/discuss/337026/Solution-in-Python-3-(~beats-99)
class Solution: def singleNumber(self, nums: List[int]) -> int: L, d = len(nums), {} for n in nums: if n in d: del d[n] else: d[n] = 1 return list(d)[0] - Python 3 - Junaid Mansuri
single-number
Solution in Python 3 (~beats 99%)
junaidmansuri
1
1,400
single number
136
0.701
Easy
1,785
https://leetcode.com/problems/single-number/discuss/2847984/Easy-Python-Solution-for-Single-Number-Problem
class Solution: def singleNumber(self, nums: List[int]) -> int: for num in set(nums): if nums.count(num)==1: return num nums=[2,2,1] sol=Solution() nums=[2,2,1] sol.singleNumber(nums) nums=[4,1,2,1,2] sol.singleNumber(nums)
single-number
Easy Python Solution for Single Number Problem
dassdipanwita
0
1
single number
136
0.701
Easy
1,786
https://leetcode.com/problems/single-number/discuss/2846414/xor-solution-python
class Solution: def singleNumber(self, nums: List[int]) -> int: res = 0 for i in nums: res^=i return res
single-number
xor solution python
Cosmodude
0
1
single number
136
0.701
Easy
1,787
https://leetcode.com/problems/single-number/discuss/2842459/Easy-understand-Time-O(n)-Space-O(1)
class Solution: def singleNumber(self, nums: List[int]) -> int: ans = [] for num in nums: if num in ans: ans.remove(num) else: ans.append(num) return ans[0]
single-number
Easy understand - Time O(n), Space O(1)
JennyLu
0
4
single number
136
0.701
Easy
1,788
https://leetcode.com/problems/single-number/discuss/2841655/count-of-element-in-list-is-1
class Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: a=nums.count(i) if a==1: return i break
single-number
count of element in list is 1
bhalke_216
0
3
single number
136
0.701
Easy
1,789
https://leetcode.com/problems/single-number/discuss/2838230/Python-XOR-solution-explained
class Solution: def singleNumber(self, nums: List[int]) -> int: res = 0 for n in nums: res = res ^ n return res
single-number
Python XOR solution explained
Omkar_Borikar
0
4
single number
136
0.701
Easy
1,790
https://leetcode.com/problems/single-number/discuss/2837787/Python-Easy-5-lines
class Solution: def singleNumber(self, nums: List[int]) -> int: from collections import Counter a = Counter(nums) e = list(a.keys()) f = list(a.values()) return e[f.index(1)]
single-number
Python- Easy 5 lines
spraj_123
0
2
single number
136
0.701
Easy
1,791
https://leetcode.com/problems/single-number/discuss/2836613/Pythonor-%22%22Operator
class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for i in nums: ans = ans^i return ans
single-number
Python| "^"Operator
lucy_sea
0
1
single number
136
0.701
Easy
1,792
https://leetcode.com/problems/single-number/discuss/2831226/4-lines-of-code-Python
class Solution: def singleNumber(self, nums: List[int]) -> int: hashmap=Counter(nums) for i in hashmap: if hashmap[i]==1: return i
single-number
4 lines of code [Python]
zakaria_eljaafari
0
2
single number
136
0.701
Easy
1,793
https://leetcode.com/problems/single-number/discuss/2830757/Using-count
class Solution: def singleNumber(self, nums: List[int]) -> int: for i in nums: if nums.count(i) == 1: return i
single-number
Using count
Es-ppx
0
3
single number
136
0.701
Easy
1,794
https://leetcode.com/problems/single-number/discuss/2829416/simple-solution
class Solution: def singleNumber(self, nums: List[int]) -> int: return [x for x in nums if nums.count(x)==1][0]
single-number
simple solution
JoelTanSG
0
3
single number
136
0.701
Easy
1,795
https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches
class Solution(object): def singleNumber(self, nums): a, b = 0, 0 for x in nums: a, b = (~x&amp;a&amp;~b)|(x&amp;~a&amp;b), ~a&amp;(x^b) return b
single-number-ii
3 python solutions with different approaches
mritunjoyhalder79
9
796
single number ii
137
0.579
Medium
1,796
https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches
class Solution: def singleNumber(self, nums: List[int]) -> int: d = {} for i in nums: if i in d: d[i] += 1 else: d[i] = 1 for a,b in d.items(): print(a,b) if b == 1: return a
single-number-ii
3 python solutions with different approaches
mritunjoyhalder79
9
796
single number ii
137
0.579
Medium
1,797
https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches
class Solution(object): def singleNumber(self, nums): a = sum(nums) - 3*sum(set(list(nums))) return (-a)//2
single-number-ii
3 python solutions with different approaches
mritunjoyhalder79
9
796
single number ii
137
0.579
Medium
1,798
https://leetcode.com/problems/single-number-ii/discuss/936917/Python-Bitwise-Solution-with-Explanation
class Solution: def singleNumber(self, nums: List[int]) -> int: a, b = 0, 0 for c in nums: b = (b ^ c) &amp; ~a a = (a ^ c) &amp; ~b return b
single-number-ii
Python Bitwise Solution with Explanation
Picassos_Shoes
4
290
single number ii
137
0.579
Medium
1,799