problem_title stringlengths 3 77 | python_solutions stringlengths 81 8.45k | post_href stringlengths 64 213 | upvotes int64 0 1.2k | question stringlengths 0 3.6k | post_title stringlengths 2 100 | views int64 1 60.9k | slug stringlengths 3 77 | acceptance float64 0.14 0.91 | user stringlengths 3 26 | difficulty stringclasses 3
values | __index_level_0__ int64 0 34k | number int64 1 2.48k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum sum circular subarray | class Solution:
def maxSubarraySumCircular(self, A: List[int]) -> int:
array_sum = 0
local_min_sum, global_min_sum = 0, float('inf')
local_max_sum, global_max_sum = 0, float('-inf')
for number in A:
local_min_sum = min( local_min_su... | https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/633106/Python-O(n)-Kadane-DP-w-Visualization | 12 | Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A... | Python O(n) Kadane // DP [w/ Visualization] | 1,100 | maximum-sum-circular-subarray | 0.382 | brianchiang_tw | Medium | 14,898 | 918 |
number of music playlists | class Solution:
def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
@cache
def fn(i, x):
"""Return number starting from ith position with x songs already appeared."""
if i == goal: return x == n
ans = 0
if x < n: ans += (n-x) * f... | https://leetcode.com/problems/number-of-music-playlists/discuss/1358218/Python3-top-down-dp | 2 | Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
Every song is played at least once.
A song can only be played again only if k other songs have been played.
Given n, goal, and k, return the ... | [Python3] top-down dp | 132 | number-of-music-playlists | 0.506 | ye15 | Hard | 14,905 | 920 |
minimum add to make parentheses valid | class Solution:
def minAddToMakeValid(self, s: str) -> int:
count = 0
x = y = 0
for i in s:
if(i == '('):
x += 1
else:
x -= 1
if(x < 0):
count += 1
x = 0
... | https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1230943/Python3-Simple-Solution | 4 | A parentheses string is valid if and only if:
It is the empty string,
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.
F... | [Python3] Simple Solution | 72 | minimum-add-to-make-parentheses-valid | 0.762 | VoidCupboard | Medium | 14,906 | 921 |
sort array by parity ii | class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
odd,even = [],[]
for n in nums:
if n%2: odd.append(n)
else: even.append(n)
o,e = 0,0
for i in range(len(nums)):
if i%2==0:
nums[i]=even[e]
e+=1
else:
... | https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1490850/Simple-to-understand-oror-For-Beginners-oror-91-faster | 6 | Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation... | 📌📌 Simple to understand || For Beginners || 91% faster 🐍 | 283 | sort-array-by-parity-ii | 0.707 | abhi9Rai | Easy | 14,947 | 922 |
3sum with multiplicity | class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
arr.sort()
# the rest of the code here | https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation | 89 | Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.
As the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (ar... | [Python] 3Sum Approach with Explanation | 5,500 | 3sum-with-multiplicity | 0.454 | zayne-siew | Medium | 14,976 | 923 |
minimize malware spread | class Solution:
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
initial = set(initial)
def dfs(i):
nodes.add(i)
for j, conn in enumerate(graph[i]):
if conn and j not in nodes:
dfs(j)
... | https://leetcode.com/problems/minimize-malware-spread/discuss/1934636/Simple-Python-DFS-with-no-Hashmap | 0 | You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, bo... | Simple Python DFS with no Hashmap | 29 | minimize-malware-spread | 0.421 | totoslg | Hard | 14,985 | 924 |
long pressed name | class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
ni = 0 # index of name
ti = 0 # index of typed
while ni <= len(name) and ti < len(typed):
if ni < len(name) and typed[ti] == name[ni]:
ti += 1
ni += 1
... | https://leetcode.com/problems/long-pressed-name/discuss/1343001/Python3-2-pointers | 6 | Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being... | [Python3] 2 pointers | 521 | long-pressed-name | 0.337 | samirpaul1 | Easy | 14,986 | 925 |
flip string to monotone increasing | class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
"""
0 0 1 1 0
oneCount: 0 0 1 2 2
zeroCount: 1 1 0 0 1
flipCount: 0 0 0 0 1
0 1 0 1 0
oneCount: 0 1 1 2 2
zeroCount: 1 0 1 1 2
fl... | https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1535758/Python3 | 2 | A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).
You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.
Return the minimum number of flips to make s monotone increasing.
Example 1:
Inpu... | [Python3] | 165 | flip-string-to-monotone-increasing | 0.596 | zhanweiting | Medium | 15,002 | 926 |
three equal parts | class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
# count number of ones
ones = sum(arr)
if ones % 3 != 0:
return [-1, -1]
elif ones == 0: # special case: all zeros
return [0, 2]
# find the start index of each group of o... | https://leetcode.com/problems/three-equal-parts/discuss/1343709/2-clean-Python-linear-solutions | 7 | You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j] with i + 1 < j, such that:
arr[0], arr[1], ..., arr[i] is the first part,
arr[i + 1], arr[i + 2], ..., arr[j - ... | 2 clean Python linear solutions | 265 | three-equal-parts | 0.396 | cthlo | Hard | 15,021 | 927 |
minimize malware spread ii | class Solution:
# the key observation for me is the fact that we don't need to
# really delete the initial in the graph. We can simply ignore
# the deleted initial while we are doing BFS. So basically we
# do BFS with each deleted value on initial, and we get the
# minimal count of the connected gra... | https://leetcode.com/problems/minimize-malware-spread-ii/discuss/2845885/Python-9-lines-O(kn2)-BFS | 0 | You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, bo... | Python 9 lines O(kn^2) BFS | 2 | minimize-malware-spread-ii | 0.426 | tinmanSimon | Hard | 15,027 | 928 |
unique email addresses | class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def parse(email):
local, domain = email.split('@')
local = local.split('+')[0].replace('.',"")
return f"{local}@{domain}"
return len(set(map(parse, emails))) | https://leetcode.com/problems/unique-email-addresses/discuss/261959/Easy-understanding-python-solution-(44ms-faster-than-99.3) | 19 | Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.
For example, in "alice@leetcode.com", "alice" is the local name, and "leetcode.com" is the domain name.
If you add periods '.' between some characters in the ... | Easy-understanding python solution (44ms, faster than 99.3%) | 1,300 | unique-email-addresses | 0.672 | ShaneTsui | Easy | 15,029 | 929 |
binary subarrays with sum | class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
ans = prefix = 0
seen = {0: 1}
for x in A:
prefix += x
ans += seen.get(prefix - S, 0)
seen[prefix] = 1 + seen.get(prefix, 0)
return ans | https://leetcode.com/problems/binary-subarrays-with-sum/discuss/957414/Python3-hash-O(N) | 2 | Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.
A subarray is a contiguous part of the array.
Example 1:
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Explanation: The 4 subarrays are bolded and underlined below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
... | [Python3] hash O(N) | 167 | binary-subarrays-with-sum | 0.511 | ye15 | Medium | 15,073 | 930 |
minimum falling path sum | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
r=len(matrix)
c=len(matrix[0])
for i in range(1,r):
for j in range(c):
if j==0:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j+1])
... | https://leetcode.com/problems/minimum-falling-path-sum/discuss/1628101/Easy-and-Simple-Python-solution | 2 | Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row +... | Easy and Simple Python solution | 87 | minimum-falling-path-sum | 0.685 | diksha_choudhary | Medium | 15,084 | 931 |
beautiful array | class Solution:
def recurse(self, nums):
if len(nums) <= 2: return nums
return self.recurse(nums[::2]) + self.recurse(nums[1::2])
def beautifulArray(self, n: int) -> List[int]:
return self.recurse([i for i in range(1, n+1)]) | https://leetcode.com/problems/beautiful-array/discuss/1368125/Detailed-Explanation-with-Diagrams.-A-Collection-of-Ideas-from-Multiple-Posts.-Python3 | 45 | An array nums of length n is beautiful if:
nums is a permutation of the integers in the range [1, n].
For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j].
Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the giv... | Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3] | 1,500 | beautiful-array | 0.651 | chaudhary1337 | Medium | 15,133 | 932 |
shortest bridge | class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
i, j = next((i, j) for i in range(m) for j in range(n) if A[i][j])
# dfs
stack = [(i, j)]
seen = set(stack)
while stack:
i, j = stack.pop()
... | https://leetcode.com/problems/shortest-bridge/discuss/958926/Python3-DFS-and-BFS | 7 | You are given an n x n binary matrix grid where 1 represents land and 0 represents water.
An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.
You may change 0's to 1's to connect the two islands to form one island.
Return the smallest number of 0'... | [Python3] DFS & BFS | 512 | shortest-bridge | 0.54 | ye15 | Medium | 15,139 | 934 |
knight dialer | class Solution:
def knightDialer(self, n: int) -> int:
arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for _ in range(n-1):
dp = [0 for _ in range(10)]
dp[0] = arr[5] + arr[7]
dp[1] = arr[6] + arr[8]
dp[2] = arr[3] + arr[7]
dp[3] = a... | https://leetcode.com/problems/knight-dialer/discuss/1544986/Python-simple-dp-O(n)-time-O(1)-space | 3 | The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:
A chess knight can move as indicated in the chess diagram... | Python simple dp, O(n) time O(1) space | 493 | knight-dialer | 0.5 | byuns9334 | Medium | 15,150 | 935 |
stamping the sequence | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
N,M = len(target),len(stamp)
move = 0
maxmove = 10*N
ans = []
def check(string):
for i in range(M):
if string[i] == stamp[i] or string[i] == '?':
cont... | https://leetcode.com/problems/stamping-the-sequence/discuss/1888562/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SIMPLE-ITERATION-oror-EASIEST-YOU-WILL-FIND-EVER-!!-oror | 7 | You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.
In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.
For example, if stamp = "abc" and target = "abcba", then s is "?????" initially. In... | PYTHON SOL || WELL EXPLAINED || SIMPLE ITERATION || EASIEST YOU WILL FIND EVER !! || | 258 | stamping-the-sequence | 0.633 | reaper_27 | Hard | 15,162 | 936 |
reorder data in log files | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
l = []
d = []
for i in logs:
if i.split()[1].isdigit():
d.append(i)
else:
l.append(i)
l.sort(key = lambda x : x.split()[0])
l.sort(key = lambda x :... | https://leetcode.com/problems/reorder-data-in-log-files/discuss/1135934/Python3-simple-solution | 12 | You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
Letter-logs: All words (except the identifier) consist of lowercase English letters.
Digit-logs: All words (except the identifier) consist of digits.
Reorder these logs so ... | Python3 simple solution | 495 | reorder-data-in-log-files | 0.564 | EklavyaJoshi | Medium | 15,172 | 937 |
range sum of bst | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], lo: int, hi: int) -> int:
res = 0
q = deque([root])
while q:
c = q.popleft()
v, l, r = c.val, c.left, c.right
if lo <= v and v <= hi:
res += v
... | https://leetcode.com/problems/range-sum-of-bst/discuss/1627963/Python3-ITERATIVE-BFS-Explained | 3 | Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
E... | ✔️ [Python3] ITERATIVE BFS, Explained | 237 | range-sum-of-bst | 0.854 | artod | Easy | 15,196 | 938 |
minimum area rectangle | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
x_axis = defaultdict(dict)
y_axis = defaultdict(dict)
d = {}
points.sort()
ans = float('inf')
for point in points:
x_axis[point[0]][point[1]] = True
y_axis... | https://leetcode.com/problems/minimum-area-rectangle/discuss/1888886/PYTHON-SOLUTION-oror-PASSED-ALL-CASES-oror-WELL-EXPLAINED-oror-EASY-SOL-oror | 1 | You are given an array of points in the X-Y plane points where points[i] = [xi, yi].
Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.
Example 1:
Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4
Example 2:
I... | PYTHON SOLUTION || PASSED ALL CASES || WELL EXPLAINED || EASY SOL || | 489 | minimum-area-rectangle | 0.53 | reaper_27 | Medium | 15,226 | 939 |
distinct subsequences ii | class Solution:
def distinctSubseqII(self, s: str) -> int:
n = len(s)
MOD = 1000000007
dp = {}
def recursion(string,index):
ans = 1 if index > 0 else 0
used = {}
for idx in range(index,n):
if s[idx] in used:continue
... | https://leetcode.com/problems/distinct-subsequences-ii/discuss/1894186/PYTHON-SOL-oror-DP-oror-EXPLAINED-oror-FULL-APPROACH-EXPLAINED-oror-TLE-TO-OPTIMIZED-SOL-oror | 0 | Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the r... | PYTHON SOL || DP || EXPLAINED || FULL APPROACH EXPLAINED || TLE TO OPTIMIZED SOL || | 102 | distinct-subsequences-ii | 0.443 | reaper_27 | Hard | 15,230 | 940 |
valid mountain array | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if len(A)<3:return False
l=len(A)
i,j=0,l-1
while i<j and A[i]<A[i+1]:
i+=1
while j>0 and A[j]<A[j-1]:
j-=1
if i==j and j!=l-1 and i!=0:return True
return False | https://leetcode.com/problems/valid-mountain-array/discuss/338636/Python-solution-using-Two-pointer-from-opposite-sides | 10 | Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Example 1... | Python solution using Two pointer from opposite sides | 778 | valid-mountain-array | 0.335 | ketan35 | Easy | 15,234 | 941 |
di string match | class Solution:
def diStringMatch(self, s: str) -> List[int]:
ans = []
a , b = 0 , len(s)
for i in s:
if(i == 'I'):
ans.append(a)
a += 1
else:
ans.append(b)
b -= 1
if(s[-1] == 'D... | https://leetcode.com/problems/di-string-match/discuss/1199072/Python3-Simple-And-Readable-Solution | 7 | A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
s[i] == 'I' if perm[i] < perm[i + 1], and
s[i] == 'D' if perm[i] > perm[i + 1].
Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm... | [Python3] Simple And Readable Solution | 157 | di-string-match | 0.768 | VoidCupboard | Easy | 15,279 | 942 |
find the shortest superstring | class Solution:
def shortestSuperstring(self, words: List[str]) -> str:
n = len(words)
graph = [[0]*n for _ in range(n)] # graph as adjacency matrix
for i in range(n):
for j in range(n):
if i != j:
for k in range(len(words[j])):
... | https://leetcode.com/problems/find-the-shortest-superstring/discuss/1231147/Python3-travelling-sales-person-(TSP) | 1 | Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.
You may assume that no string in words is a substring of another string in words.
Example 1:
Input: words = ["alex","loves","le... | [Python3] travelling sales person (TSP) | 441 | find-the-shortest-superstring | 0.448 | ye15 | Hard | 15,303 | 943 |
delete columns to make sorted | class Solution:
def minDeletionSize(self, A: List[str]) -> int:
zipped=list(map(list,zip(*A)))
count=0
for item in zipped:
if item!=sorted(item):
count+=1
return count | https://leetcode.com/problems/delete-columns-to-make-sorted/discuss/427225/Python3-6-line-96ms-beats-99-easy-to-understand | 3 | You are given an array of n strings strs, all of the same length.
The strings can be arranged such that there is one on each line, making a grid.
For example, strs = ["abc", "bce", "cae"] can be arranged as follows:
abc
bce
cae
You want to delete the columns that are not sorted lexicographically. In the above example (... | Python3 6 line 96ms beats 99%, easy to understand | 244 | delete-columns-to-make-sorted | 0.696 | wangzi100 | Easy | 15,304 | 944 |
minimum increment to make array unique | class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
ans = 0
for i in range(1,n):
if nums[i] <= nums[i-1]:
# this is the case for making item unique
diff = nums[i-1] + 1 - nums[i]
... | https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1897470/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SORTING-ororGREEDYoror-APPROACH-EXPLAINED-oror-SIMPLE-oror-O(n*log(n))oror | 8 | You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: nums = [1,2,2]
Output: 1
E... | PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))|| | 271 | minimum-increment-to-make-array-unique | 0.504 | reaper_27 | Medium | 15,323 | 945 |
validate stack sequences | class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
for i in pushed:
stack.append(i)
while stack and popped and stack[-1] == popped[0]:
stack.pop()
popped.pop(0)
return not stack | https://leetcode.com/problems/validate-stack-sequences/discuss/1106110/Easy-python-solution-or-86-memory-86-time | 6 | Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the followin... | Easy python solution | 86% memory 86% time | 259 | validate-stack-sequences | 0.676 | vanigupta20024 | Medium | 15,333 | 946 |
most stones removed with same row or column | class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
def remove_point(a,b): # Function to remove connected points from the ongoing graph.
points.discard((a,b))
for y in x_dic[a]:
if (a,y) in points:
remove_point(a,y)
for x in y_dic[b]:
... | https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/1689443/For-Beginners-oror-Count-Number-of-Connected-Graphs-O(N)-oror-94-Faster | 22 | On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
Given an array stones of length n where stones[i] = [xi, yi] represents the locatio... | 📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍 | 1,500 | most-stones-removed-with-same-row-or-column | 0.588 | abhi9Rai | Medium | 15,374 | 947 |
bag of tokens | class Solution:
def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
score=0
tokens.sort()
i=0
j=len(tokens)-1
mx=0
while i<=j:
if tokens[i]<=power:
power-=tokens[i]
score+=1
i+=1
... | https://leetcode.com/problems/bag-of-tokens/discuss/2564480/Easy-python-solution-TC%3A-O(nlogn)-SC%3A-O(1) | 10 | You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of tokeni.
Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but... | Easy python solution TC: O(nlogn), SC: O(1) | 820 | bag-of-tokens | 0.521 | shubham_1307 | Medium | 15,407 | 948 |
largest time for given digits | class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
hh = mm = -1
for x in set(permutations(A, 4)):
h = 10*x[0] + x[1]
m = 10*x[2] + x[3]
if h < 24 and m < 60 and 60*h + m > 60*hh + mm: hh, mm = h, m
return f"{hh:02}:{mm:02}" if hh >= 0 e... | https://leetcode.com/problems/largest-time-for-given-digits/discuss/406661/Python3-6-line-via-permutation | 2 | Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
Return the latest 24-hour time in "HH:MM" format. ... | [Python3] 6-line via permutation | 124 | largest-time-for-given-digits | 0.352 | ye15 | Medium | 15,445 | 949 |
reveal cards in increasing order | class Solution:
def deckRevealedIncreasing(self, D: List[int]) -> List[int]:
L, Q, _ = len(D)-1, collections.deque(), D.sort()
for _ in range(L): Q.appendleft(D.pop()), Q.appendleft(Q.pop())
return D + list(Q)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/394028/Solution-in-Python-3-(Deque)-(three-lines) | 5 | You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
You will do the following steps repeatedly until all cards are rev... | Solution in Python 3 (Deque) (three lines) | 803 | reveal-cards-in-increasing-order | 0.778 | junaidmansuri | Medium | 15,455 | 950 |
flip equivalent binary trees | class Solution:
def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
if not root1 or not root2:
return not root1 and not root2
if root1.val != root2.val: return False
return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root... | https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/1985423/Python-oror-4-line-93 | 2 | For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
Given the roots of two binary trees root1 and root2, return tru... | Python || 4-line 93% | 69 | flip-equivalent-binary-trees | 0.668 | gulugulugulugulu | Medium | 15,461 | 951 |
largest component size by common factor | class Solution:
def largestComponentSize(self, nums: List[int]) -> int:
m = max(nums)
uf = UnionFind(m+1)
for x in nums:
for p in range(2, int(sqrt(x))+1):
if x%p == 0:
uf.union(x, p)
uf.union(x, x//p)
freq = Coun... | https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find | 4 | You are given an integer array of unique positive integers nums. Consider the following graph:
There are nums.length nodes, labeled nums[0] to nums[nums.length - 1],
There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.
Return the size of the largest connec... | [Python3] union-find | 259 | largest-component-size-by-common-factor | 0.404 | ye15 | Hard | 15,470 | 952 |
verifying an alien dictionary | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
hm = {ch: i for i, ch in enumerate(order)}
prev_repr = list(hm[ch] for ch in words[0])
for i in range(1, len(words)):
cur_repr = list(hm[ch] for ch in words[i])
if cur_repr < prev_repr:
... | https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1370816/Python3-fast-and-easy-to-understand-28-ms-faster-than-96.25 | 5 | In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorte... | Python3, fast and easy to understand, 28 ms, faster than 96.25% | 364 | verifying-an-alien-dictionary | 0.527 | MihailP | Easy | 15,473 | 953 |
array of doubled pairs | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
count = collections.Counter(arr)
for n in sorted(arr, key=abs):
if count[n] == 0:
continue
if count[n * 2] == 0:
return False
count[n] -= 1
count[n * 2... | https://leetcode.com/problems/array-of-doubled-pairs/discuss/1840844/python-3-oror-O(nlogn) | 1 | Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.
Example 1:
Input: arr = [3,1,3,6]
Output: false
Example 2:
Input: arr = [2,1,2,6]
Output: false
Example 3:
Input: arr = [4,-2,2,-4]
Out... | python 3 || O(nlogn) | 81 | array-of-doubled-pairs | 0.391 | dereky4 | Medium | 15,507 | 954 |
delete columns to make sorted ii | class Solution:
def minDeletionSize(self, A: List[str]) -> int:
m, n = len(A), len(A[0])
ans, in_order = 0, [False] * (m-1)
for j in range(n):
tmp_in_order = in_order[:]
for i in range(m-1):
# previous step, rows are not in order; and current step rows are not in ... | https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/844457/Python-3-or-Greedy-DP-(28-ms)-or-Explanation | 6 | You are given an array of n strings strs, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].
Suppose we c... | Python 3 | Greedy, DP (28 ms) | Explanation | 550 | delete-columns-to-make-sorted-ii | 0.346 | idontknoooo | Medium | 15,514 | 955 |
tallest billboard | class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
dp = {0: 0}
for x in rods:
for k, v in dp.copy().items():
dp[k+x] = max(dp.get(k+x, 0), v)
if k >= x: dp[k-x] = max(dp.get(k-x, 0), v+x)
else: dp[x-k] = max(dp.get(x-k, 0... | https://leetcode.com/problems/tallest-billboard/discuss/1561795/Python3-dp-and-binary-search | 0 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them togethe... | [Python3] dp & binary search | 273 | tallest-billboard | 0.399 | ye15 | Hard | 15,517 | 956 |
prison cells after n days | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
def nextday(cells):
next_day_cells = [0] *len(cells)
for i in range(1,len(cells)-1):
if cells[i-1] == cells[i+1]:
next_day_cells[i] = 1
else:
... | https://leetcode.com/problems/prison-cells-after-n-days/discuss/347500/Python3-Prison-Cells-After-N-days%3A-dictionary-to-store-pattern | 33 | There are 8 prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.
Note that bec... | [Python3] Prison Cells After N days: dictionary to store pattern | 3,800 | prison-cells-after-n-days | 0.391 | zhanweiting | Medium | 15,519 | 957 |
check completeness of a binary tree | class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
# The criteria for an n-level complete tree:
#
# • The first n-1 rows have no null nodes.
#
# • The nth row has no non-null no... | https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/2287813/Python3-oror-bfs-8-lines-w-explanation-oror-TM%3A-9797 | 3 | Given the root of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
Input: root = [1... | Python3 || bfs, 8 lines, w/ explanation || T/M: 97%/97% | 111 | check-completeness-of-a-binary-tree | 0.538 | warrenruud | Medium | 15,531 | 958 |
regions cut by slashes | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
def dfs(i: int, j: int) -> int:
if min(i, j) < 0 or max(i, j) >= len(g) or g[i][j] != 0:
return 0
g[i][j] = 1
return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)
... | https://leetcode.com/problems/regions-cut-by-slashes/discuss/205674/DFS-on-upscaled-grid | 733 | An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '. These characters divide the square into contiguous regions.
Given the grid grid represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\' is represented ... | DFS on upscaled grid | 23,400 | regions-cut-by-slashes | 0.691 | votrubac | Medium | 15,536 | 959 |
delete columns to make sorted iii | class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
m, n = len(strs), len(strs[0]) # dimensions
@cache
def fn(k, prev):
"""Return min deleted columns to make sorted."""
if k == n: return 0
ans = 1 + fn(k+1, prev) # delete kth colu... | https://leetcode.com/problems/delete-columns-to-make-sorted-iii/discuss/1258211/Python3-top-down-dp | 2 | You are given an array of n strings strs, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have strs = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"].
Suppose we c... | [Python3] top-down dp | 139 | delete-columns-to-make-sorted-iii | 0.571 | ye15 | Hard | 15,542 | 960 |
n repeated element in size 2n array | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
list1 = []
for i in nums :
if i in list1 :
return i
else :
list1.append(i) | https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER | 11 | You are given an integer array nums with the following properties:
nums.length == 2 * n.
nums contains n + 1 unique elements.
Exactly one element of nums is repeated n times.
Return the element that is repeated n times.
Example 1:
Input: nums = [1,2,3,3]
Output: 3
Example 2:
Input: nums = [2,1,2,5,3,2]
Output: 2
Exam... | PYTHON 3 : SUPER EASY 99.52% FASTER | 510 | n-repeated-element-in-size-2n-array | 0.759 | rohitkhairnar | Easy | 15,543 | 961 |
maximum width ramp | class Solution:
def maxWidthRamp(self, A: List[int]) -> int:
ans = 0
stack = []
for i in range(len(A)):
if not stack or A[stack[-1]] > A[i]: stack.append(i)
else:
lo, hi = 0, len(stack)
while lo < hi:
mid = lo + h... | https://leetcode.com/problems/maximum-width-ramp/discuss/977244/Python3-binary-search-O(NlogN)-and-stack-O(N) | 8 | A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.
Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.
Example 1:
Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ra... | [Python3] binary search O(NlogN) & stack O(N) | 299 | maximum-width-ramp | 0.49 | ye15 | Medium | 15,580 | 962 |
minimum area rectangle ii | class Solution:
def minAreaFreeRect(self, points: List[List[int]]) -> float:
ans = inf
seen = {}
for i, (x0, y0) in enumerate(points):
for x1, y1 in points[i+1:]:
cx = (x0 + x1)/2
cy = (y0 + y1)/2
d2 = (x0 - x1)**2 + (y0 - y1)**2
... | https://leetcode.com/problems/minimum-area-rectangle-ii/discuss/980956/Python3-center-point-O(N2) | 28 | You are given an array of points in the X-Y plane points where points[i] = [xi, yi].
Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0.
Answers within 10-5 of the actual answer will be accepted.
Exam... | [Python3] center point O(N^2) | 1,200 | minimum-area-rectangle-ii | 0.547 | ye15 | Medium | 15,584 | 963 |
least operators to express number | class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
@cache
def fn(val):
"""Return min ops to express val."""
if val < x: return min(2*val-1, 2*(x-val))
k = int(log(val)//log(x))
ans = k + fn(val - x**k)
if... | https://leetcode.com/problems/least-operators-to-express-number/discuss/1367268/Python3-top-down-dp | 4 | Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing such an ... | [Python3] top-down dp | 277 | least-operators-to-express-number | 0.48 | ye15 | Hard | 15,586 | 964 |
univalued binary tree | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
val = root.val
def helper(root):
return root is None or (root.val == val and helper(root.left) and helper(root.right))
return helper(root) | https://leetcode.com/problems/univalued-binary-tree/discuss/1569046/python-dfs-recursion-faster-than-97 | 2 | A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in ... | python dfs recursion faster than 97% | 89 | univalued-binary-tree | 0.693 | dereky4 | Easy | 15,588 | 965 |
vowel spellchecker | class Solution:
def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:
# Convert words and vowels to sets for O(1) lookup times
words = set(wordlist)
vowels = set('aeiouAEIOU')
# Create two maps.
# One for case insensitive word to al... | https://leetcode.com/problems/vowel-spellchecker/discuss/1121773/Python-One-Case-At-A-Time | 5 | Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
For a given query word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case ... | [Python] One Case At A Time | 288 | vowel-spellchecker | 0.514 | rowe1227 | Medium | 15,608 | 966 |
numbers with same consecutive differences | class Solution:
def numsSameConsecDiff(self, n: int, k: int) -> List[int]:
graph = defaultdict(list)
for i in range(0, 10):
if i-k >= 0:
graph[i].append(i-k)
if i +k < 10:
graph[i].append(i+k)
start = [i for i in graph if i!= 0]
for j in range(n-1):
new = set()
for i in start:
last = i%... | https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521416/44ms-PYTHON-91-Faster-93-Memory-Efficient-Solution-MULTIPLE-APPROACHES | 5 | Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order.
Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.
Example 1:
Input: n = 3, k = 7
Output: [181,... | 🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥 | 421 | numbers-with-same-consecutive-differences | 0.571 | anuvabtest | Medium | 15,618 | 967 |
binary tree cameras | class Solution:
def minCameraCover(self, root: TreeNode) -> int:
# set the value of camera nodes to 1
# set the value of monitored parent nodes to 2
def dfs(node: Optional[TreeNode]) -> int:
if not node:
return 0
res = dfs(node.left)+dfs(node.right)
... | https://leetcode.com/problems/binary-tree-cameras/discuss/2160386/Python-Making-a-Hard-Problem-Easy!-Postorder-Traversal-with-Explanation | 50 | You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: root = [0,0,null,0,0]
Output: 1
Explanation: One camera ... | [Python] Making a Hard Problem Easy! Postorder Traversal with Explanation | 2,100 | binary-tree-cameras | 0.468 | zayne-siew | Hard | 15,660 | 968 |
pancake sorting | class Solution:
def pancakeSort(self, arr: List[int]) -> List[int]:
if arr == sorted(arr):
return []
flips = []
end = len(arr) - 1
# find the max flip all the numbers from the first position to the max position
# ==> from 0 to max_position = k
... | https://leetcode.com/problems/pancake-sorting/discuss/2844744/Kind-of-a-simulation-solution | 0 | Given an array of integers arr, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
Choose an integer k where 1 <= k <= arr.length.
Reverse the sub-array arr[0...k-1] (0-indexed).
For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we revers... | Kind of a simulation solution | 1 | pancake-sorting | 0.7 | khaled_achech | Medium | 15,673 | 969 |
powerful integers | class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
bx = int(log(bound)/log(x)) if x > 1 else 0
by = int(log(bound)/log(y)) if y > 1 else 0
ans = set()
for i in range(bx+1):
for j in range(by+1):
if x**i + y**j <... | https://leetcode.com/problems/powerful-integers/discuss/1184254/Python3-brute-force | 2 | Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.
An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.
You may return the answer in any order. In your answer, each value should occur at most once.
... | [Python3] brute force | 45 | powerful-integers | 0.436 | ye15 | Medium | 15,684 | 970 |
flip binary tree to match preorder traversal | class Solution:
def __init__(self):
self.flipped_nodes = []
self.index = 0
def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
queue = deque([root])
while queue:
node = queue.pop()
if not node: continue
if node.v... | https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/1343381/Elegant-Python-Iterative-and-Recursive-Preorder-Traversals | 0 | You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, ... | Elegant Python Iterative & Recursive Preorder Traversals | 75 | flip-binary-tree-to-match-preorder-traversal | 0.499 | soma28 | Medium | 15,696 | 971 |
equal rational numbers | class Solution:
def isRationalEqual(self, S: str, T: str) -> bool:
L, A = [len(S), len(T)], [S,T]
for i,p in enumerate([S,T]):
if '(' in p:
I = p.index('(')
A[i] = p[0:I] + 7*p[I+1:L[i]-1]
return abs(float(A[0])-float(A[1])) < 1E-7
- Junaid M... | https://leetcode.com/problems/equal-rational-numbers/discuss/405505/Python-3-(beats-~99)-(six-lines) | 1 | Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPa... | Python 3 (beats ~99%) (six lines) | 119 | equal-rational-numbers | 0.43 | junaidmansuri | Hard | 15,702 | 972 |
k closest points to origin | class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
return sorted(points, key = lambda p: p[0]**2 + p[1]**2)[0:k] | https://leetcode.com/problems/k-closest-points-to-origin/discuss/1647325/Python3-ONE-LINER-Explained | 9 | Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is g... | ✔️ [Python3] ONE-LINER, Explained | 2,000 | k-closest-points-to-origin | 0.658 | artod | Medium | 15,707 | 973 |
subarray sums divisible by k | class Solution:
def subarraysDivByK(self, A: List[int], k: int) -> int:
dic = collections.defaultdict(int)
dic[0] = 1
ans = 0
presum = 0
for num in A:
presum += num
ans += dic[presum%k]
dic[presum%k] += 1
return ans
``` | https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1060120/Python3-O(N)-HashMap-and-Prefix-Sum | 9 | Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5,... | Python3 O(N) HashMap and Prefix Sum | 590 | subarray-sums-divisible-by-k | 0.536 | coffee90 | Medium | 15,747 | 974 |
odd even jump | class Solution:
def oddEvenJumps(self, A: List[int]) -> int:
# find next index of current index that is the least larger/smaller
def getNextIndex(sortedIdx):
stack = []
result = [None] * len(sortedIdx)
for i in sortedIdx:
while stack an... | https://leetcode.com/problems/odd-even-jump/discuss/1293059/Python-O(nlogn)-bottom-up-DP-easy-to-understand-260ms | 9 | You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.
You may jump forwa... | Python O(nlogn) bottom-up DP easy to understand 260ms | 966 | odd-even-jump | 0.389 | ScoutBoi | Hard | 15,767 | 975 |
largest perimeter triangle | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort(reverse = True)
for i in range(3,len(A)+1):
if(A[i-3] < A[i-2] + A[i-1]):
return sum(A[i-3:i])
return 0 | https://leetcode.com/problems/largest-perimeter-triangle/discuss/915905/Python-3-98-better-explained-with-simple-logic | 14 | Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.
Example 1:
Input: nums = [2,1,2]
Output: 5
Explanation: You can form a triangle with three side lengths: 1, 2, and 2.... | Python 3, 98% better, explained with simple logic | 2,300 | largest-perimeter-triangle | 0.544 | apurva_101 | Easy | 15,769 | 976 |
squares of a sorted array | class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
return_array = [0] * len(A)
write_pointer = len(A) - 1
left_read_pointer = 0
right_read_pointer = len(A) - 1
left_square = A[left_read_pointer] ** 2
right_square = A[right_read_pointer] ** 2
w... | https://leetcode.com/problems/squares-of-a-sorted-array/discuss/310865/Python%3A-A-comparison-of-lots-of-approaches!-Sorting-two-pointers-deque-iterator-generator | 386 | Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
I... | Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator] | 20,500 | squares-of-a-sorted-array | 0.719 | Hai_dee | Easy | 15,822 | 977 |
longest turbulent subarray | class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
cur, mx, t = 1, 1, None
for i in range(1, len(arr)):
# Start of subarray
if t == None:
if arr[i] != arr[i-1]:
cur = 2
t = arr[i] > arr[i-1]
... | https://leetcode.com/problems/longest-turbulent-subarray/discuss/1464950/Python3-Longest-Turbulent-Subarray-O(n)-(one-pass) | 2 | Given an integer array arr, return the length of a maximum size turbulent subarray of arr.
A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:
For i <= k < ... | ✅ [Python3] Longest Turbulent Subarray O(n) (one pass) | 207 | longest-turbulent-subarray | 0.474 | vscala | Medium | 15,877 | 978 |
distribute coins in binary tree | class Solution:
def distributeCoins(self, v: Optional[TreeNode], parent=None) -> int:
if v is None:
return 0
m = self.distributeCoins(v.left, v) + self.distributeCoins(v.right, v)
if v.val != 1:
parent.val += v.val - 1
m += abs(v.val - 1)
return m | https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/2797049/Very-short-concise-Python-solution-with-DFS | 0 | You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return the min... | Very short, concise Python solution with DFS | 4 | distribute-coins-in-binary-tree | 0.721 | metaphysicalist | Medium | 15,891 | 979 |
unique paths iii | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
# first, prepare the starting and ending points
# simultaneously, record all the non-obstacle coordinates
start = end = None
visit = set()
for i in range(len(grid)):
for j in range(len(grid[0])):
... | https://leetcode.com/problems/unique-paths-iii/discuss/1535158/Python-Backtracking%3A-Easy-to-understand-with-Explanation | 74 | You are given an m x n integer array grid where grid[i][j] could be:
1 representing the starting square. There is exactly one starting square.
2 representing the ending square. There is exactly one ending square.
0 representing empty squares we can walk over.
-1 representing obstacles that we cannot walk over.
Return t... | Python Backtracking: Easy-to-understand with Explanation | 3,500 | unique-paths-iii | 0.797 | zayne-siew | Hard | 15,895 | 980 |
triples with bitwise and equal to zero | class Solution:
def countTriplets(self, nums: List[int]) -> int:
freq = defaultdict(int)
for x in nums:
for y in nums:
freq[x&y] += 1
ans = 0
for x in nums:
mask = x = x ^ 0xffff
while x:
ans += freq... | https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/1257470/Python3-hash-table | 4 | Given an integer array nums, return the number of AND triples.
An AND triple is a triple of indices (i, j, k) such that:
0 <= i < nums.length
0 <= j < nums.length
0 <= k < nums.length
nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.
Example 1:
Input: nums = [2,1,3]
Output: 12
Explanation... | [Python3] hash table | 222 | triples-with-bitwise-and-equal-to-zero | 0.577 | ye15 | Hard | 15,925 | 982 |
minimum cost for tickets | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
#create the total costs for the days
costForDays = [0 for _ in range(days[-1] + 1) ]
#since days are sorted in ascending order, we only need the index of the days we haven't visited yet
curIdx = 0
for... | https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1219272/Python-O(N)-Runtime-O(N)-with-explanation | 3 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.
Train tickets are sold in three different ways:
a 1-day pass is sold for costs[0] dollars,
a 7-day pass is sold for costs[1] dollars, and
a 3... | Python O(N) Runtime O(N) with explanation | 244 | minimum-cost-for-tickets | 0.644 | sherlockieee | Medium | 15,928 | 983 |
string without aaa or bbb | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
res = []
while a + b > 0:
if len(res) >= 2 and res[-2:] == ['a', 'a']:
res.append('b')
b-=1
elif len(res) >= 2 and res[-2:] == ['b', 'b']:
res.append('a')
... | https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1729883/Python-beats-91 | 1 | Given two integers a and b, return any string s such that:
s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,
The substring 'aaa' does not occur in s, and
The substring 'bbb' does not occur in s.
Example 1:
Input: a = 1, b = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all co... | Python beats 91% | 104 | string-without-aaa-or-bbb | 0.43 | leopardcoderd | Medium | 15,944 | 984 |
sum of even numbers after queries | class Solution:
# the idea is we don't calculate the even sum from scratch for each query
# instead, we calculate it at the beginning
# since each query only updates one value,
# so we can adjust the even sum base on the original value and new value
def sumEvenAfterQueries(self, nums: List[int], qu... | https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603372/LeetCode-The-Hard-Way-Explained-Line-By-Line | 58 | You are given an integer array nums and an array queries where queries[i] = [vali, indexi].
For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.
Return an integer array answer where answer[i] is the answer to the ith query.
Example 1:
Input: nums = [1,2,3,4... | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 3,200 | sum-of-even-numbers-after-queries | 0.682 | wingkwong | Medium | 15,949 | 985 |
interval list intersections | class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
idx_a, idx_b = 0, 0
size_a, size_b = len(A), len(B)
intersection = []
# Scan each possible interval pair
while idx_a < size_a and idx_b < size... | https://leetcode.com/problems/interval-list-intersections/discuss/646939/Python-O(m%2Bn)-by-two-pointers.w-Graph | 3 | You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
A closed interval [a, b] (with a <= b) denotes the set of r... | Python O(m+n) by two-pointers.[w/ Graph] | 264 | interval-list-intersections | 0.714 | brianchiang_tw | Medium | 15,997 | 986 |
vertical order traversal of a binary tree | class Solution:
def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
results = defaultdict(list)
queue = [ (root, 0, 0) ]
while queue:
node, pos, depth = queue.pop(0)
if not node: continue
results[(pos,depth)].append(... | https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2526928/Python-BFS-%2B-Hashmap | 13 | Given the root of a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).
The vertical order traversal of a binary tree is a... | Python BFS + Hashmap | 1,700 | vertical-order-traversal-of-a-binary-tree | 0.447 | complete_noob | Hard | 16,025 | 987 |
smallest string starting from leaf | class Solution:
res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13
def smallestFromLeaf(self, root: TreeNode) -> str:
def helper(node: TreeNode, prev):
prev = chr(97 + node.val) + prev
if not node.left and not node.right:
... | https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/422855/Python-readable.-44ms-99.7-14MB-100 | 3 | You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.
Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.
As a reminder, any shorter prefix of a string is lexicographically smaller.
For example, "ab... | Python readable. 44ms 99.7% 14MB 100% | 331 | smallest-string-starting-from-leaf | 0.497 | lsy7905 | Medium | 16,051 | 988 |
add to array form of integer | class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
return list(str(int("".join([str(x) for x in num])) + k)) | https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2037608/Python3-or-One-line-solution | 2 | The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1].
Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.
Example 1:
Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Ex... | Python3 | One line solution | 186 | add-to-array-form-of-integer | 0.455 | manfrommoon | Easy | 16,063 | 989 |
satisfiability of equality equations | class Solution: # Here's the plan:
# 1) We make an undirected graph in which the nodes are integers
# (as lower-case letters) and each edge connects integers
# that are equal.
# 2) We use a union-find process to determine ... | https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2624938/python3-oror-13-lines-sets-oror-1-TM%3A-8967 | 26 | You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true if i... | python3 || 13 lines, sets || 1 T/M: 89%/67% | 1,800 | satisfiability-of-equality-equations | 0.508 | warrenruud | Medium | 16,109 | 990 |
broken calculator | class Solution:
def brokenCalc(self, x: int, y: int) -> int:
if y<=x:
return x-y
else:
res=0
while x<y:
if y%2==1:
y+=1
else:
y=y//2
res+=1
res+=(x-y)
r... | https://leetcode.com/problems/broken-calculator/discuss/1033822/Easy-and-Clear-Solution-Python-3 | 2 | There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:
multiply the number on display by 2, or
subtract 1 from the number on display.
Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.
... | Easy & Clear Solution Python 3 | 182 | broken-calculator | 0.541 | moazmar | Medium | 16,127 | 991 |
subarrays with k different integers | class Solution:
def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
def window(nums, k):
left = 0
right = 0
res = 0
in_set = set()
hash_map = collections.Counter()
while right < len(nums):
in_set... | https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1215277/Python-Sliding-Window-or-Set-%2B-HashMap | 5 | Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good array is an array where the number of different integers in that array is exactly k.
For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [... | [Python] Sliding Window | Set + HashMap | 813 | subarrays-with-k-different-integers | 0.545 | Sai-Adarsh | Hard | 16,146 | 992 |
cousins in binary tree | class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
# Check if root node is x or y
if root.val == x or root.val == y:
return False
# Prepare for BFS, initialise variables
curr, flag = [root.left, root.right], False
while curr:
... | https://leetcode.com/problems/cousins-in-binary-tree/discuss/1527334/Python-BFS%3A-Easy-to-understand-solution-w-Explanation | 8 | Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
Note that in ... | Python BFS: Easy-to-understand solution w Explanation | 423 | cousins-in-binary-tree | 0.542 | zayne-siew | Easy | 16,153 | 993 |
rotting oranges | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
visit, curr = set(), deque()
# find all fresh and rotten oranges
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
visit.add((i, j))
el... | https://leetcode.com/problems/rotting-oranges/discuss/1546489/Python-BFS%3A-Easy-to-understand-with-Explanation | 59 | You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return the minimum number of minutes that must elap... | Python BFS: Easy-to-understand with Explanation | 3,900 | rotting-oranges | 0.525 | zayne-siew | Medium | 16,179 | 994 |
minimum number of k consecutive bit flips | class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
ans = 0
q = []
for i in range(len(nums)):
if len(q) % 2 == 0:
if nums[i] == 0:
if i+k-1 <= len(nums)-1:
ans += 1
q.append(i+... | https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/discuss/2122927/Python-O(N)-S(N)-Queue-solution | 0 | You are given a binary array nums and an integer k.
A k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1... | Python O(N) S(N) Queue solution | 64 | minimum-number-of-k-consecutive-bit-flips | 0.512 | DietCoke777 | Hard | 16,219 | 995 |
number of squareful arrays | class Solution(object):
def numSquarefulPerms(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def dfs(temp,num,count = 0):
if len(num)==0:
return count+1
for i in xrange(len(num)):
if (i>0 and num[i]==num[i-1]) or... | https://leetcode.com/problems/number-of-squareful-arrays/discuss/1375586/python-simple-backtracking.-20ms | 1 | An array is squareful if the sum of every pair of adjacent elements is a perfect square.
Given an integer array nums, return the number of permutations of nums that are squareful.
Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].
Example 1:
Input: nums = [1,17,8]
... | python simple backtracking. 20ms | 305 | number-of-squareful-arrays | 0.492 | leah123 | Hard | 16,221 | 996 |
find the town judge | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
Trusted = [0] * (N+1)
for (a, b) in trust:
Trusted[a] -= 1
Trusted[b] += 1
for i in range(1, len(Trusted)):
if Trusted[i] == N-1:
return i
retu... | https://leetcode.com/problems/find-the-town-judge/discuss/1663344/C%2B%2BJavaPython3Javascript-Everything-you-need-to-know-from-start-to-end-. | 144 | In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given... | [C++/Java/Python3/Javascript] Everything you need to know from start to end . | 9,500 | find-the-town-judge | 0.493 | Cosmic_Phantom | Easy | 16,228 | 997 |
maximum binary tree ii | class Solution:
def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
if val > root.val: return TreeNode(val, root)
root.right = self.insertIntoMaxTree(root.right, val)
return root | https://leetcode.com/problems/maximum-binary-tree-ii/discuss/2709985/Python-short-python-solution | 0 | A maximum tree is a tree where every node has a value greater than any other value in its subtree.
You are given the root of a maximum binary tree and an integer val.
Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:
... | [Python] short python solution | 6 | maximum-binary-tree-ii | 0.665 | scrptgeek | Medium | 16,266 | 998 |
available captures for rook | class Solution:
def numRookCaptures(self, b: List[List[str]]) -> int:
I, J = divmod(sum(b,[]).index('R'),8)
C = "".join([i for i in [b[I]+['B']+[b[i][J] for i in range(8)]][0] if i != '.'])
return C.count('Rp') + C.count('pR')
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/available-captures-for-rook/discuss/356593/Solution-in-Python-3-(beats-~97)-(three-lines) | 8 | On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, c... | Solution in Python 3 (beats ~97%) (three lines) | 839 | available-captures-for-rook | 0.679 | junaidmansuri | Easy | 16,270 | 999 |
minimum cost to merge stones | class Solution:
def mergeStones(self, stones: List[int], k: int) -> int:
if (len(stones)-1) % (k-1): return -1 # impossible
prefix = [0]
for x in stones: prefix.append(prefix[-1] + x)
@cache
def fn(lo, hi):
"""Return min cost of merging stones[l... | https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/1465680/Python3-dp | 1 | There are n piles of stones arranged in a row. The ith pile has stones[i] stones.
A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.
Return the minimum cost to merge all piles of stones into one pile. If it is impossib... | [Python3] dp | 654 | minimum-cost-to-merge-stones | 0.423 | ye15 | Hard | 16,291 | 1,000 |
grid illumination | class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
lamps = {(r, c) for r, c in lamps}
row, col, left, right = dict(), dict(), dict(), dict()
for r, c in lamps:
row[r] = row.get(r, 0) + 1
col[c] =... | https://leetcode.com/problems/grid-illumination/discuss/1233528/Python-or-HashMap-or-O(L%2BQ)-or-928ms | 2 | There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.
You are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.
When a lamp is... | Python | HashMap | O(L+Q) | 928ms | 103 | grid-illumination | 0.362 | PuneethaPai | Hard | 16,294 | 1,001 |
find common characters | class Solution:
def commonChars(self, A: List[str]) -> List[str]:
alphabet = string.ascii_lowercase
d = {c: 0 for c in alphabet}
for k, v in d.items():
d[k] = min([word.count(k) for word in A])
res = []
for c, n in d.items():
if n > 0:
... | https://leetcode.com/problems/find-common-characters/discuss/721548/Python-Faster-than-77.67-and-Better-Space-than-86.74 | 8 | Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
Example 1:
Input: words = ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: words = ["cool","lock","cook"]
Output: ["c","o"]
Con... | Python Faster than 77.67% and Better Space than 86.74 | 997 | find-common-characters | 0.683 | parkershamblin | Easy | 16,301 | 1,002 |
check if word is valid after substitutions | class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for i in s:
if i == 'a':stack.append(i)
elif i=='b':
if not stack:return False
else:
if stack[-1]=='a':stack.pop()
else:return False
... | https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1291378/python-solution-using-stack | 2 | Given a string s, determine if it is valid.
A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:
Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note ... | python solution using stack | 94 | check-if-word-is-valid-after-substitutions | 0.582 | chikushen99 | Medium | 16,339 | 1,003 |
max consecutive ones iii | class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = 0
answer = 0
counts = {0: 0, 1: 0}
for right, num in enumerate(nums):
counts[num] += 1
while counts[0] > k:
counts[nums[left]] -= 1
... | https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1793625/Python-3-Very-typical-sliding-window-%2B-hashmap-problem. | 5 | Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Examp... | [Python 3] Very typical sliding window + hashmap problem. | 152 | max-consecutive-ones-iii | 0.634 | seankala | Medium | 16,356 | 1,004 |
maximize sum of array after k negations | class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort()
i = 0
while i < len(A) and K>0:
if A[i] < 0: # negative value
A[i] = A[i] * -1 # update the list, change negative to positive
K-=1
elif A[i] > 0: # positive value
if K % 2 == 0: # let K==2(must be even v... | https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1120243/WEEB-EXPLAINS-PYTHON-SOLUTION | 6 | Given an integer array nums and an integer k, modify the array in the following way:
choose an index i and replace nums[i] with -nums[i].
You should apply this process exactly k times. You may choose the same index i multiple times.
Return the largest possible sum of the array after modifying it in this way.
Example ... | WEEB EXPLAINS PYTHON SOLUTION | 361 | maximize-sum-of-array-after-k-negations | 0.51 | Skywalker5423 | Easy | 16,397 | 1,005 |
clumsy factorial | class Solution:
def clumsy(self, N: int) -> int:
return N + ([1,2,2,-1][N % 4] if N > 4 else [0,0,0,3,3][N]) | https://leetcode.com/problems/clumsy-factorial/discuss/395085/Three-Solutions-in-Python-3-(beats-~99)-(one-line) | 3 | The factorial of a positive integer n is the product of all positive integers less than or equal to n.
For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with mu... | Three Solutions in Python 3 (beats ~99%) (one line) | 525 | clumsy-factorial | 0.55 | junaidmansuri | Medium | 16,424 | 1,006 |
minimum domino rotations for equal row | class Solution:
def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:
total = len(tops)
top_fr, bot_fr, val_total = [0]*7, [0]*7, [total]*7
for top, bot in zip(tops, bottoms):
if top == bot:
val_total[top] -= 1
else:
... | https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865333/Python3-UNPRECENDENT-NUMBER-OF-COUNTERS-o()o-Explained | 23 | In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.
Return the minimum number of rotations so that all the values in... | ✔️[Python3] UNPRECENDENT NUMBER OF COUNTERS o͡͡͡͡͡͡͡͡͡͡͡͡͡͡╮(。❛ᴗ❛。)╭o͡͡͡͡͡͡͡͡͡͡͡͡͡͡, Explained | 1,100 | minimum-domino-rotations-for-equal-row | 0.524 | artod | Medium | 16,432 | 1,007 |
construct binary search tree from preorder traversal | class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
node_stack = []
node = root = TreeNode(preorder[0])
for n in preorder[1:]:
if n <= node.val:
node.left = TreeNode(n)
node_stack.append(node)
node = node.lef... | https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/649369/Python.-No-recursion. | 4 | Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
A binary search tree is a binary tre... | Python. No recursion. | 464 | construct-binary-search-tree-from-preorder-traversal | 0.809 | techrabbit58 | Medium | 16,451 | 1,008 |
complement of base 10 integer | class Solution:
def bitwiseComplement(self, n: int) -> int:
if n == 0:
return 1
else:
result = 0
factor = 1
while(n > 0):
result += factor * (1 if n%2 == 0 else 0)
factor *= 2
n //= 2
... | https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666811/Python-Simple-Solution-with-Detail-Explanation-%3A-O(log-n) | 2 | The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.
Example 1:
Input: n = 5
Output: 2
Expla... | Python Simple Solution with Detail Explanation : O(log n) | 314 | complement-of-base-10-integer | 0.619 | yashitanamdeo | Easy | 16,476 | 1,009 |
pairs of songs with total durations divisible by 60 | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
res , count = 0, [0] * 60
for one in range(len(time)):
index = time[one] % 60
res += count[(60 - index)%60] # %60 is for index==0
count[index] += 1
return res | https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/422213/Python-O(n)-6-Lines-beats-86-time | 26 | You are given a list of songs where the ith song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.
Example 1:
Input: time = [30,20,150,100... | Python O(n) 6 Lines beats 86% time | 1,900 | pairs-of-songs-with-total-durations-divisible-by-60 | 0.529 | macqueen | Medium | 16,510 | 1,010 |
capacity to ship packages within d days | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
def feasible(capacity):
days = 1
local = 0
for w in weights:
local+=w
if local>capacity:
local = w
days+=1
if days>D:
... | https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1581292/Well-Explained-oror-Thought-process-oror-94-faster | 31 | A conveyor belt has packages that must be shipped from one port to another within days days.
The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the... | 📌📌 Well-Explained || Thought process || 94% faster 🐍 | 1,900 | capacity-to-ship-packages-within-d-days | 0.646 | abhi9Rai | Medium | 16,543 | 1,011 |
numbers with repeated digits | class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
T = [9,261,4725,67509,831429,9287109,97654149,994388229]
t = [99,999,9999,99999,999999,9999999,99999999,999999999]
if N < 10:
return 0
L = len(str(N))
m, n = [1], []
g = 11-L
for i in range(L):
n.append(int(... | https://leetcode.com/problems/numbers-with-repeated-digits/discuss/332462/Solution-in-Python-3-(beats-~99) | 2 | Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.
Example 1:
Input: n = 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: n = 100
Output: 10
Explanation: The positive numbers (<= 100) w... | Solution in Python 3 (beats ~99%) | 962 | numbers-with-repeated-digits | 0.406 | junaidmansuri | Hard | 16,569 | 1,012 |
partition array into three parts with equal sum | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
S = sum(A)
if S % 3 != 0: return False
g, C, p = S//3, 0, 0
for a in A[:-1]:
C += a
if C == g:
if p == 1: return True
C, p = 0, 1
return False | https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/352417/Solution-in-Python-3-(beats-~99)-(With-Detailed-Explanation)-(-O(n)-time-)-(-O(1)-space-) | 22 | Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1... | Solution in Python 3 (beats ~99%) (With Detailed Explanation) ( O(n) time ) ( O(1) space ) | 1,600 | partition-array-into-three-parts-with-equal-sum | 0.432 | junaidmansuri | Easy | 16,570 | 1,013 |
best sightseeing pair | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
dp = [0]*(len(values))
dp[0] = values[0]
maxVal = 0
for i in range(1, len(values)):
dp[i] = max(dp[i-1], values[i-1]+i-1)
maxVal = max(maxVal, dp[i]+values[i]-i)
return maxV... | https://leetcode.com/problems/best-sightseeing-pair/discuss/1521786/oror-Very-easy-explanation-oror-DP-oror-Complexity-Analysis-oror-Python | 34 | You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance ... | ✅ || Very easy explanation || DP || Complexity Analysis || Python | 1,100 | best-sightseeing-pair | 0.595 | siddp6 | Medium | 16,586 | 1,014 |
smallest integer divisible by k | class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
if not k % 2 or not k % 5: return -1
n = length = 1
while True:
if not n % k: return length
length += 1
n = 10*n + 1 | https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1655649/Python3-Less-Math-More-Intuition-or-2-Accepted-Solutions-or-Intuitive | 26 | Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.
Return the length of n. If there is no such n, return -1.
Note: n may not fit in a 64-bit signed integer.
Example 1:
Input: k = 1
Output: 1
Explanation: The smalle... | [Python3] ✔️ Less Math, More Intuition ✔️ | 2 Accepted Solutions | Intuitive | 1,900 | smallest-integer-divisible-by-k | 0.47 | PatrickOweijane | Medium | 16,616 | 1,015 |
binary string with substrings representing 1 to n | class Solution:
def queryString(self, S: str, N: int) -> bool:
for x in range(N, 0, -1):
if bin(x)[2:] not in S: return False
return True | https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1106296/Python3-2-approaches | 6 | Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "0110", n = 3
Output: true
Example 2:
Input: s = "0110",... | [Python3] 2 approaches | 387 | binary-string-with-substrings-representing-1-to-n | 0.575 | ye15 | Medium | 16,623 | 1,016 |
convert to base 2 | class Solution:
def baseNeg2(self, n: int) -> str:
ans = ""
while n != 0:
if n%-2 != 0 :
ans = '1' + ans
n = (n-1)//-2
else:
ans = '0' + ans
n = n//-2
return ans if ans !="" else '0' | https://leetcode.com/problems/convert-to-base-2/discuss/2007392/PYTHON-SOL-oror-EASY-oror-BINARY-CONVERSION-oror-WELL-EXPLAINED-oror | 1 | Given an integer n, return a binary string representing its representation in base -2.
Note that the returned string should not have leading zeros unless the string is "0".
Example 1:
Input: n = 2
Output: "110"
Explantion: (-2)2 + (-2)1 = 2
Example 2:
Input: n = 3
Output: "111"
Explantion: (-2)2 + (-2)1 + (-2)0 = 3
E... | PYTHON SOL || EASY || BINARY CONVERSION || WELL EXPLAINED || | 172 | convert-to-base-2 | 0.61 | reaper_27 | Medium | 16,630 | 1,017 |
binary prefix divisible by 5 | class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
n = 0
for i in range(len(A)): A[i], n = (2*n + A[i]) % 5 == 0, (2*n + A[i]) % 5
return A
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/356289/Solution-in-Python-3-(beats-~98)-(three-lines)-(-O(1)-space-) | 4 | You are given a binary array nums (0-indexed).
We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).
For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.
Return an array of booleans answer where answer[i] is true if xi is divi... | Solution in Python 3 (beats ~98%) (three lines) ( O(1) space ) | 349 | binary-prefix-divisible-by-5 | 0.473 | junaidmansuri | Easy | 16,634 | 1,018 |
next greater node in linked list | class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
result = []
stack = []
for i, current in enumerate(self.value_iterator(head)):
result.append(0)
while stack and stack[-1][0] < current:
_, index = stack.pop()
resul... | https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/283607/Clean-Python-Code | 3 | You are given the head of a linked list with n nodes.
For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.
Return an integer array answer where answer[i] is the value of the next greater n... | Clean Python Code | 817 | next-greater-node-in-linked-list | 0.599 | aquafie | Medium | 16,644 | 1,019 |
number of enclaves | class Solution:
def numEnclaves(self, A: List[List[int]]) -> int:
row, col = len(A), len(A[0])
if not A or not A[0]:
return 0
boundary1 = deque([(i,0) for i in range(row) if A[i][0]==1]) + deque([(i,col-1) for i in range(row) if A[i][col-1]==1])
boundary2 = deque([(0,i) for i in range(... | https://leetcode.com/problems/number-of-enclaves/discuss/1040282/Python-BFS-and-DFS-by-yours-truly | 14 | You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.
Return the number of land cells in grid for which we cannot walk off the boundary ... | Python BFS and DFS by yours truly | 1,100 | number-of-enclaves | 0.65 | Skywalker5423 | Medium | 16,664 | 1,020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.