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/range-sum-of-sorted-subarray-sums/discuss/1818999/Python-Brute-Force-Solution
class Solution: def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: sum_arr=[] for i in range(0, n): s=0 for j in range(i, n): s+=nums[j] sum_arr.append(s) sum_arr.sort() print(sum_arr) return sum(sum_arr[left-1: right])%1000000007
range-sum-of-sorted-subarray-sums
Python Brute Force Solution
Siddharth_singh
1
85
range sum of sorted subarray sums
1,508
0.593
Medium
22,400
https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/730522/PythonPython3-Range-Sum-of-Sorted-Sums
class Solution: def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: i,j,amount = 0,0,0 total_sum = [] while i < len(nums): if j == len(nums) - 1: amount += nums[j] total_sum.append(amount) i += 1 j = i amount = 0 else: if i == j: amount = nums[j] total_sum.append(amount) j += 1 else: amount += nums[j] total_sum.append(amount) j += 1 total_sum.sort() return sum(total_sum[left-1:right])%(10**9 + 7)
range-sum-of-sorted-subarray-sums
[Python/Python3] Range Sum of Sorted Sums
newborncoder
1
384
range sum of sorted subarray sums
1,508
0.593
Medium
22,401
https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/2516754/Python-3-or-Brutal-Force-10-lines-or-Explanation
class Solution: def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: ans = [nums[0]] for i in range(1, n): ans.append(nums[i]) nums[i] += nums[i-1] ans.append(nums[i]) for j in range(i-1): ans.append(nums[i] - nums[j]) ans.sort() return sum(ans[left-1:right]) % 1000000007
range-sum-of-sorted-subarray-sums
Python 3 | Brutal Force 10 lines | Explanation
idontknoooo
0
83
range sum of sorted subarray sums
1,508
0.593
Medium
22,402
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1433873/Python3Python-Easy-readable-solution-with-comments.
class Solution: def minDifference(self, nums: List[int]) -> int: n = len(nums) # If nums are less than 3 all can be replace, # so min diff will be 0, which is default condition if n > 3: # Init min difference min_diff = float("inf") # sort the array nums = sorted(nums) # Get the window size, this indicates, if we # remove 3 element in an array how many element # are left, consider 0 as the index, window # size should be (n-3), but for array starting # with 0 it should be ((n-1)-3) window = (n-1)-3 # Run through the entire array slinding the # window and calculating minimum difference # between the first and the last element of # that window for i in range(n): if i+window >= n: break else: min_diff = min(nums[i+window]-nums[i], min_diff) # return calculated minimum difference return min_diff return 0 # default condition
minimum-difference-between-largest-and-smallest-value-in-three-moves
[Python3/Python] Easy readable solution with comments.
ssshukla26
10
1,000
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,403
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/730686/Python3-1-line-O(N)
class Solution: def minDifference(self, nums: List[int]) -> int: return min(x-y for x, y in zip(nlargest(4, nums), reversed(nsmallest(4, nums))))
minimum-difference-between-largest-and-smallest-value-in-three-moves
[Python3] 1-line O(N)
ye15
9
1,300
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,404
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/730686/Python3-1-line-O(N)
class Solution: def minDifference(self, nums: List[int]) -> int: small = nsmallest(4, nums) large = nlargest(4, nums) return min(x-y for x, y in zip(large, reversed(small)))
minimum-difference-between-largest-and-smallest-value-in-three-moves
[Python3] 1-line O(N)
ye15
9
1,300
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,405
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/921535/Python-O(N)-Time-O(1)-Space-beats-100-without-sorting
class Solution: def minDifference(self, nums: List[int]) -> int: if len(nums) < 5: return 0 maxV, minV = [-float('inf')] * 4, [float('inf')] * 4 for n in nums: if n > maxV[0]: maxV[0] = n for i in range(0, 3): if maxV[i] > maxV[i + 1]: maxV[i], maxV[i + 1] = maxV[i + 1], maxV[i] if n < minV[0]: minV[0] = n for i in range(0, 3): if minV[i] < minV[i + 1]: minV[i], minV[i + 1] = minV[i + 1], minV[i] return min(maxV[i] - minV[3 - i] for i in range(4))
minimum-difference-between-largest-and-smallest-value-in-three-moves
[Python] O(N) Time, O(1) Space, beats 100 % without sorting
licpotis
6
987
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,406
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1902571/Python-sliding-window
class Solution: def minDifference(self, nums: List[int]) -> int: # sliding window n = len(nums) if n <= 4: return 0 smallest = float("inf") nums.sort() window = n - 4 for i in range(4): smallest = min(smallest, nums[i+window] - nums[i]) return smallest
minimum-difference-between-largest-and-smallest-value-in-three-moves
Python sliding window
ganyue246
1
175
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,407
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/2849174/Shift-based-O(n)-Solution-(without-sorting)
class Solution: def minDifference(self, nums: List[int]) -> int: # do not need to keep indices, can safely remove duplicates top_vals = [float("-inf")] * 4 bot_vals = [float("inf")] * 4 if len(nums) <= 4: return 0 def _shift_right(q, el, st): for l in range(len(q) - 1, st, -1): q[l] = q[l - 1] q[st] = el def _push_item_top(n, q): if n > q[0]: _shift_right(q, n, 0) return for i in range(0, len(q) - 1): if q[i + 1] < n <= q[i]: _shift_right(q, n, i + 1) break def _push_item_bot(n, q): if n < q[0]: _shift_right(q, n, 0) return for i in range(0, len(q) - 1): if q[i + 1] > n >= q[i]: _shift_right(q, n, i + 1) break for num in nums: _push_item_top(num, top_vals) _push_item_bot(num, bot_vals) ans = float("inf") for top_rem in range(0, 4): bot_rem = 3 - top_rem diff = top_vals[top_rem] - bot_vals[bot_rem] if diff >= 0 and diff < ans: ans = diff return ans
minimum-difference-between-largest-and-smallest-value-in-three-moves
Shift-based O(n) Solution (without sorting)
devtrent
0
2
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,408
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/2638350/Python-checking-all-possibilities-sorting.-O(N)O(N)
class Solution: def minDifference(self, nums: List[int]) -> int: if len(nums) <= 4: return 0 nums.sort() return min(nums[-1-i] - nums[3-i] for i in range(4))
minimum-difference-between-largest-and-smallest-value-in-three-moves
Python, checking all possibilities, sorting. O(N)/O(N)
blue_sky5
0
6
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,409
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/2370193/python-o(nlogn)
class Solution: def minDifference(self, nums: List[int]) -> int: if len(nums) <= 3: return 0 nums.sort() t1 = nums[-1] - nums[3] t2 = nums[-4] - nums[0] t3 = nums[-2] - nums[2] t4 = nums[-3] - nums[1] return min(t1,t2,t3,t4)
minimum-difference-between-largest-and-smallest-value-in-three-moves
python o(nlogn)
ddawngbof
0
44
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,410
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/2302806/Python3-brute-force-unpythonic-for-readability-and-flexibility
class Solution: def minDifference(self, nums: List[int]) -> int: moves = 3 left, right = 0, len(nums) - 1 nums.sort() def diff(i: int, left: int, right: int) -> int: if i == moves or left == right: return nums[right] - nums[left] # remove smallest or remove biggest remove_left = diff(i + 1, left + 1, right) remove_right = diff(i + 1, left, right - 1) return min(remove_left, remove_right) return diff(0, left, right)
minimum-difference-between-largest-and-smallest-value-in-three-moves
[Python3] brute force unpythonic for readability and flexibility
parmenio
0
46
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,411
https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1701502/Simple-python-heapq-solution
class Solution: def minDifference(self, nums: List[int]) -> int: heapq.heapify(nums) return min(map(lambda x, y: x-y, heapq.nlargest(4,nums), heapq.nsmallest(4,nums)[::-1]))
minimum-difference-between-largest-and-smallest-value-in-three-moves
Simple python heapq solution
nidinlal
0
55
minimum difference between largest and smallest value in three moves
1,509
0.546
Medium
22,412
https://leetcode.com/problems/stone-game-iv/discuss/1708107/Python3-DP
class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [False] * (n + 1) squares = [] curSquare = 1 for i in range(1, n + 1): if i == curSquare * curSquare: squares.append(i) curSquare += 1 dp[i] = True else: for square in squares: if not dp[i - square]: dp[i] = True break return dp[n]
stone-game-iv
[Python3] DP
PatrickOweijane
8
397
stone game iv
1,510
0.605
Hard
22,413
https://leetcode.com/problems/stone-game-iv/discuss/730695/Python3-bottom-up-dp
class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [False] * (n+1) for x in range(1, n+1): for k in range(1, int(sqrt(x))+1): if not dp[x-k*k]: dp[x] = True break return dp[-1]
stone-game-iv
[Python3] bottom-up dp
ye15
3
223
stone game iv
1,510
0.605
Hard
22,414
https://leetcode.com/problems/stone-game-iv/discuss/730695/Python3-bottom-up-dp
class Solution: def winnerSquareGame(self, n: int) -> bool: @cache def fn(x): if x == 0: return False for k in range(1, int(sqrt(x))+1): if not fn(x-k*k): return True return False return fn(n)
stone-game-iv
[Python3] bottom-up dp
ye15
3
223
stone game iv
1,510
0.605
Hard
22,415
https://leetcode.com/problems/stone-game-iv/discuss/732761/Python-DP-with-clear-step-by-step-comments
class Solution: def winnerSquareGame(self, n: int) -> bool: dp = [False for _ in range(n+1)] # init dp[0] as False since it implies no move to make. dp[1] = True # known corner case for i in range(2,n+1): # for every i in [2,n] sqr = int(i**0.5) # calculate upper bound for integer square root less than i for j in range(1, sqr+1): # for every integer square root less than sqrt(i) dp[i] |= not dp[i-j**2] # if there is any n == (i-j**2) that is doomed to lose, i should be true. # because Alice can make that move(remove j**2 stones) and make Bob lose. # otherwise i should be false since there is no any choice that will lead to winning. if dp[i]: # Optimization due to test case TLE: if it is already true, break out. break return dp[n]
stone-game-iv
Python DP with clear step-by-step comments
iamlockon
1
65
stone game iv
1,510
0.605
Hard
22,416
https://leetcode.com/problems/stone-game-iv/discuss/1711507/Python3-Solution
class Solution: def winnerSquareGame(self, n): @lru_cache(None) def dfs(state): if state == 0: return False for i in range(1, int(math.sqrt(state))+1): if not dfs(state - i*i): return True return False return dfs(n)
stone-game-iv
Python3 Solution
nomanaasif9
0
17
stone game iv
1,510
0.605
Hard
22,417
https://leetcode.com/problems/stone-game-iv/discuss/1710733/Python-simple-DP-solution
class Solution: def winnerSquareGame(self, n: int) -> bool: game = [False] * (n + 1) for i in range(0, n + 1): if game[i]: continue for k in range(int((n - i) ** 0.5), 0, -1): pos = i + k ** 2 if pos == n: return True if pos < n: game[pos] = True return False
stone-game-iv
Python simple DP solution
johnro
0
32
stone game iv
1,510
0.605
Hard
22,418
https://leetcode.com/problems/stone-game-iv/discuss/1709616/Python-3-or-O(n)-or-easy-dp-solution
class Solution: def winnerSquareGame(self, n: int) -> bool: squares = [] for i in range(1, n + 1): if i * i <= n: squares.append(i * i) dp = [False] * (n + 1) for i in range(1, n + 1): for square in squares: if square <= i and dp[i - square] is False: dp[i] = True break return dp[n]
stone-game-iv
[Python 3] | O(n) | easy-dp solution
BrijGwala
0
24
stone game iv
1,510
0.605
Hard
22,419
https://leetcode.com/problems/stone-game-iv/discuss/1708615/PYTHON-3-or-Memoziation-or-O(N)-Time-and-Space
class Solution: def game(self,alice,stones): if stones in self.results[alice]: return self.results[alice][stones] if stones==0: return not alice win,s=True,int(stones**0.5) if alice: win=False while s**2>0: if alice: win=win or self.game(not alice,stones-s**2) else: win=win and self.game(not alice,stones-s**2) if (alice and win) or (not alice and not win): break s-=1 self.results[alice][stones]=win return self.results[alice][stones] def winnerSquareGame(self, n: int) -> bool: # True for Alice Turn and False for Bob # For each num of stones save result of game self.results={True:{},False:{}} return self.game(True,n)
stone-game-iv
PYTHON 3 | Memoziation | O(N) Time & Space
saa_73
0
45
stone game iv
1,510
0.605
Hard
22,420
https://leetcode.com/problems/stone-game-iv/discuss/1708336/Python-oror-Recursive-oror-optimal-oror-DP-DFS-oror-Easy-to-understand
class Solution: @cache def winnerSquareGame(self, n: int) -> bool: if n <= 0: return False for i in range(floor(sqrt(n)),0,-1): if self.winnerSquareGame(n-i**2) ==0: return True return False
stone-game-iv
Python || Recursive || optimal || ❌ DP ❌ DFS || Easy to understand
rushi_javiya
0
55
stone game iv
1,510
0.605
Hard
22,421
https://leetcode.com/problems/stone-game-iv/discuss/1708287/Python-Solution-using-Dynamic-Programming
class Solution: def winnerSquareGame(self, n: int) -> bool: dp=[False]*(n+1) for i in range(1,n+1): for j in range(1,int(i**0.5)+1): if dp[i-j**2]==False: dp[i]=True break return dp[n]
stone-game-iv
✔✔ Python Solution using Dynamic Programming 🔥
ASHOK_KUMAR_MEGHVANSHI
0
44
stone game iv
1,510
0.605
Hard
22,422
https://leetcode.com/problems/stone-game-iv/discuss/1385878/Python-short-top-down-solution
class Solution: def winnerSquareGame(self, n: int) -> bool: squares, memory, i = [], {}, 1 while i * i <= n: squares.append(i * i) i += 1 squares.reverse() def approach(num): nonlocal squares if num <= 0: return False if num in memory: return memory[num] memory[num] = any(not approach(num - s) for s in squares if s <= num) return memory[num] return approach(n)
stone-game-iv
Python short top down solution
yiseboge
0
87
stone game iv
1,510
0.605
Hard
22,423
https://leetcode.com/problems/stone-game-iv/discuss/1346503/Fast-and-CLEAN-commented-try-all-options-for-the-player-%3A)-n-1-n-4n-9....n-X*X....-for-all-sqr
class Solution: def winnerSquareGame(self, n: int) -> bool: @cache def doIWin(n, isAlice): if n == 0: return False # I lost, i cannot pick anything more :( sqr = 1 while sqr*sqr <= n: if False == doIWin(n-sqr*sqr, 1 ^ isAlice): # i forced my opponent to lose :) return True sqr += 1 # I did not find any way to make opponent lose.. return False return doIWin(n, True) """ No need of 'isAlice' :) Just makes the code cleaner? """ @cache def doIWin(n): if n == 0: return False # I lost, i cannot pick anything more :( sqr = 1 while sqr*sqr <= n: if False == doIWin(n-sqr*sqr): # i forced my opponent to lose :) return True sqr += 1 # I did not find any way to make opponent lose.. return False return doIWin(n) # final optimization.. travel backwards from sqrt to 1 :) @cache def doIWin(n): if n == 0: return False # I lost, i cannot pick anything more :( sqr = floor(sqrt(n)) while sqr: if not doIWin(n-sqr*sqr): # i forced my opponent to lose :) return True sqr -= 1 # I did not find any way to make opponent lose.. return False return doIWin(n)
stone-game-iv
Fast and CLEAN commented try all options for the player :) n-1, n-4,n-9,....n-X*X.... for all sqr
yozaam
0
92
stone game iv
1,510
0.605
Hard
22,424
https://leetcode.com/problems/stone-game-iv/discuss/910135/Python-DP
class Solution: def winnerSquareGame(self, n: int) -> bool: dp: List[bool] = [False] * (n+1) for i in range(1, n+1): for j in range(1, math.isqrt(i)+1): if not dp[i - j**2]: dp[i] = True break return dp[n]
stone-game-iv
Python DP
vlee
0
41
stone game iv
1,510
0.605
Hard
22,425
https://leetcode.com/problems/stone-game-iv/discuss/731278/Python-Very-Easy-To-Read-beats-85-and-100
class Solution: def __init__(self): self.cache = {} def winnerSquareGame(self, n: int) -> bool: if not n: return False if n in self.cache: return self.cache[n] i = int(math.sqrt(n)) while i >= 1: if not self.winnerSquareGame(n - i*i): self.cache[n] = True return self.cache[n] i -= 1 self.cache[n] = False return self.cache[n]
stone-game-iv
Python Very Easy To Read, beats 85% and 100%
sexylol
0
50
stone game iv
1,510
0.605
Hard
22,426
https://leetcode.com/problems/number-of-good-pairs/discuss/749025/Python-O(n)-simple-dictionary-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: hashMap = {} res = 0 for number in nums: if number in hashMap: res += hashMap[number] hashMap[number] += 1 else: hashMap[number] = 1 return res
number-of-good-pairs
Python O(n) simple dictionary solution
Arturo001
88
6,200
number of good pairs
1,512
0.882
Easy
22,427
https://leetcode.com/problems/number-of-good-pairs/discuss/1202414/WEEB-EXPLAINS-PYTHON(BEATS-97.65)
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: nums, memo = sorted(nums), {} # sort to get the total number of digits that have duplicates for i in range(len(nums)-1): # lets say nums = [1,1,1,1,2,2,2,3] the total digits with duplicates is 7 if nums[i] == nums[i+1]: # because nums has 4 ones and 3 twos so it adds up to 7 if nums[i] not in memo: # 3 is not counted because there are no duplicates of it memo[nums[i]] = 1 memo[nums[i]] = memo[nums[i]] + 1 # nums = [1,1,1,1,2,2,2,3] # so now memo = {1 : 4, 2: 3} which means we have 4 ones and 3 twos answer = 0 for n in memo.values(): # this is the hard part, please refer to my beautiful drawing to understand this answer += (n**2 - n)//2 # after looking at the drawing, we repeat with each n value in memo return answer
number-of-good-pairs
WEEB EXPLAINS PYTHON(BEATS 97.65%)
Skywalker5423
28
1,200
number of good pairs
1,512
0.882
Easy
22,428
https://leetcode.com/problems/number-of-good-pairs/discuss/941242/Python-Simple-Solutions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: c=0 for i in range(len(nums)): c+=nums[:i].count(nums[i]) return c
number-of-good-pairs
Python Simple Solutions
lokeshsenthilkumar
15
1,200
number of good pairs
1,512
0.882
Easy
22,429
https://leetcode.com/problems/number-of-good-pairs/discuss/941242/Python-Simple-Solutions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: d={};c=0 for i in nums: if i in d: c+=d[i] d[i]+=1 else: d[i]=1 return c
number-of-good-pairs
Python Simple Solutions
lokeshsenthilkumar
15
1,200
number of good pairs
1,512
0.882
Easy
22,430
https://leetcode.com/problems/number-of-good-pairs/discuss/1122623/Clear-explanation-using-Combinations-for-pairs
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: pairs = 0 counts = {} for num in nums: prior_num_count = counts.get(num, 0) pairs += prior_num_count counts[num] = prior_num_count + 1 return pairs
number-of-good-pairs
Clear explanation using Combinations for pairs
alexanco
11
646
number of good pairs
1,512
0.882
Easy
22,431
https://leetcode.com/problems/number-of-good-pairs/discuss/990196/Python-3-faster-than-99.48
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: ans = 0 d = defaultdict(list) for i in range(len(nums)): d[nums[i]].append(i) # print(d) for k,v in d.items(): n = len(v) # print(n) if n > 1: ans += ((n-1) * n) // 2 return ans
number-of-good-pairs
Python 3, faster than 99.48%
Narasimhag
7
848
number of good pairs
1,512
0.882
Easy
22,432
https://leetcode.com/problems/number-of-good-pairs/discuss/837450/Python3-solution-with-a-single-pass-and-no-if-else-statements
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: my_count = 0 my_dict = {} for n in nums: # Check to see if number has already been encountered # and increase count by the number of previous instances my_count += my_dict.get(n, 0) # Increase the count of previous observation # Or store newly encountered number along with its count my_dict[n] = my_dict.get(n, 0) + 1 return my_count
number-of-good-pairs
Python3 solution with a single pass and no if-else statements
ecampana
5
435
number of good pairs
1,512
0.882
Easy
22,433
https://leetcode.com/problems/number-of-good-pairs/discuss/1976561/Python-3-greater-99-fast.-3-solutions-each-better-than-the-other
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: mapping = collections.defaultdict(list) count = 0 for i, num in enumerate(nums): mapping[num].append(i) for indexes in mapping.values(): for i in range(len(indexes)-1): for j in range(i+1, len(indexes)): count += 1 return count
number-of-good-pairs
Python 3 -> 99% fast. 3 solutions each better than the other
mybuddy29
4
217
number of good pairs
1,512
0.882
Easy
22,434
https://leetcode.com/problems/number-of-good-pairs/discuss/1976561/Python-3-greater-99-fast.-3-solutions-each-better-than-the-other
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: mapping = collections.defaultdict(list) count = 0 for i, num in enumerate(nums): mapping[num].append(i) for indexes in mapping.values(): size = len(indexes) count += (size * (size-1))//2 return count
number-of-good-pairs
Python 3 -> 99% fast. 3 solutions each better than the other
mybuddy29
4
217
number of good pairs
1,512
0.882
Easy
22,435
https://leetcode.com/problems/number-of-good-pairs/discuss/1976561/Python-3-greater-99-fast.-3-solutions-each-better-than-the-other
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: mapping = collections.Counter(nums) count = 0 for value in mapping.values(): count += (value * (value-1))//2 return count
number-of-good-pairs
Python 3 -> 99% fast. 3 solutions each better than the other
mybuddy29
4
217
number of good pairs
1,512
0.882
Easy
22,436
https://leetcode.com/problems/number-of-good-pairs/discuss/1479230/Python3-solution-using-dictionary
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: mydict = {} for i in nums: if i not in mydict: mydict[i] = 1 else: mydict[i] += 1 count = 0 for i in mydict: count += (mydict[i]*(mydict[i]-1))/2 return int(count)
number-of-good-pairs
Python3 solution using dictionary
s_m_d_29
3
316
number of good pairs
1,512
0.882
Easy
22,437
https://leetcode.com/problems/number-of-good-pairs/discuss/1147877/Brute-Force-Solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums) - 1): for j in range(i + 1 , len(nums)): if(nums[i] == nums[j]): count += 1 return count
number-of-good-pairs
Brute Force Solution
VoidCupboard
3
63
number of good pairs
1,512
0.882
Easy
22,438
https://leetcode.com/problems/number-of-good-pairs/discuss/2400203/python-o2-solution
class SolutionTwo: def numIdenticalPairs(self, nums: List[int]) -> int: goodPairs = 0; for i in range(0, len(nums)): for j in range(i + 1, len(nums)): if (nums[i] == nums[j]): goodPairs += 1; return goodPairs;
number-of-good-pairs
python o[2] solution
fida10
2
100
number of good pairs
1,512
0.882
Easy
22,439
https://leetcode.com/problems/number-of-good-pairs/discuss/2250415/Python3-O(n)-oror-O(n)-Runtime%3A-47ms-60.77-Memory%3A-13.8mb-95.62
class Solution: # O(n) || O(n) # Runtime: 47ms 60.77% Memory: 13.8mb 95.62% def numIdenticalPairs(self, nums: List[int]) -> int: if not nums: return 0 freqOfNumber = Counter(nums) return sum([key * (key - 1) // 2 for key in freqOfNumber.values()])
number-of-good-pairs
Python3 O(n) || O(n) # Runtime: 47ms 60.77% Memory: 13.8mb 95.62%
arshergon
2
84
number of good pairs
1,512
0.882
Easy
22,440
https://leetcode.com/problems/number-of-good-pairs/discuss/1151138/Python3-Brute-Force-and-99-faster-than-online-python3-sumbissions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): for j in range(i + 1 , len(nums)): if(nums[i] == nums[j]): count += 1 return count
number-of-good-pairs
[Python3] Brute Force and 99% faster than online python3 sumbissions
Lolopola
2
135
number of good pairs
1,512
0.882
Easy
22,441
https://leetcode.com/problems/number-of-good-pairs/discuss/1143065/Python-Simple-and-Easy-To-Understand-Solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): for j in range(len(nums)): if nums[i] == nums[j] and i < j: count+=1 return count
number-of-good-pairs
Python Simple & Easy To Understand Solution
saurabhkhurpe
2
491
number of good pairs
1,512
0.882
Easy
22,442
https://leetcode.com/problems/number-of-good-pairs/discuss/771943/A-Different-Yet-Simple-Python-Solution-Faster-Than-88.7-and-Beats-58.8-on-Space
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: d = {} res = 0 for n in nums: if n in d: res += d[n] d[n] += 1 else: d[n] = 1 return res
number-of-good-pairs
A Different Yet Simple Python Solution - Faster Than 88.7% and Beats 58.8% on Space
parkershamblin
2
306
number of good pairs
1,512
0.882
Easy
22,443
https://leetcode.com/problems/number-of-good-pairs/discuss/757652/Python3-program-faster-than-100
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: i, ans, nums = 0, 0, sorted(nums) for j in range(1, len(nums)): if nums[i] == nums[j]: ans += (j - i) else: i = j return ans
number-of-good-pairs
Python3 program faster than 100%
ashmit007
2
176
number of good pairs
1,512
0.882
Easy
22,444
https://leetcode.com/problems/number-of-good-pairs/discuss/731670/PythonPython3-Number-of-Good-Pairs
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: i = 0 for x in range(len(nums)): for y in range(x+1,len(nums)): if x<y and nums[x] == nums[y]: i += 1 return i
number-of-good-pairs
[Python/Python3] Number of Good Pairs
newborncoder
2
504
number of good pairs
1,512
0.882
Easy
22,445
https://leetcode.com/problems/number-of-good-pairs/discuss/2598265/python-solution-using-two-for-loops
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count=0 n=len(nums) for i in range(n): for j in range(i+1, n): if nums[i]==nums[j] and i<j: count+=1 return count
number-of-good-pairs
python solution using two for loops
Vidyart29
1
169
number of good pairs
1,512
0.882
Easy
22,446
https://leetcode.com/problems/number-of-good-pairs/discuss/2412848/Python-3-or-3-Different-Solutions-or-T.C%3A-O(n)-S.C%3A-O(n)
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: # Method 1: Brute Force T.C: O(nˆ2) S.C: O(1) count = 0 for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] == nums[j] and i<j: count += 1 return count # Method 2: T.C: O(n+n) S.C: O(n) count = {} for i in range(len(nums)): count[nums[i]] = 1 + count.get(nums[i],0) ans = 0 for key,val in count.items(): if val>1: math = val * (val-1)//2 ans += math return ans # Method 3 (Most Efficient): T.C: O(n) S.C: O(n) count = {} ans = 0 for i in range(len(nums)): if nums[i] in count: ans += count[nums[i]] count[nums[i]] = 1 + count.get(nums[i],0) return ans # Search answers with tag chawlashivansh to find my answers.
number-of-good-pairs
Python 3 | 3 Different Solutions | T.C: O(n) S.C: O(n)
chawlashivansh
1
71
number of good pairs
1,512
0.882
Easy
22,447
https://leetcode.com/problems/number-of-good-pairs/discuss/2014021/Python-One-Liner!
class Solution: def numIdenticalPairs(self, nums): return sum(n*(n-1)//2 for n in Counter(nums).values())
number-of-good-pairs
Python - One-Liner!
domthedeveloper
1
175
number of good pairs
1,512
0.882
Easy
22,448
https://leetcode.com/problems/number-of-good-pairs/discuss/1950511/Python3-solution-Easy
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] == nums[j]: count += 1 return count
number-of-good-pairs
Python3 solution - Easy
amarthineni
1
82
number of good pairs
1,512
0.882
Easy
22,449
https://leetcode.com/problems/number-of-good-pairs/discuss/1935268/Python-3-Solution-95-faster-and-less-storage
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: x = dict(Counter(nums)) #count frequency of each element count = 0 for i, j in x.items(): count += (j*(j-1))/2 #count of good pairs return int(count)
number-of-good-pairs
Python 3 Solution [ 95% faster and less storage ]
__vishal07__
1
92
number of good pairs
1,512
0.882
Easy
22,450
https://leetcode.com/problems/number-of-good-pairs/discuss/1822384/Python3-92.3-faster-than-other-user-and-73-less-space-usages
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 frequency_array = [0]*101 for i in nums: frequency_array[i]+=1 for i in nums: count += frequency_array[i]-1 frequency_array[i]-=1 return count
number-of-good-pairs
[Python3] 92.3% faster than other user and 73% less space usages
ankushbisht01
1
111
number of good pairs
1,512
0.882
Easy
22,451
https://leetcode.com/problems/number-of-good-pairs/discuss/1725166/1512-good_pairs%3A-for-loops-submissions-that-beats-84-and-19
class Solution(object): def numIdenticalPairs(self, nums): good_pairs = 0 for i in range(0,len(nums)): for j in range(0,len(nums)): if nums[i] == nums[j] and (i<j): good_pairs += 1 return good_pairs
number-of-good-pairs
1512 - good_pairs: for loops submissions that beats 84% & 19%
ankit61d
1
79
number of good pairs
1,512
0.882
Easy
22,452
https://leetcode.com/problems/number-of-good-pairs/discuss/1725166/1512-good_pairs%3A-for-loops-submissions-that-beats-84-and-19
class Solution(object): def numIdenticalPairs(self, nums): good_pairs = 0 for i in range(0,len(nums)): for j in range(i+1,len(nums)): if nums[i] == nums[j]: good_pairs += 1 return good_pairs
number-of-good-pairs
1512 - good_pairs: for loops submissions that beats 84% & 19%
ankit61d
1
79
number of good pairs
1,512
0.882
Easy
22,453
https://leetcode.com/problems/number-of-good-pairs/discuss/1377256/Easiest-Python-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(0,len(nums)): for j in range(i+1,len(nums)): if nums[i] == nums[j]: count += 1 return count
number-of-good-pairs
Easiest Python solution
ajaykathwate
1
161
number of good pairs
1,512
0.882
Easy
22,454
https://leetcode.com/problems/number-of-good-pairs/discuss/1100304/Python-3-Unique-Solution-using-Math
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: nums_count = Counter(nums) pairs = 0 for i in nums_count.values(): if i >= 2: pairs += factorial(i)/(2*factorial(i-2)) return int(pairs)
number-of-good-pairs
[Python 3] Unique Solution using Math
vatsalbhuva11
1
71
number of good pairs
1,512
0.882
Easy
22,455
https://leetcode.com/problems/number-of-good-pairs/discuss/1024381/Python-O(n)-91.82-runtime-and-98.58-memory
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: sort_nums = sorted(nums) # Sort numbers in list i = 0 # For while loop count = 0 # keep track of # of pairs l = len(sort_nums) # length of list while(i < l): # this gets the count (number of instances) a number shows up in the list n = sort_nums.count(sort_nums[i]) if n > 1: # We only care about counts that are greater than 1 since a pair requires 2 #'s i = i + n # since the list is in order we skip to the next different number in the loop by adding the count of the # current number in the list to i count = count + (n/2)*(n-1) # Since the list is in order, to solve how many pairs can be created by the current number we # are at we can use this arithmetic series to figure that out. #ex: [1,1,1] --> count = 3 --> (3/2) * (3-1) = 3 which is total of possible pairs else: i +=1 #1 number can't make a pair so go to next number in list return int(count)
number-of-good-pairs
Python O(n) 91.82% runtime & 98.58% memory
buttonpoker
1
179
number of good pairs
1,512
0.882
Easy
22,456
https://leetcode.com/problems/number-of-good-pairs/discuss/948903/Python3-%3A-Three-Solutions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): cur = nums[i] for j in range(i+1,len(nums)): if(nums[j] == cur): count += 1 return count
number-of-good-pairs
Python3 : Three Solutions
abhijeetmallick29
1
336
number of good pairs
1,512
0.882
Easy
22,457
https://leetcode.com/problems/number-of-good-pairs/discuss/948903/Python3-%3A-Three-Solutions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: d = {} count = 0 for i in range(len(nums)): count += d.get(nums[i],0) d[nums[i]] = d.get(nums[i],0) + 1 return count
number-of-good-pairs
Python3 : Three Solutions
abhijeetmallick29
1
336
number of good pairs
1,512
0.882
Easy
22,458
https://leetcode.com/problems/number-of-good-pairs/discuss/948903/Python3-%3A-Three-Solutions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: d = {} count = 0 for i in range(len(nums)): count += d.get(nums[i],0) d[nums[i]] = d.get(nums[i],0) + 1 return count
number-of-good-pairs
Python3 : Three Solutions
abhijeetmallick29
1
336
number of good pairs
1,512
0.882
Easy
22,459
https://leetcode.com/problems/number-of-good-pairs/discuss/731866/Python3-1-liner-Number-of-Good-Pairs
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: return sum((n-1) * n // 2 for n in Counter(nums).values())
number-of-good-pairs
Python3 1 liner - Number of Good Pairs
r0bertz
1
227
number of good pairs
1,512
0.882
Easy
22,460
https://leetcode.com/problems/number-of-good-pairs/discuss/731617/Python3-frequency-table
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: freq = dict() for x in nums: freq[x] = 1 + freq.get(x, 0) return sum(v*(v-1)//2 for v in freq.values())
number-of-good-pairs
[Python3] frequency table
ye15
1
103
number of good pairs
1,512
0.882
Easy
22,461
https://leetcode.com/problems/number-of-good-pairs/discuss/2849175/Python-TIL
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: num = 0 end = len(nums) for i in range(end-1): for j in range(i+1, end): if nums[i]==nums[j]: num+=1 return num
number-of-good-pairs
Python - TIL
MichaelMcG5100
0
1
number of good pairs
1,512
0.882
Easy
22,462
https://leetcode.com/problems/number-of-good-pairs/discuss/2846445/Python3-Beats-96-of-Python-Submissions
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count = 0 for x in range (0, len(nums)): for y in range(x+1, len(nums)): if nums[x] == nums[y]: count += 1 return count
number-of-good-pairs
Python3 Beats 96% of Python Submissions
James-Kosinar
0
2
number of good pairs
1,512
0.882
Easy
22,463
https://leetcode.com/problems/number-of-good-pairs/discuss/2842925/1-line-solution-Python3
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: return len([(i,j ) for i in range(len(nums)) for j in range(i+1,len(nums)) if nums[j]==nums[i]])
number-of-good-pairs
1 line solution Python3
vovatoshev1986
0
3
number of good pairs
1,512
0.882
Easy
22,464
https://leetcode.com/problems/number-of-good-pairs/discuss/2840429/Clean-Python-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count, n = 0, len(nums) for i in range(n): for j in range(i + 1, n): if nums[i] == nums[j] and i < j: count += 1 return count
number-of-good-pairs
Clean Python solution
emrecoltu
0
2
number of good pairs
1,512
0.882
Easy
22,465
https://leetcode.com/problems/number-of-good-pairs/discuss/2839783/Solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: s=0 for i in range(len(nums)): for j in range(i+1,len(nums)): if(nums[i]==nums[j]): s+=1 return s
number-of-good-pairs
Solution
N1xnonymous
0
1
number of good pairs
1,512
0.882
Easy
22,466
https://leetcode.com/problems/number-of-good-pairs/discuss/2839625/Solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: s=0 for i in range(len(nums)): for j in range(1,len(nums)): if(nums[i]==nums[j] and i<j): s+=1 return s
number-of-good-pairs
Solution
N1xnonymous
0
1
number of good pairs
1,512
0.882
Easy
22,467
https://leetcode.com/problems/number-of-good-pairs/discuss/2837442/Easy-Python-Code-Begineers
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: output = 0 for i in range(0, len(nums)): for j in range (1, len(nums)): if nums[i]==nums[j] and i<j: output += 1 return output
number-of-good-pairs
Easy Python Code - Begineers
bharatvishwa
0
2
number of good pairs
1,512
0.882
Easy
22,468
https://leetcode.com/problems/number-of-good-pairs/discuss/2815459/Python-Easy-One-Liner
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: length = len(nums) return len([0 for i in range(0, length) for j in range(0, length) if nums[i] == nums[j] and i < j])
number-of-good-pairs
Python Easy One-Liner
PranavBhatt
0
7
number of good pairs
1,512
0.882
Easy
22,469
https://leetcode.com/problems/number-of-good-pairs/discuss/2807697/PYTHON3-BEST
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: repeat = {} num = 0 for i in nums: if i in repeat: if repeat[i] == 1: num += 1 else: num += repeat[i] repeat[i] += 1 else: repeat[i] = 1 return num
number-of-good-pairs
PYTHON3 BEST
Gurugubelli_Anil
0
3
number of good pairs
1,512
0.882
Easy
22,470
https://leetcode.com/problems/number-of-good-pairs/discuss/2805679/python-easy-Solution-O(n)
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: temp = {} ans = 0 for i in nums: if i not in temp: temp[i] = 1 else: ans += temp[i] temp[i] += 1 return ans
number-of-good-pairs
python easy Solution O(n)
game50914
0
4
number of good pairs
1,512
0.882
Easy
22,471
https://leetcode.com/problems/number-of-good-pairs/discuss/2780977/python-easy-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: count=0 for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]==nums[j] and i<j: count+=1 return count
number-of-good-pairs
python easy solution
user7798V
0
5
number of good pairs
1,512
0.882
Easy
22,472
https://leetcode.com/problems/number-of-good-pairs/discuss/2766626/Number-of-Good-Pairs
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: goodpairs=0 d=dict() for i in nums: if i not in d: d[i]=1 else: goodpairs+=d[i] d[i]+=1 return goodpairs # count=0 # for i in range(len(nums)): # for j in range(i+1,len(nums)): # if nums[i]==nums[j]: # count+=1 # return count
number-of-good-pairs
Number of Good Pairs
shivansh2001sri
0
5
number of good pairs
1,512
0.882
Easy
22,473
https://leetcode.com/problems/number-of-good-pairs/discuss/2751326/Beginner-friendly-python3-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: hm= {} #declaring an empty hashmap total=0 #variable that will store the sum of final pairs for i, val in enumerate(nums): #this loop counts the number of times perticuar number repeats in list nums if val in hm: hm[val]+=1 else: hm[val]=1 for i,val in enumerate(hm): #simply applything the formula on the repeated number values if hm[val]>1: hm[val]= int((hm[val]*(hm[val]-1))/2) total+=hm[val] return total
number-of-good-pairs
Beginner friendly python3 solution
rubalsxngh
0
5
number of good pairs
1,512
0.882
Easy
22,474
https://leetcode.com/problems/number-of-good-pairs/discuss/2713466/Python-90-faster-solution-or-use-hash-map
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: hash_table = {} good_pair_count = 0 for i in range(len(nums)): if nums[i] not in hash_table: hash_table[nums[i]] = 1 else: good_pair_count += hash_table[nums[i]] hash_table[nums[i]] += 1 return good_pair_count
number-of-good-pairs
Python 90% faster solution | use hash map
kawamataryo
0
8
number of good pairs
1,512
0.882
Easy
22,475
https://leetcode.com/problems/number-of-good-pairs/discuss/2703897/Python-simple-solution
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: pairs = 0 for i in range(len(nums)): j = len(nums)-1 while i < j: if nums[i] == nums[j]: pairs += 1 j -= 1 return pairs
number-of-good-pairs
Python simple solution
ft3793
0
5
number of good pairs
1,512
0.882
Easy
22,476
https://leetcode.com/problems/number-of-good-pairs/discuss/2700421/Simple-Python-Solution
class Solution: def calc(self,n): sum=0 for i in range(n): sum+=i return sum def numIdenticalPairs(self, nums: List[int]) -> int: count={} for i in range(len(nums)): if nums[i] not in count: count[nums[i]]=1 else: count[nums[i]]+=1 c=0 for i in count.keys(): if(count[i]!=1): c+=self.calc(count[i]) return c
number-of-good-pairs
Simple Python Solution
Kiran_Rokkam
0
3
number of good pairs
1,512
0.882
Easy
22,477
https://leetcode.com/problems/number-of-good-pairs/discuss/2688590/Python-Simplest-Solution-using-Dictionary-and-Maths
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: repetitions = {} for value in nums: repetitions[value] = repetitions.get(value, -1) + 1 return sum((v*(v+1))//2 for v in repetitions.values())
number-of-good-pairs
Python Simplest Solution using Dictionary and Maths
dionjw
0
5
number of good pairs
1,512
0.882
Easy
22,478
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731754/Python-Sum-of-Arithmetic-Progression-with-explanation-**100.00-Faster**
class Solution: def numSub(self, s: str) -> int: res = 0 s = s.split("0") for one in s: if one == "": continue n = len(one) temp = (n / 2)*(2*n + (n-1)*-1) if temp >= 1000000007: res += temp % 1000000007 else: res += temp return int(res)
number-of-substrings-with-only-1s
[Python] Sum of Arithmetic Progression with explanation **100.00% Faster**
Jasper-W
8
506
number of substrings with only 1s
1,513
0.454
Medium
22,479
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731634/Python3-count-continuous-%221%22
class Solution: def numSub(self, s: str) -> int: ans = n = 0 for c in s: if c == "0": ans = (ans + n*(n+1)//2) % 1_000_000_007 n = 0 else: n += 1 return (ans + n*(n+1)//2) % 1_000_000_007
number-of-substrings-with-only-1s
[Python3] count continuous "1"
ye15
2
134
number of substrings with only 1s
1,513
0.454
Medium
22,480
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1814012/Python-easy-to-read-and-understand
class Solution: def numSub(self, s: str) -> int: cnt, ans = 0, 0 for i in range(len(s)): if s[i] == '0': cnt = 0 else: cnt += 1 ans += cnt return ans % ((10**9)+7)
number-of-substrings-with-only-1s
Python easy to read and understand
sanial2001
1
101
number of substrings with only 1s
1,513
0.454
Medium
22,481
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731680/Python-3Number-of-Substring-With-only-1s.-Easy
class Solution: def numSub(self, s: str) -> int: res=0 one_rt = 0 for c in s: if c == '0': one_rt=0 else: one_rt+=1 res+=one_rt return res % 1000000007
number-of-substrings-with-only-1s
[Python 3]Number of Substring With only 1s. Easy
tilak_
1
68
number of substrings with only 1s
1,513
0.454
Medium
22,482
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731641/PythonPython3-Number-of-Substrings-with-only-1's
class Solution: def numSub(self, s: str) -> int: j = s.split('0') total = [] for x in j: if x: k = len(x) total.append(((k)*(k+1))//2) return sum(total)%(10**9+7)
number-of-substrings-with-only-1s
[Python/Python3] Number of Substrings with only 1's
newborncoder
1
133
number of substrings with only 1s
1,513
0.454
Medium
22,483
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731641/PythonPython3-Number-of-Substrings-with-only-1's
class Solution: def numSub(self, s: str) -> int: i, j, total, count_one = 0, 0, 0, 0 while j < len(s): if s[j] == '1': count_one += 1 elif count_one: i = j total += (((count_one)*(count_one+1))//2) count_one = 0 j += 1 total += (((count_one)*(count_one+1))//2) return total%(10**9+7)
number-of-substrings-with-only-1s
[Python/Python3] Number of Substrings with only 1's
newborncoder
1
133
number of substrings with only 1s
1,513
0.454
Medium
22,484
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/2713448/EASY-Beginner-Friendly-Python
class Solution: def numSub(self, s: str) -> int: x=[] n=len(s) i=0 while i<n: c=1 while i+1<n and s[i]==s[i+1]: c+=1 i+=1 if s[i]=="1": x.append("1"*c) i+=1 c=0 for i in x: n=len(i) c+=n*(n+1)//2 return c%(10**9 + 7)
number-of-substrings-with-only-1s
EASY Beginner Friendly Python
imamnayyar86
0
2
number of substrings with only 1s
1,513
0.454
Medium
22,485
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1800333/Python3-accepted-solution
class Solution: def numSub(self, s: str) -> int: s = (s.lstrip("0").split("0")) sum_=0 for i in range(len(s)): if(len(s[i])>0): sum_ += sum([j for j in range(1,len(s[i])+1)]) return sum_%1000000007
number-of-substrings-with-only-1s
Python3 accepted solution
sreeleetcode19
0
41
number of substrings with only 1s
1,513
0.454
Medium
22,486
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1703426/Python-trianglular-numbers
class Solution: def numSub(self, s: str) -> int: def format_ans(ans): return ans % ((10**9) + 7) # triangle number is how many combinations are in a given number excluding the empty set. # e.g: 111 (n=3) gives, (1, 1, 1) + (11, 11) + (111), or 6 def triangle(n): if n == 0: return 0 return n + triangle(n-1) s += '#' # just appending a termination char to make the iteration easier for the last char in string ans, cur = 0, 0 for c in s: if c == '1': cur += 1 else: ans += triangle(cur) cur = 0 return format_ans(ans)
number-of-substrings-with-only-1s
Python trianglular numbers
kevinquinnyo
0
60
number of substrings with only 1s
1,513
0.454
Medium
22,487
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1627163/Python-oror-Easy-solution-oror-beat~90
class Solution: def numSub(self, s: str) -> int: count = 0 for i, j in itertools.groupby(s): if i == "1": temp = len(list(j)) count += (temp * (temp + 1)) // 2 return count % (10 ** 9 + 7)
number-of-substrings-with-only-1s
Python || Easy solution || beat~90%
naveenrathore
0
76
number of substrings with only 1s
1,513
0.454
Medium
22,488
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1494150/Why-not-this
class Solution: def numSub(self, s: str) -> int: current_count = 0 total = 0 for c in s: if c == '1': current_count += 1 else: current_count = 0 total += current_count return total % (10**9 + 7)
number-of-substrings-with-only-1s
Why not this?
jiljiljiga
0
32
number of substrings with only 1s
1,513
0.454
Medium
22,489
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1170179/simple-and-easy-to-understand-python
class Solution: def numSub(self, s: str) -> int: res = 0 count = 0 for i in s: if i == "1": count+=1 res+=count else: count = 0 return res % (10**9+7)
number-of-substrings-with-only-1s
simple and easy to understand python
pheobhe
0
42
number of substrings with only 1s
1,513
0.454
Medium
22,490
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1090228/Python-Get's-the-Job-Done
class Solution: def numSub(self, s: str) -> int: result = 0 for x in s.split('0'): if not x: continue result += sum([i+1 for i in range(len(x))]) return result % ((10 ** 9) + 7)
number-of-substrings-with-only-1s
Python - Get's the Job Done
dev-josh
0
82
number of substrings with only 1s
1,513
0.454
Medium
22,491
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1090228/Python-Get's-the-Job-Done
class Solution: def numSub(self, s: str) -> int: result = 0 for x in s.split('0'): if not x: continue result += (len(x)*(len(x)+1)) // 2 return result % ((10 ** 9) + 7)
number-of-substrings-with-only-1s
Python - Get's the Job Done
dev-josh
0
82
number of substrings with only 1s
1,513
0.454
Medium
22,492
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/736604/Python%3A-faster-less-memory-than-100-(with-explanation)
class Solution: def numSub(self, s: str) -> int: # split into strings of ones only substrings = s.split('0') # each substring of length n adds (n)*(n+1)/2 substrings # some strings will have length 0, and that's ok num = 0 for sub in substrings: num += len(sub) * (len(sub) + 1) // 2 return num % (10 ** 9 + 7)
number-of-substrings-with-only-1s
Python: faster / less memory than 100% (with explanation)
catters
0
95
number of substrings with only 1s
1,513
0.454
Medium
22,493
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731664/Python-O(N)-Simple-easy-to-read-solution
class Solution: def numSub(self, s: str) -> int: def count_it(i): ret = 0 while i != 0: ret += i i -= 1 return ret if not s: return 0 intervals = [] ans, counter = 0, 0 for idx, c in enumerate(s): if c == '1': counter += 1 else: ans += count_it(counter) counter = 0 if idx == len(s)-1: ans += count_it(counter) return ans % (10**9 + 7) ```
number-of-substrings-with-only-1s
Python O(N) Simple easy to read solution
sexylol
0
40
number of substrings with only 1s
1,513
0.454
Medium
22,494
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731596/Two-Pointer-Method-or-O(N)-or-Python
class Solution: def numSub(self, s: str) -> int: ans = 0 n = len(s) i = 0 while(i<n-1): l = 0 # reset the substring length having all 1s equal to 0 if s[i] == '1': l += 1 for j in range(i+1, n): if(s[j] == '1'): l += 1 else: # We encounter '0' so we break and calculate the number of substrings. break ans += l*(l+1)//2; # Calculate number of non-empty substrings using above formula. i = j + 1 # Update i-pointer to the next character where last '0' is found else: i += 1 # keep on incrementing untill '1' is not found. # Since i goes upto the second last character only we need to check if the last character was included or not. # It will not be included if the second last character is '0', so check if last character was '1' and second last character is '0' # we increment the answer by 1. if s[-1] == '1' and s[-2] == '0': ans += 1 return ans%1000000007
number-of-substrings-with-only-1s
Two Pointer Method | O(N) | Python
bugsanderrors
0
44
number of substrings with only 1s
1,513
0.454
Medium
22,495
https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/1349154/Python3-One-line-Solution
class Solution: def numSub(self, s: str) -> int: return sum(map(lambda x: ((1+len(x))*len(x)//2)%(10**9+7), s.split('0')))
number-of-substrings-with-only-1s
[Python3] One line Solution
Utada
-1
62
number of substrings with only 1s
1,513
0.454
Medium
22,496
https://leetcode.com/problems/path-with-maximum-probability/discuss/731655/Python3-Dijkstra's-algo
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph, prob = dict(), dict() #graph with prob for i, (u, v) in enumerate(edges): graph.setdefault(u, []).append(v) graph.setdefault(v, []).append(u) prob[u, v] = prob[v, u] = succProb[i] h = [(-1, start)] #Dijkstra's algo seen = set() while h: p, n = heappop(h) if n == end: return -p seen.add(n) for nn in graph.get(n, []): if nn in seen: continue heappush(h, (p * prob.get((n, nn), 0), nn)) return 0
path-with-maximum-probability
[Python3] Dijkstra's algo
ye15
27
2,500
path with maximum probability
1,514
0.484
Medium
22,497
https://leetcode.com/problems/path-with-maximum-probability/discuss/731630/Python-or-Dijkstra-or-heap-or-commented
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: # construct the graph graph = collections.defaultdict(list) prob = collections.defaultdict(dict) for i,(p,[a,b]) in enumerate(zip(succProb,edges)): graph[a].append(b) graph[b].append(a) prob[a][b] = prob[b][a] = p # apply dijkstra dis = {start:1} for i in range(n): dis[i] = 0 visited = set([]) # note that Python only supports min-heap # so some tricks here to get a max-heap pq = [(-1,start)] while pq: _p, node = heapq.heappop(pq) visited.add(node) for child in graph[node]: if child not in visited: if dis[child] < -1 * _p * prob[node][child]: heapq.heappush(pq,(_p * prob[node][child],child)) dis[child] = -1 * _p * prob[node][child] return dis[end]
path-with-maximum-probability
Python | Dijkstra | heap | commented
since2020
4
553
path with maximum probability
1,514
0.484
Medium
22,498
https://leetcode.com/problems/path-with-maximum-probability/discuss/2846489/python-dijkstra
class Solution: def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: graph = defaultdict(list) for idx, (a, b) in enumerate(edges): c = -math.log(succProb[idx]) graph[a].append((b, c)) graph[b].append((a, c)) visited = set() q = [(0, start)] while len(q) > 0: cost, node = heapq.heappop(q) if node == end: return 2.71828 ** (-cost) if node not in visited: visited.add(node) for nex, edge_cost in graph[node]: heapq.heappush(q, (cost + edge_cost, nex)) return 0
path-with-maximum-probability
python dijkstra
xsdnmg
0
2
path with maximum probability
1,514
0.484
Medium
22,499