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_sum + number, number )
global_min_sum = min( global_min_sum, local_min_sum )
local_max_sum = max( local_max_sum + number, number )
global_max_sum = max( global_max_sum, local_max_sum )
array_sum += number
# global_max_sum denotes the maximum subarray sum without crossing boundary
# arry_sum - global_min_sum denotes the maximum subarray sum with crossing boundary
if global_max_sum > 0:
return max( array_sum - global_min_sum, global_max_sum )
else:
# corner case handle for all number are negative
return global_max_sum | 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 subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.
Example 1:
Input: nums = [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3.
Example 2:
Input: nums = [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.
Example 3:
Input: nums = [-3,-2,-3]
Output: -2
Explanation: Subarray [-2] has maximum sum -2.
Constraints:
n == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104 | 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) * fn(i+1, x+1) # a new song
if k < x: ans += (x-k) * fn(i+1, x) # an old song
return ans % 1_000_000_007
return fn(0, 0) | 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 number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: n = 3, goal = 3, k = 1
Output: 6
Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].
Example 2:
Input: n = 2, goal = 3, k = 0
Output: 6
Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].
Example 3:
Input: n = 2, goal = 3, k = 1
Output: 2
Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].
Constraints:
0 <= k < n <= goal <= 100 | [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
if(y < 0):
count += 1
y = 0
return count + x + y | 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.
For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))".
Return the minimum number of moves required to make s valid.
Example 1:
Input: s = "())"
Output: 1
Example 2:
Input: s = "((("
Output: 3
Constraints:
1 <= s.length <= 1000
s[i] is either '(' or ')'. | [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:
nums[i]=odd[o]
o+=1
return nums | 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: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Example 2:
Input: nums = [2,3]
Output: [2,3]
Constraints:
2 <= nums.length <= 2 * 104
nums.length is even.
Half of the integers in nums are even.
0 <= nums[i] <= 1000
Follow Up: Could you solve it in-place? | 📌📌 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 (arr[i], arr[j], arr[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.
Example 2:
Input: arr = [1,1,2,2,2,2], target = 5
Output: 12
Explanation:
arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.
Example 3:
Input: arr = [2,1,3], target = 6
Output: 1
Explanation: (1, 2, 3) occured one time in the array so we return 1.
Constraints:
3 <= arr.length <= 3000
0 <= arr[i] <= 100
0 <= target <= 300 | [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)
maxRemoval, minNode = -1, float('inf')
for node in initial:
nodes = set()
dfs(node)
if nodes & initial == {node}:
l = len(nodes)
if l > maxRemoval or (l == maxRemoval and node < minNode):
minNode = node
maxRemoval = l
return minNode if maxRemoval > -1 else min(initial) | 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, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.
Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1
Constraints:
n == graph.length
n == graph[i].length
2 <= n <= 300
graph[i][j] is 0 or 1.
graph[i][j] == graph[j][i]
graph[i][i] == 1
1 <= initial.length <= n
0 <= initial[i] <= n - 1
All the integers in initial are unique. | 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
elif typed[ti] == name[ni-1] and ni != 0:
ti += 1
else:
return False
return ni == len(name) and ti == len(typed) | 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 long pressed.
Example 1:
Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it was not in the typed output.
Constraints:
1 <= name.length, typed.length <= 1000
name and typed consist of only lowercase English letters. | [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
flipCount: 0 0 1 1 2
0 0 0 1 1 0 0 0
oneCount: 0 0 0 1 2 2 2 2
zeroCount: 1 1 1 0 0 1 2 3
flipCount: 0 0 0 0 0 1 2 2
"""
oneCount = 0
zeroCount = 0
flipCount = 0
for c in s:
if c == "1":
oneCount += 1
if c == "0":
zeroCount += 1
flipCount = min(zeroCount,oneCount)
zeroCount = flipCount
return flipCount | 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:
Input: s = "00110"
Output: 1
Explanation: We flip the last digit to get 00111.
Example 2:
Input: s = "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.
Example 3:
Input: s = "00011000"
Output: 2
Explanation: We flip to get 00000000.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'. | [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 ones
c = 0
starts = []
for i, d in enumerate(arr):
if d == 1:
if c % (ones // 3) == 0:
starts.append(i)
c += 1
# scan the groups in parallel to compare digits
i, j, k = starts
while k < len(arr): # note that the last/rightmost group must include all digits till the end
if arr[i] == arr[j] == arr[k]:
i += 1
j += 1
k += 1
else:
return [-1, -1]
return [i-1, j] | 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 - 1] is the second part, and
arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
All three parts have equal binary values.
If it is not possible, return [-1, -1].
Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.
Example 1:
Input: arr = [1,0,1,0,1]
Output: [0,3]
Example 2:
Input: arr = [1,1,0,1,1]
Output: [-1,-1]
Example 3:
Input: arr = [1,1,0,0,1]
Output: [0,2]
Constraints:
3 <= arr.length <= 3 * 104
arr[i] is 0 or 1 | 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 graph. Note if two deleted
# values give same count of connected graph, then we choose
# smaller value. that's why I used a tuple, (BFS(a), a) this
# will first compare BFS(a), if they are equal then it compares
# a.
def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:
def BFS(delval):
seen, lst = set(), list(initial)
while lst:
node = lst.pop()
if node == delval or node in seen: continue
seen.add(node)
lst += [i for i, val in enumerate(graph[node]) if val]
return len(seen)
return min(initial, key=lambda a: (BFS(a), a)) | 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, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.
Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Example 2:
Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1
Example 3:
Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1
Constraints:
n == graph.length
n == graph[i].length
2 <= n <= 300
graph[i][j] is 0 or 1.
graph[i][j] == graph[j][i]
graph[i][i] == 1
1 <= initial.length < n
0 <= initial[i] <= n - 1
All the integers in initial are unique. | 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 local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.
For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.
If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.
For example, "m.y+name@email.com" will be forwarded to "my@email.com".
It is possible to use both of these rules at the same time.
Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.
Example 1:
Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.
Example 2:
Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]
Output: 3
Constraints:
1 <= emails.length <= 100
1 <= emails[i].length <= 100
emails[i] consist of lowercase English letters, '+', '.' and '@'.
Each emails[i] contains exactly one '@' character.
All local and domain names are non-empty.
Local names do not start with a '+' character.
Domain names end with the ".com" suffix. | 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]
Example 2:
Input: nums = [0,0,0,0,0], goal = 0
Output: 15
Constraints:
1 <= nums.length <= 3 * 104
nums[i] is either 0 or 1.
0 <= goal <= nums.length | [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])
elif j==c-1:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1])
else:
matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1],matrix[i-1][j+1])
return min(matrix[r-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 + 1, col - 1), (row + 1, col), or (row + 1, col + 1).
Example 1:
Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]
Output: 13
Explanation: There are two falling paths with a minimum sum as shown.
Example 2:
Input: matrix = [[-19,57],[-40,-5]]
Output: -59
Explanation: The falling path with a minimum sum is shown.
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 100
-100 <= matrix[i][j] <= 100 | 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 given n.
Example 1:
Input: n = 4
Output: [2,1,4,3]
Example 2:
Input: n = 5
Output: [3,1,2,5,4]
Constraints:
1 <= n <= 1000 | 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()
seen.add((i, j)) # mark as visited
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and A[ii][jj] and (ii, jj) not in seen:
stack.append((ii, jj))
seen.add((ii, jj))
# bfs
ans = 0
queue = list(seen)
while queue:
newq = []
for i, j in queue:
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen:
if A[ii][jj] == 1: return ans
newq.append((ii, jj))
seen.add((ii, jj))
queue = newq
ans += 1 | 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's you must flip to connect the two islands.
Example 1:
Input: grid = [[0,1],[1,0]]
Output: 1
Example 2:
Input: grid = [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Example 3:
Input: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
Constraints:
n == grid.length == grid[i].length
2 <= n <= 100
grid[i][j] is either 0 or 1.
There are exactly two islands in grid. | [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] = arr[2] + arr[8] + arr[9]
dp[4] = 0
dp[5] = arr[0] + arr[6] + arr[9]
dp[6] = arr[1] + arr[5]
dp[7] = arr[0] + arr[2]
dp[8] = arr[1] + arr[3]
dp[9] = arr[3] + arr[5]
arr = dp
return sum(arr) % (10**9+7) | 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 below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000 | 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] == '?':
continue
else:
return False
return True
while move < maxmove:
premove = move
for i in range(N-M+1):
if check(target[i:i+M]):
move += 1
ans.append(i)
target = target[:i] + "?"*M + target[i+M:]
if target == "?"*N : return ans[::-1]
if premove == move:return []
return [] | 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 one turn you can:
place stamp at index 0 of s to obtain "abc??",
place stamp at index 1 of s to obtain "?abc?", or
place stamp at index 2 of s to obtain "??abc".
Note that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).
We want to convert s to target using at most 10 * target.length turns.
Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.
Example 1:
Input: stamp = "abc", target = "ababc"
Output: [0,2]
Explanation: Initially s = "?????".
- Place stamp at index 0 to get "abc??".
- Place stamp at index 2 to get "ababc".
[1,0,2] would also be accepted as an answer, as well as some other answers.
Example 2:
Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]
Explanation: Initially s = "???????".
- Place stamp at index 3 to get "???abca".
- Place stamp at index 0 to get "abcabca".
- Place stamp at index 1 to get "aabcaca".
Constraints:
1 <= stamp.length <= target.length <= 1000
stamp and target consist of lowercase English letters. | 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 : x.split()[1:])
return l + d | 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 that:
The letter-logs come before all digit-logs.
The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
The digit-logs maintain their relative ordering.
Return the final order of the logs.
Example 1:
Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Explanation:
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
Example 2:
Input: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
Constraints:
1 <= logs.length <= 100
3 <= logs[i].length <= 100
All the tokens of logs[i] are separated by a single space.
logs[i] is guaranteed to have an identifier and at least one word after the identifier. | 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
if l and (lo < v or v > hi):
q.append(l)
if r and (lo > v or v < hi):
q.append(r)
return res | 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.
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
Constraints:
The number of nodes in the tree is in the range [1, 2 * 104].
1 <= Node.val <= 105
1 <= low <= high <= 105
All Node.val are unique. | ✔️ [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[point[1]][point[0]] = True
d[(point[0],point[1])] = True
for point in points:
x1 = point[0]
y1 = point[1]
for y2 in x_axis[x1]:
if y2 == y1:continue
for x2 in y_axis[y2]:
if x2 == x1:continue
if (x2,y1) in d:
tmp = abs(x2-x1) * abs(y2-y1)
if tmp < ans : ans = tmp
return ans if ans!=float('inf') else 0 | 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:
Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
Output: 2
Constraints:
1 <= points.length <= 500
points[i].length == 2
0 <= xi, yi <= 4 * 104
All the given points are unique. | 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
used[s[idx]] = True
ans += recursion(string + s[idx] , idx + 1)
return ans
res = recursion("",0)%MOD
return res | 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 remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.
Example 1:
Input: s = "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
Example 2:
Input: s = "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba".
Example 3:
Input: s = "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".
Constraints:
1 <= s.length <= 2000
s consists of lowercase English letters. | 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:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 104 | 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'):
ans.append(a)
else:
ans.append(b)
return ans | 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, return any of them.
Example 1:
Input: s = "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: s = "III"
Output: [0,1,2,3]
Example 3:
Input: s = "DDI"
Output: [3,2,0,1]
Constraints:
1 <= s.length <= 105
s[i] is either 'I' or 'D'. | [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])):
if words[i].endswith(words[j][:k]):
graph[i][j] = len(words[j]) - k
@cache
def fn(prev, mask):
"""Return length of shortest superstring & current choice of word."""
if mask == 0: return 0, None
vv, kk = inf, None
for k in range(n):
if mask & 1<<k:
v, _ = fn(k, mask ^ 1<<k)
offset = len(words[k]) if prev == -1 else graph[prev][k]
if v + offset < vv: vv, kk = v + offset, k
return vv, kk
ans = []
prev = -1
mask = (1<<n) - 1
while mask:
_, k = fn(prev, mask)
if ans: ans.append(words[k][-graph[prev][k]:])
else: ans.append(words[k])
prev = k
mask ^= 1<<k
return "".join(ans) | 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","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.
Example 2:
Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"
Constraints:
1 <= words.length <= 12
1 <= words[i].length <= 20
words[i] consists of lowercase English letters.
All the strings of words are unique. | [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 (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, while column 1 ('b', 'c', 'a') is not, so you would delete column 1.
Return the number of columns that you will delete.
Example 1:
Input: strs = ["cba","daf","ghi"]
Output: 1
Explanation: The grid looks as follows:
cba
daf
ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
Example 2:
Input: strs = ["a","b"]
Output: 0
Explanation: The grid looks as follows:
a
b
Column 0 is the only column and is sorted, so you will not delete any columns.
Example 3:
Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: The grid looks as follows:
zyx
wvu
tsr
All 3 columns are not sorted, so you will delete all 3.
Constraints:
n == strs.length
1 <= n <= 100
1 <= strs[i].length <= 1000
strs[i] consists of lowercase English letters. | 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]
ans += diff
nums[i] = nums[i-1] + 1
return ans | 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
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: nums = [3,2,1,2,1,7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105 | 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 following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
1 <= pushed.length <= 1000
0 <= pushed[i] <= 1000
All the elements of pushed are unique.
popped.length == pushed.length
popped is a permutation of pushed. | 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]:
if (x,b) in points:
remove_point(x,b)
x_dic = defaultdict(list)
y_dic = defaultdict(list)
points= {(i,j) for i,j in stones}
for i,j in stones: # Construction of graph by x_coordinates and y_coordinates.
x_dic[i].append(j)
y_dic[j].append(i)
cnt = 0
for a,b in stones: # counting of distinct connected graph.
if (a,b) in points:
remove_point(a,b)
cnt+=1
return len(stones)-cnt | 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 location of the ith stone, return the largest possible number of stones that can be removed.
Example 1:
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Explanation: One way to remove 5 stones is as follows:
1. Remove stone [2,2] because it shares the same row as [2,1].
2. Remove stone [2,1] because it shares the same column as [0,1].
3. Remove stone [1,2] because it shares the same row as [1,0].
4. Remove stone [1,0] because it shares the same column as [0,0].
5. Remove stone [0,1] because it shares the same row as [0,0].
Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.
Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Explanation: One way to make 3 moves is as follows:
1. Remove stone [2,2] because it shares the same row as [2,0].
2. Remove stone [2,0] because it shares the same column as [0,0].
3. Remove stone [0,2] because it shares the same row as [0,0].
Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.
Example 3:
Input: stones = [[0,0]]
Output: 0
Explanation: [0,0] is the only stone on the plane, so you cannot remove it.
Constraints:
1 <= stones.length <= 1000
0 <= xi, yi <= 104
No two stones are at the same coordinate point. | 📌📌 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
mx=max(mx,score)
elif score>0:
score-=1
power+=tokens[j]
j-=1
else:
break
return mx | 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 not both for the same token):
Face-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.
Face-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score.
Return the maximum possible score you can achieve after playing any number of tokens.
Example 1:
Input: tokens = [100], power = 50
Output: 0
Explanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).
Example 2:
Input: tokens = [200,100], power = 150
Output: 1
Explanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.
There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.
Example 3:
Input: tokens = [100,200,300,400], power = 200
Output: 2
Explanation: Play the tokens in this order to get a score of 2:
Play token0 (100) face-up, reducing power to 100 and increasing score to 1.
Play token3 (400) face-down, increasing power to 500 and reducing score to 0.
Play token1 (200) face-up, reducing power to 300 and increasing score to 1.
Play token2 (300) face-up, reducing power to 0 and increasing score to 2.
The maximum score achievable is 2.
Constraints:
0 <= tokens.length <= 1000
0 <= tokens[i], power < 104 | 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 else "" | 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. If no valid time can be made, return an empty string.
Example 1:
Input: arr = [1,2,3,4]
Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
Example 2:
Input: arr = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.
Constraints:
arr.length == 4
0 <= arr[i] <= 9 | [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 revealed:
Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
Note that the first entry in the answer is considered to be the top of the deck.
Example 1:
Input: deck = [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
Example 2:
Input: deck = [1,1000]
Output: [1,1000]
Constraints:
1 <= deck.length <= 1000
1 <= deck[i] <= 106
All the values of deck are unique. | 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, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)) | 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 true if the two trees are flip equivalent or false otherwise.
Example 1:
Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Output: true
Explanation: We flipped at nodes with values 1, 3, and 5.
Example 2:
Input: root1 = [], root2 = []
Output: true
Example 3:
Input: root1 = [], root2 = [1]
Output: false
Constraints:
The number of nodes in each tree is in the range [0, 100].
Each tree will have unique node values in the range [0, 99]. | 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 = Counter(uf.find(x) for x in nums)
return max(freq.values()) | 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 connected component in the graph.
Example 1:
Input: nums = [4,6,15,35]
Output: 4
Example 2:
Input: nums = [20,50,9,63]
Output: 2
Example 3:
Input: nums = [2,3,6,7,4,12,21,39]
Output: 8
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] <= 105
All the values of nums are unique. | [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:
return False
prev_repr = cur_repr
return True | 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 sorted lexicographically in this alien language.
Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.
Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in words[i] and order are English lowercase letters. | 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] -= 1
return True | 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]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
Constraints:
2 <= arr.length <= 3 * 104
arr.length is even.
-105 <= arr[i] <= 105 | 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 order, remove this column
if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break
# previous step, rows are not in order, but they are in order now
elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True
# if column wasn't removed, update the row order information
else: in_order = tmp_in_order
# not necessary, but speed things up
if all(in_order): return ans
return ans | 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 chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.
Example 1:
Input: strs = ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, strs = ["a", "b", "c"].
Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
Example 2:
Input: strs = ["xc","yb","za"]
Output: 0
Explanation:
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)
Example 3:
Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: We have to delete every column.
Constraints:
n == strs.length
1 <= n <= 100
1 <= strs[i].length <= 100
strs[i] consists of lowercase English letters. | 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), v+k)
return dp[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 together to make a support of length 6.
Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.
Example 1:
Input: rods = [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input: rods = [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input: rods = [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Constraints:
1 <= rods.length <= 20
1 <= rods[i] <= 1000
sum(rods[i]) <= 5000 | [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:
next_day_cells[i] = 0
return next_day_cells
seen = {}
while N > 0:
c = tuple(cells)
if c in seen:
N %= seen[c] - N
seen[c] = N
if N >= 1:
N -= 1
cells = nextday(cells)
return cells | 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 because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.
Return the state of the prison after n days (i.e., n such changes described above).
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], n = 7
Output: [0,0,1,1,0,0,0,0]
Explanation: The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000
Output: [0,0,1,1,1,1,1,0]
Constraints:
cells.length == 8
cells[i] is either 0 or 1.
1 <= n <= 109 | [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 nodes to the right of the left-most null
# node encountered (if it exists).
#
# The plan is to bfs the tree, left to right, level by level. We mark the
# instance of the first null popped from the queue and then ensure the remaining
# queue is only null nodes. If so, both criteria are satisfied and True is
# returned. If not, False is returned.
queue = deque([root]) # <-- initialize the queue
while queue[0]: # <-- if and while top queue node is not null, pop
node = queue.popleft() # it and then push its left child and right
queue.extend([node.left, node.right]) # child onto the queue.
while queue and not queue[0]: # <-- if and while top queue node is null, pop it.
queue.popleft() #
if queue: return False # <-- If the queue is not empty, it must be non-null, so
return True # return False; if the queue is empty, return True. | 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,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 1000 | 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)
n, regions = len(grid), 0
g = [[0] * n * 3 for i in range(n * 3)]
for i in range(n):
for j in range(n):
if grid[i][j] == '/':
g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1
elif grid[i][j] == '\\':
g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1
for i in range(n * 3):
for j in range(n * 3):
regions += 1 if dfs(i, j) > 0 else 0
return regions | 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 as '\\'.
Example 1:
Input: grid = [" /","/ "]
Output: 2
Example 2:
Input: grid = [" /"," "]
Output: 1
Example 3:
Input: grid = ["/\\","\\/"]
Output: 5
Explanation: Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.
Constraints:
n == grid.length == grid[i].length
1 <= n <= 30
grid[i][j] is either '/', '\', or ' '. | 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 column
if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(m)):
ans = min(ans, fn(k+1, k)) # retain kth column
return ans
return fn(0, -1) | 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 chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.
Example 1:
Input: strs = ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).
Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.
Example 2:
Input: strs = ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.
Example 3:
Input: strs = ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.
Constraints:
n == strs.length
1 <= n <= 100
1 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
| [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
Example 3:
Input: nums = [5,1,5,2,5,3,5,4]
Output: 5
Constraints:
2 <= n <= 5000
nums.length == 2 * n
0 <= nums[i] <= 104
nums contains n + 1 unique elements and one of them is repeated exactly n times. | 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 + hi >> 1
if A[stack[mid]] <= A[i]: hi = mid
else: lo = mid + 1
ans = max(ans, i - stack[lo])
return ans | 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 ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
Example 2:
Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
Constraints:
2 <= nums.length <= 5 * 104
0 <= nums[i] <= 5 * 104 | [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
for xx, yy in seen.get((cx, cy, d2), []):
area = sqrt(((x0-xx)**2 + (y0-yy)**2) * ((x1-xx)**2 + (y1-yy)**2))
ans = min(ans, area)
seen.setdefault((cx, cy, d2), []).append((x0, y0))
return ans if ans < inf else 0 | 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.
Example 1:
Input: points = [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
Example 2:
Input: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.
Example 3:
Input: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]
Output: 0
Explanation: There is no possible rectangle to form from these points.
Constraints:
1 <= points.length <= 50
points[i].length == 2
0 <= xi, yi <= 4 * 104
All the given points are unique. | [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 x**(k+1) < 2*val:
ans = min(ans, k + 1 + fn(x**(k+1) - val))
return ans
return fn(target) | 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 expression, we adhere to the following conventions:
The division operator (/) returns rational numbers.
There are no parentheses placed anywhere.
We use the usual order of operations: multiplication and division happen before addition and subtraction.
It is not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.
Example 1:
Input: x = 3, target = 19
Output: 5
Explanation: 3 * 3 + 3 * 3 + 3 / 3.
The expression contains 5 operations.
Example 2:
Input: x = 5, target = 501
Output: 8
Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.
The expression contains 8 operations.
Example 3:
Input: x = 100, target = 100000000
Output: 3
Explanation: 100 * 100 * 100 * 100.
The expression contains 3 operations.
Constraints:
2 <= x <= 100
1 <= target <= 2 * 108 | [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 the tree is in the range [1, 100].
0 <= Node.val < 100 | 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 all words that match "key" -> ["Key", "kEy", "KEY"]
# The other for vowel insensitive words "k*t*" -> ["Kite", "kato", "KUTA"]
case_insensitive = collections.defaultdict(list)
vowel_insensitive = collections.defaultdict(list)
for word in wordlist:
case_insensitive[word.lower()].append(word)
key = ''.join(char.lower() if char not in vowels else '*' for char in word)
vowel_insensitive[key].append(word)
res = []
for word in queries:
# Case 1: When query exactly matches a word
if word in words:
res.append(word)
continue
# Case 2: When query matches a word up to capitalization
low = word.lower()
if low in case_insensitive:
res.append(case_insensitive[low][0])
continue
# Case 3: When query matches a word up to vowel errors
key = ''.join(char.lower() if char not in vowels else '*' for char in word)
if key in vowel_insensitive:
res.append(vowel_insensitive[key][0])
continue
res.append('')
return res | 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 as the case in the wordlist.
Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow"
Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow"
Example: wordlist = ["yellow"], query = "yellow": correct = "yellow"
Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw"
Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)
Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match)
In addition, the spell checker operates under the following precedence rules:
When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.
When the query matches a word up to capitlization, you should return the first such match in the wordlist.
When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
If the query has no matches in the wordlist, you should return the empty string.
Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].
Example 1:
Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]
Example 2:
Input: wordlist = ["yellow"], queries = ["YellOw"]
Output: ["yellow"]
Constraints:
1 <= wordlist.length, queries.length <= 5000
1 <= wordlist[i].length, queries[i].length <= 7
wordlist[i] and queries[i] consist only of only English letters. | [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%10
for k in graph[last]:
new.add(i*10 + k)
start = new
return list(start) | 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,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.
Example 2:
Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
Constraints:
2 <= n <= 9
0 <= k <= 9 | 🔥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)
# find out if current node is a root node / next node in line to be monitored
curr = min(node.left.val if node.left else float('inf'), node.right.val if node.right else float('inf'))
if curr == 0:
# at least one child node requires monitoring, this node must have a camera
node.val = 1
res += 1
elif curr == 1:
# at least one child node is a camera, this node is already monitored
node.val = 2
# if curr == float('inf'), the current node is a leaf node; let the parent node monitor this node
# if curr == 2, all child nodes are being monitored; treat the current node as a leaf node
return res
# ensure that root node is monitored, otherwise, add a camera onto root node
return dfs(root)+(root.val == 0) | 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 is enough to monitor all nodes if placed as shown.
Example 2:
Input: root = [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
Node.val == 0 | [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
# ==> if max not at the end : flip again until the max is at the end of the array
# ==> from 0 to max_position = k
# end = end - 1
# repeat previous steps
while end > 0:
max_num = max(arr[:end+1])
index_num = arr.index(max_num)
if index_num != end:
k = index_num + 1
arr = arr[0:k][::-1] + arr[k:]
flips.append(k)
arr = arr[:end+1][::-1] + arr[end+1:]
flips.append(end+1)
else:
k = end
arr = arr[0:k][::-1] + arr[k:]
flips.append(k)
end -= 1
return flips | 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 reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.
Example 1:
Input: arr = [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = [3, 2, 4, 1]
After 1st flip (k = 4): arr = [1, 4, 2, 3]
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
Example 2:
Input: arr = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= arr.length
All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length). | 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 <= bound:
ans.add(x**i + y**j)
return ans | 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.
Example 1:
Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32
Example 2:
Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]
Constraints:
1 <= x, y <= 100
0 <= bound <= 106 | [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.val != voyage[self.index]: return [-1]
self.index += 1
if node.left and node.left.val != voyage[self.index]:
self.flipped_nodes.append(node.val)
node.left, node.right = node.right, node.left
queue.append(node.right), queue.append(node.left)
return self.flipped_nodes | 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, flipping node 1 will have the following effect:
Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.
Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].
Example 1:
Input: root = [1,2], voyage = [2,1]
Output: [-1]
Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.
Example 2:
Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]
Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
Example 3:
Input: root = [1,2,3], voyage = [1,2,3]
Output: []
Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
Constraints:
The number of nodes in the tree is n.
n == voyage.length
1 <= n <= 100
1 <= Node.val, voyage[i] <= n
All the values in the tree are unique.
All the values in voyage are unique. | 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 Mansuri | 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>, <NonRepeatingPart>, and a <RepeatingPart>. The number will be represented in one of the following three ways:
<IntegerPart>
For example, 12, 0, and 123.
<IntegerPart><.><NonRepeatingPart>
For example, 0.5, 1., 2.12, and 123.0001.
<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
For example, 0.1(6), 1.(9), 123.00(1212).
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).
Example 1:
Input: s = "0.(52)", t = "0.5(25)"
Output: true
Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.
Example 2:
Input: s = "0.1666(6)", t = "0.166(66)"
Output: true
Example 3:
Input: s = "0.9(9)", t = "1."
Output: true
Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".
Constraints:
Each part consists only of digits.
The <IntegerPart> does not have leading zeros (except for the zero itself).
1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4 | 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 guaranteed to be unique (except for the order that it is in).
Example 1:
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.
Constraints:
1 <= k <= points.length <= 104
-104 <= xi, yi <= 104 | ✔️ [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, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example 2:
Input: nums = [5], k = 9
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104 | 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 and i > stack[-1]:
result[stack.pop()] = i
stack.append(i)
return result
sortedIdx = sorted(range(len(A)), key= lambda x: A[x])
oddIndexes = getNextIndex(sortedIdx)
sortedIdx.sort(key=lambda x: -A[x])
evenIndexes = getNextIndex(sortedIdx)
# [odd, even], the 0th jump is even
dp = [[0,1] for _ in range(len(A))]
for i in range(len(A)):
if oddIndexes[i] is not None:
dp[oddIndexes[i]][0] += dp[i][1]
if evenIndexes[i] is not None:
dp[evenIndexes[i]][1] += dp[i][0]
return dp[-1][0] + dp[-1][1] | 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 forward from index i to index j (with i < j) in the following way:
During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
It may be the case that for some index i, there are no legal jumps.
A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).
Return the number of good starting indices.
Example 1:
Input: arr = [10,13,12,14,15]
Output: 2
Explanation:
From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.
From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.
From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.
From starting index i = 4, we have reached the end already.
In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of
jumps.
Example 2:
Input: arr = [2,3,1,1,4]
Output: 3
Explanation:
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:
During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].
During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3
During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].
We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.
In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some
number of jumps.
Example 3:
Input: arr = [5,1,3,4,2]
Output: 3
Explanation: We can reach the end from starting indices 1, 2, and 4.
Constraints:
1 <= arr.length <= 2 * 104
0 <= arr[i] < 105 | 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.
Example 2:
Input: nums = [1,2,1,10]
Output: 0
Explanation:
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
Constraints:
3 <= nums.length <= 104
1 <= nums[i] <= 106 | 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
while write_pointer >= 0:
if left_square > right_square:
return_array[write_pointer] = left_square
left_read_pointer += 1
left_square = A[left_read_pointer] ** 2
else:
return_array[write_pointer] = right_square
right_read_pointer -= 1
right_square = A[right_read_pointer] ** 2
write_pointer -= 1
return return_array | 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:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach? | 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]
# Valid element in subarray, continue cur subarray
elif (t and arr[i] < arr[i-1]) or (not t and arr[i] > arr[i-1]):
cur += 1; t = not t
# Invalid element in subarray, start new subarray
else:
if arr[i] == arr[i-1]: t = None
mx = max(mx, cur)
cur = 2
return max(mx, cur) | 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 < j:
arr[k] > arr[k + 1] when k is odd, and
arr[k] < arr[k + 1] when k is even.
Or, for i <= k < j:
arr[k] > arr[k + 1] when k is even, and
arr[k] < arr[k + 1] when k is odd.
Example 1:
Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]
Example 2:
Input: arr = [4,8,12,16]
Output: 2
Example 3:
Input: arr = [100]
Output: 1
Constraints:
1 <= arr.length <= 4 * 104
0 <= arr[i] <= 109 | ✅ [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 minimum number of moves required to make every node have exactly one coin.
Example 1:
Input: root = [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:
Input: root = [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Constraints:
The number of nodes in the tree is n.
1 <= n <= 100
0 <= Node.val <= n
The sum of all Node.val is n. | 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])):
if grid[i][j] == 0:
visit.add((i, j))
elif grid[i][j] == 1:
start = (i, j)
elif grid[i][j] == 2:
end = (i, j)
visit.add((i, j))
def backtrack(x, y, visit):
if (x, y) == end:
# implement success condition: valid only if there are no more coordinates to visit
return len(visit) == 0
result = 0 # assume no valid paths by default
# we need to try every possible path from this coordinate
if (x-1, y) in visit:
# the coordinate directly above this one is non-obstacle, try that path
visit.remove((x-1, y)) # first, note down the 'visited status' of the coordinate
result += backtrack(x-1, y, visit) # then, DFS to find all valid paths from that coordinate
visit.add((x-1, y)) # last, reset the 'visited status' of the coordinate
if (x+1, y) in visit:
# the coordinate directly below this one is non-obstacle, try that path
visit.remove((x+1, y))
result += backtrack(x+1, y, visit)
visit.add((x+1, y))
if (x, y-1) in visit:
# the coordinate directly to the left of this one is non-obstacle, try that path
visit.remove((x, y-1))
result += backtrack(x, y-1, visit)
visit.add((x, y-1))
if (x, y+1) in visit:
# the coordinate directly to the right of this one is non-obstacle, try that path
visit.remove((x, y+1))
result += backtrack(x, y+1, visit)
visit.add((x, y+1))
return result
return backtrack(start[0], start[1], visit) # we start from the starting point, backtrack all the way back, and consolidate the result | 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 the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
Example 1:
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Explanation: We have the following two paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
Example 2:
Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
Explanation: We have the following four paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
Example 3:
Input: grid = [[0,1],[2,0]]
Output: 0
Explanation: There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 20
1 <= m * n <= 20
-1 <= grid[i][j] <= 2
There is exactly one starting cell and one ending cell. | 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[x]
x = mask & (x-1)
ans += freq[0]
return ans | 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: We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
Example 2:
Input: nums = [0,0,0]
Output: 27
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 216 | [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 d in range(1, len(costForDays)):
#if we do not need to travel that day
#we don't need to add extra costs
if d < days[curIdx]:
costForDays[d] = costForDays[d - 1]
continue
#else this means we need to travel this day
#find the cost if we were to buy a 1-day pass, 7-day pass and 30-day pass
costs_extra_1 = costForDays[d - 1] + costs[0]
costs_extra_7 = costForDays[max(0, d - 7)] + costs[1]
costs_extra_30 = costForDays[max(0, d - 30)] + costs[2]
#get the minimum value
costForDays[d] = min(costs_extra_1, costs_extra_7, costs_extra_30)
#update the index to the next day we need to travel
curIdx += 1
return costForDays[-1] | 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 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel.
For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation: For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
Constraints:
1 <= days.length <= 365
1 <= days[i] <= 365
days is in strictly increasing order.
costs.length == 3
1 <= costs[i] <= 1000 | 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')
a-=1
elif a > b:
res.append('a')
a-=1
else:
res.append('b')
b-=1
return ''.join(res) | 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 correct answers.
Example 2:
Input: a = 4, b = 1
Output: "aabaa"
Constraints:
0 <= a, b <= 100
It is guaranteed such an s exists for the given a and b. | 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], queries: List[List[int]]) -> List[int]:
# calculate the sum of all even numbers
evenSum = sum(x for x in nums if x % 2 == 0)
ans = []
for val, idx in queries:
# if original nums[idx] is even, then we deduct it from evenSum
if nums[idx] % 2 == 0: evenSum -= nums[idx]
# in-place update nums
nums[idx] += val
# check if we need to update evenSum for the new value
if nums[idx] % 2 == 0: evenSum += nums[idx]
# then we have evenSum after this query, push it to ans
ans.append(evenSum)
return ans | 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], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation: At the beginning, the array is [1,2,3,4].
After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
Example 2:
Input: nums = [1], queries = [[4,0]]
Output: [0]
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
1 <= queries.length <= 104
-104 <= vali <= 104
0 <= indexi < nums.length | 🔥 [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_b :
# Get start-time as well as end-time
start_a, end_a = A[idx_a]
start_b, end_b = B[idx_b]
# Compute common start time and end time for current interval pair
common_start = max( start_a, start_b )
common_end = min( end_a, end_b )
if common_start <= common_end:
# Find one common overlapped interval
intersection.append( [common_start, common_end] )
if end_a <= end_b:
# Try next interval of A
idx_a += 1
else:
# Try next interval of B
idx_b += 1
return intersection | 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 real numbers x with a <= x <= b.
The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].
Example 1:
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Example 2:
Input: firstList = [[1,3],[5,9]], secondList = []
Output: []
Constraints:
0 <= firstList.length, secondList.length <= 1000
firstList.length + secondList.length >= 1
0 <= starti < endi <= 109
endi < starti+1
0 <= startj < endj <= 109
endj < startj+1 | 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(node.val)
results[(pos,depth)].sort()
queue.extend( [ (node.left, pos-1, depth+1), (node.right, pos+1, depth+1) ] )
res = defaultdict(list)
keys = sorted(list(results.keys()), key=lambda x: (x[0], x[1]))
for k in keys:
pos, depth = k
res[pos].extend(results[k])
return res.values() | 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 list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return the vertical order traversal of the binary tree.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
Example 2:
Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
Example 3:
Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 1000 | 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:
self.res = min(self.res, prev)
return
if node.left:
helper(node.left, prev)
if node.right:
helper(node.right, prev)
helper(root, "")
return self.res | 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" is lexicographically smaller than "aba".
A leaf of a node is a node that has no children.
Example 1:
Input: root = [0,1,2,3,4,3,4]
Output: "dba"
Example 2:
Input: root = [25,1,3,1,3,0,2]
Output: "adz"
Example 3:
Input: root = [2,2,1,null,1,0,null,0]
Output: "abc"
Constraints:
The number of nodes in the tree is in the range [1, 8500].
0 <= Node.val <= 25 | 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]
Explanation: 1200 + 34 = 1234
Example 2:
Input: num = [2,7,4], k = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455
Example 3:
Input: num = [2,1,5], k = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021
Constraints:
1 <= num.length <= 104
0 <= num[i] <= 9
num does not contain any leading zeros except for the zero itself.
1 <= k <= 104 | 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 the connected graphs
# 3) We keep track of the pairs (a,b) such that a =! b. If the any
# such pair are in the same connected graph, then return False,
# otherwise return True.
def equationsPossible(self, equations: List[str]) -> bool:
parent, diff = {}, []
def find(x):
if x not in parent: return x
else: return find(parent[x])
for s in equations: # <-- 1)
a, b = s[0], s[3]
if s[1]== "=": # <-- 2)
x, y = find(a), find(b)
if x!=y:
parent[y] = x
else:
diff.append((a,b)) # <-- 3)
return all(find(a)!=find(b) for a, b in diff) | 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 it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.
Example 1:
Input: equations = ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
Example 2:
Input: equations = ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Constraints:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] is a lowercase letter.
equations[i][1] is either '=' or '!'.
equations[i][2] is '='.
equations[i][3] is a lowercase letter. | 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)
return res | 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.
Example 1:
Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2:
Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.
Example 3:
Input: startValue = 3, target = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.
Constraints:
1 <= startValue, target <= 109 | 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.add(nums[right])
hash_map[nums[right]] += 1
while len(in_set) > k:
hash_map[nums[left]] -= 1
if hash_map[nums[left]] == 0:
in_set.remove(nums[left])
left += 1
res += (right - left + 1)
right += 1
return res
return window(nums, k) - window(nums, k - 1) | 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 = [1,2,1,2,3], k = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Example 2:
Input: nums = [1,2,1,3,4], k = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i], k <= nums.length | [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:
tmp = []
# Check nodes two-by-two
for i in range(0, len(curr), 2):
# Case 1: x and y are both found
# This indicates that they have the same parent
if curr[i] and curr[i+1] and \
((curr[i].val == x and curr[i+1].val == y) or \
(curr[i+1].val == x and curr[i].val == y)):
return False
# Case 2: Either one of x or y is found
elif (curr[i] and (curr[i].val == x or curr[i].val == y)) or \
(curr[i+1] and (curr[i+1].val == x or curr[i+1].val == y)):
if flag:
# Previously, the other node has been found in the same depth
# This is our success condition, return True
return True
# Otherwise, this is the first node in the current depth to be found
flag = True
# Simultaneously, we can prepare the nodes for the subsequent depth
# Note to append both left and right regardless of existence
if curr[i]:
tmp.append(curr[i].left)
tmp.append(curr[i].right)
if curr[i+1]:
tmp.append(curr[i+1].left)
tmp.append(curr[i+1].right)
# Before we proceed to the next depth, check:
if flag:
# One of the nodes has already been found
# This means that the other node cannot be of the same depth
# By definition, this means that the two nodes are not cousins
return False
curr = tmp # Assign the new nodes as the current ones
# The program will never reach here since x and y are guaranteed to be found
# But you can return False if you want | 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 a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Constraints:
The number of nodes in the tree is in the range [2, 100].
1 <= Node.val <= 100
Each node has a unique value.
x != y
x and y are exist in the tree. | 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))
elif grid[i][j] == 2:
curr.append((i, j))
result = 0
while visit and curr:
# BFS iteration
for _ in range(len(curr)):
i, j = curr.popleft() # obtain recent rotten orange
for coord in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):
if coord in visit: # check if adjacent orange is fresh
visit.remove(coord)
curr.append(coord)
result += 1
# check if fresh oranges remain and return accordingly
return -1 if visit else result | 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 elapse until no cell has a fresh orange. If this is impossible, return -1.
Example 1:
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j] is 0, 1, or 2. | 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+k-1)
else:
return -1
else:
if nums[i] == 1:
if i+k-1 <= len(nums)-1:
ans += 1
q.append(i+k-1)
else:
return -1
if q:
if q[0] == i:
q.pop(0)
return ans | 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.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [0,1,0], k = 1
Output: 2
Explanation: Flip nums[0], then flip nums[2].
Example 2:
Input: nums = [1,1,0], k = 2
Output: -1
Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].
Example 3:
Input: nums = [0,0,0,1,0,1,1,0], k = 3
Output: 3
Explanation:
Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]
Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]
Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]
Constraints:
1 <= nums.length <= 105
1 <= k <= nums.length | 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 (len(temp) > 0 and math.sqrt(num[i] + temp[-1]) % 1 != 0):
continue
count = dfs(temp+[num[i]],num[:i]+num[i+1:],count)
return count
nums.sort()
res = dfs([],nums)
return res | 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]
Output: 2
Explanation: [1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: nums = [2,2,2]
Output: 1
Constraints:
1 <= nums.length <= 12
0 <= nums[i] <= 109 | 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
return -1 | 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 an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.
Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.
Example 1:
Input: n = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: n = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: n = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Constraints:
1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
All the pairs of trust are unique.
ai != bi
1 <= ai, bi <= n | [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:
If a is empty, return null.
Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i].
The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).
The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).
Return root.
Note that we were not given a directly, only a root node root = Construct(a).
Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.
Return Construct(b).
Example 1:
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: a = [1,4,2,3], b = [1,4,2,3,5]
Example 2:
Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: a = [2,1,5,4], b = [2,1,5,4,3]
Example 3:
Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: a = [2,1,5,3], b = [2,1,5,3,4]
Constraints:
The number of nodes in the tree is in the range [1, 100].
1 <= Node.val <= 100
All the values of the tree are unique.
1 <= val <= 100 | [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, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.
Return the number of available captures for the white rook.
Example 1:
Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: In this example, the rook is attacking all the pawns.
Example 2:
Input: board = [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation: The bishops are blocking the rook from attacking any of the pawns.
Example 3:
Input: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation: The rook is attacking the pawns at positions b5, d6, and f5.
Constraints:
board.length == 8
board[i].length == 8
board[i][j] is either 'R', '.', 'B', or 'p'
There is exactly one cell with board[i][j] == 'R' | 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[lo:hi]."""
if hi - lo < k: return 0 # not enough stones
ans = inf
for mid in range(lo+1, hi, k-1):
ans = min(ans, fn(lo, mid) + fn(mid, hi))
if (hi-lo-1) % (k-1) == 0: ans += prefix[hi] - prefix[lo]
return ans
return fn(0, len(stones)) | 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 impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], k = 2
Output: 20
Explanation: We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], k = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], k = 3
Output: 25
Explanation: We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Constraints:
n == stones.length
1 <= n <= 30
1 <= stones[i] <= 100
2 <= k <= 30 | [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] = col.get(c, 0) + 1
left[r - c] = left.get(r - c, 0) + 1
right[r + c] = right.get(r + c, 0) + 1
res = list()
for qr, qc in queries:
if row.get(qr, 0) or col.get(qc, 0) or left.get(qr - qc, 0) or right.get(qr + qc, 0):
res.append(1)
else:
res.append(0)
for r, c in product(range(qr - 1, qr + 2), range(qc - 1, qc + 2)):
if (r, c) in lamps:
lamps.remove((r, c))
row[r] -= 1
col[c] -= 1
left[r - c] -= 1
right[r + c] -= 1
return res | 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 turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.
You are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].
Return an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.
Example 1:
Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].
The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.
Example 2:
Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]
Output: [1,1]
Example 3:
Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]
Output: [1,1,0]
Constraints:
1 <= n <= 109
0 <= lamps.length <= 20000
0 <= queries.length <= 20000
lamps[i].length == 2
0 <= rowi, coli < n
queries[j].length == 2
0 <= rowj, colj < n | 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:
res += [c] * n
return res | 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"]
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of lowercase English letters. | 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
stack.append(i)
else:
if not stack:return False
else:
if stack[-1]=='b':stack.pop()
else:return False
return len(stack)==0 | 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 that tleft and tright may be empty.
Return true if s is a valid string, otherwise, return false.
Example 1:
Input: s = "aabcbc"
Output: true
Explanation:
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.
Example 2:
Input: s = "abcabcababcc"
Output: true
Explanation:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.
Example 3:
Input: s = "abccba"
Output: false
Explanation: It is impossible to get "abccba" using the operation.
Constraints:
1 <= s.length <= 2 * 104
s consists of letters 'a', 'b', and 'c' | 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
left += 1
curr_window_size = right - left + 1
answer = max(answer, curr_window_size)
return answer | 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.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
0 <= k <= nums.length | [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 value), this means -1*-1==1 so it has no effect on sum
return sum(A)
else: return sum(A) - 2 * min(A) # let A==[1,2,3],K=1, so equation is 6-2(1)==4, same as -1+2+3=4 after taking the minimum in the list to give the largest possible sum required in the question
else: return sum(A) # if A[i]==0,just sum cuz 0 is neutral: 1-0==1 or 1+0==1 thus no change just sum
i+=1
if K > len(A): # that means we have changed all values to positive
A.sort() # cuz now its the opposite let A = [-4,-2,-3], K = 8, now flipping all negatives to positives, we have a new minimum which is 2
if K % 2 == 0: # Here onwards is basically the same thing from before
return sum(A)
else: return sum(A) - 2 * min(A)
return sum(A) | 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 1:
Input: nums = [4,2,3], k = 1
Output: 5
Explanation: Choose index 1 and nums becomes [4,-2,3].
Example 2:
Input: nums = [3,-1,0,2], k = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
Input: nums = [2,-3,-1,5,-4], k = 2
Output: 13
Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Constraints:
1 <= nums.length <= 104
-100 <= nums[i] <= 100
1 <= k <= 104 | 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 multiply '*', divide '/', add '+', and subtract '-' in this order.
For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.
Given an integer n, return the clumsy factorial of n.
Example 1:
Input: n = 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1
Example 2:
Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
Constraints:
1 <= n <= 104 | 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:
top_fr[top] += 1
bot_fr[bot] += 1
for val in range(1, 7):
if (val_total[val] - top_fr[val]) == bot_fr[val]:
return min(top_fr[val], bot_fr[val])
return -1 | 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 tops are the same, or all the values in bottoms are the same.
If it cannot be done, return -1.
Example 1:
Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
Example 2:
Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.
Constraints:
2 <= tops.length <= 2 * 104
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6 | ✔️[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.left
else:
while node_stack and n > node_stack[-1].val:
node = node_stack.pop()
node.right = TreeNode(n)
node = node.right
return root | 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 tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
Example 1:
Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Example 2:
Input: preorder = [1,3]
Output: [1,null,3]
Constraints:
1 <= preorder.length <= 100
1 <= preorder[i] <= 1000
All the values of preorder are unique. | 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
return result | 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
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
Example 2:
Input: n = 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
Example 3:
Input: n = 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
Constraints:
0 <= n < 109
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/ | 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,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60
Example 2:
Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
Constraints:
1 <= time.length <= 6 * 104
1 <= time[i] <= 500 | 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:
return False
return True
left, right = max(weights), sum(weights)
while left < right:
mid = left + (right-left)//2
if feasible(mid):
right = mid
else:
left = mid + 1
return left | 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 ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], days = 3
Output: 6
Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], days = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
Constraints:
1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500 | 📌📌 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(str(N)[i]))
m.append(g)
g = g*(12-L+i)
S = 0
for i in range(L):
if len(set(n[:L-i-1])) != len(n)-i-1:
continue
k = 0
for j in range(10):
if j not in n[:L-i-1] and j > n[L-i-1]:
k += 1
S += k*m[i]
return(T[L-2]-(t[L-2]-N-S))
- Python 3
- Junaid Mansuri | 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) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: n = 1000
Output: 262
Constraints:
1 <= n <= 109 | 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])
Example 1:
Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
Example 2:
Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: arr = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= arr.length <= 5 * 104
-104 <= arr[i] <= 104 | 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 maxVal | 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 between them.
Return the maximum score of a pair of sightseeing spots.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
Constraints:
2 <= values.length <= 5 * 104
1 <= values[i] <= 1000 | ✅ || 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 smallest answer is n = 1, which has length 1.
Example 2:
Input: k = 2
Output: -1
Explanation: There is no such positive integer n divisible by 2.
Example 3:
Input: k = 3
Output: 3
Explanation: The smallest answer is n = 111, which has length 3.
Constraints:
1 <= k <= 105 | [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", n = 4
Output: false
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= n <= 109 | [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
Example 3:
Input: n = 4
Output: "100"
Explantion: (-2)2 = 4
Constraints:
0 <= n <= 109 | 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 divisible by 5.
Example 1:
Input: nums = [0,1,1]
Output: [true,false,false]
Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer[0] is true.
Example 2:
Input: nums = [1,1,1]
Output: [false,false,false]
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1. | 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()
result[index] = current
stack.append((current, i))
return result
def value_iterator(self, head: ListNode):
while head is not None:
yield head.val
head = head.next | 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 node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.
Example 1:
Input: head = [2,1,5]
Output: [5,5,0]
Example 2:
Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]
Constraints:
The number of nodes in the list is n.
1 <= n <= 104
1 <= Node.val <= 109 | 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(1,col-1) if A[0][i]==1]) + deque([(row-1,i) for i in range(1,col-1) if A[row-1][i]==1])
queue = boundary1+boundary2
def bfs(queue,A):
visited = set()
while queue:
x,y = queue.popleft()
A[x][y] = "T"
if (x,y) in visited: continue
visited.add((x,y))
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col and A[nx][ny]==1:
A[nx][ny] = "T"
queue.append((nx,ny))
return A
bfs(queue,A)
count = 0
for x in range(row):
for y in range(col):
if A[x][y] == 1:
count+=1
return count | 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 of the grid in any number of moves.
Example 1:
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Example 2:
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: All 1s are either on the boundary or can reach the boundary.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j] is either 0 or 1. | Python BFS and DFS by yours truly | 1,100 | number-of-enclaves | 0.65 | Skywalker5423 | Medium | 16,664 | 1,020 |
Subsets and Splits