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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
number of days between two dates | class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def f_date(date): # calculates days passed since '1900-01-01'
year0 = '1900'
year1, month1, day1 = date.split('-')
days = 0
for y in range(int(year0), int(year1)):
days += 365
if y%100 == 0:
if y%400 == 0:
days += 1
else:
if y%4 == 0:
days += 1
for m in range(int(month1)):
if m in [1, 3, 5, 7, 8, 10, 12]:
days += 31
if m in [4, 6, 9, 11]:
days += 30
if m == 2:
days += 28
if int(year1)%100 == 0:
if int(year1)%400 == 0:
days += 1
else:
if int(year1)%4 ==0:
days += 1
days += int(day1)
return days
return abs(f_date(date1) - f_date(date2)) | https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1814530/Python3-Solution-from-Scratch-NOT-USING-DATETIME | 3 | Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Example 1:
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Constraints:
The given dates are valid dates between the years 1971 and 2100. | Python3 Solution from Scratch - NOT USING DATETIME | 617 | number-of-days-between-two-dates | 0.476 | rmateusc | Easy | 20,467 | 1,360 |
validate binary tree nodes | class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
n = len(leftChild)
# tree has 2 requirements
# 1. every node has a single parent
# 2. single root (only one node has NO parent)
# 3. no cycle
# 4. all nodes connected to each other (single component)
parent = [-1] * n
# checking condition (1. and 2.)
for idx, (left, right) in enumerate(zip(leftChild, rightChild)):
if left != -1:
# FAILED: condition (1.)
if parent[left] != -1: return False
parent[left] = idx
if right != -1:
# FAILED: condition (1.)
if parent[right] != -1: return False
parent[right] = idx
# FAILED condition (2.)
if parent.count(-1) != 1: return False
# checking condition (3. and 4.)
vis = set()
def dfs_has_cycle(u):
if u in vis:
return True
else:
vis.add(u)
for kid in [leftChild[u], rightChild[u]]:
if kid != -1:
if dfs_has_cycle(kid): return True
# FAILED condition (3.) - found a cycle
if dfs_has_cycle(parent.index(-1)): return False
# FAILED condition (4.) - DFS did not visit all nodes!
if len(vis) != n: return False
# did not FAIL any condition, success ;)
return True
"""
Tricky test case (cycle and not connected):
4
[1,-1,3,-1]
[2,-1,-1,-1]
""" | https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1393392/Diagram-Explained-Clean-4-checks-single-parents-single-root-no-cycle-all-connected | 6 | You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
Example 1:
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
Output: true
Example 2:
Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
Output: false
Example 3:
Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
Output: false
Constraints:
n == leftChild.length == rightChild.length
1 <= n <= 104
-1 <= leftChild[i], rightChild[i] <= n - 1 | Diagram Explained Clean 4 checks [single parents, single root, no cycle, all connected] | 232 | validate-binary-tree-nodes | 0.403 | yozaam | Medium | 20,474 | 1,361 |
closest divisors | class Solution:
def closestDivisors(self, num: int) -> List[int]:
for i in range(int((num+2)**0.5), 0, -1):
if not (num+1)%i: return (i, (num+1)//i)
if not (num+2)%i: return (i, (num+2)//i) | https://leetcode.com/problems/closest-divisors/discuss/517720/Python3-A-concise-solution | 1 | Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.
Return the two integers in any order.
Example 1:
Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
Example 2:
Input: num = 123
Output: [5,25]
Example 3:
Input: num = 999
Output: [40,25]
Constraints:
1 <= num <= 10^9 | [Python3] A concise solution | 50 | closest-divisors | 0.599 | ye15 | Medium | 20,490 | 1,362 |
largest multiple of three | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
def dump(r: int) -> str:
if r:
for i in range(3):
idx = 3 * i + r
if counts[idx]:
counts[idx] -= 1
break
else:
rest = 2
for j in range(3):
idx = 3 * j + (-r % 3)
while rest and counts[idx]:
counts[idx] -= 1
rest -= 1
if not rest: break
if rest: return ''
if any(counts):
result = ''
for i in reversed(range(10)):
result += str(i) * counts[i]
return str(int(result))
return ''
total, counts = 0, [0] * 10
for digit in digits:
counts[digit] += 1
total += digit
return dump(total % 3) | https://leetcode.com/problems/largest-multiple-of-three/discuss/519005/Clean-Python-3-counting-sort-O(N)O(1)-timespace-100 | 2 | Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
Example 1:
Input: digits = [8,1,9]
Output: "981"
Example 2:
Input: digits = [8,6,7,1,0]
Output: "8760"
Example 3:
Input: digits = [1]
Output: ""
Constraints:
1 <= digits.length <= 104
0 <= digits[i] <= 9 | Clean Python 3, counting sort O(N)/O(1) time/space, 100% | 268 | largest-multiple-of-three | 0.333 | lenchen1112 | Hard | 20,499 | 1,363 |
how many numbers are smaller than the current number | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
a=[]
numi = sorted(nums)
for i in range(0,len(nums)):
a.append(numi.index(nums[i]))
return a | https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/613343/Simple-Python-Solution-72ms-and-13.8-MB-EXPLAINED | 10 | Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
Example 2:
Input: nums = [6,5,4,8]
Output: [2,1,0,3]
Example 3:
Input: nums = [7,7,7,7]
Output: [0,0,0,0]
Constraints:
2 <= nums.length <= 500
0 <= nums[i] <= 100 | Simple Python Solution [72ms and 13.8 MB] EXPLAINED | 849 | how-many-numbers-are-smaller-than-the-current-number | 0.867 | code_zero | Easy | 20,506 | 1,365 |
rank teams by votes | class Solution:
def rankTeams(self, votes: List[str]) -> str:
teamVotes = collections.defaultdict(lambda: [0] * 26)
for vote in votes:
for pos, team in enumerate(vote):
teamVotes[team][pos] += 1
return ''.join(sorted(teamVotes.keys(), reverse=True,
key=lambda team: (teamVotes[team], -ord(team)))) | https://leetcode.com/problems/rank-teams-by-votes/discuss/2129031/python-3-oror-simple-O(n)O(1)-solution | 5 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
You are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation:
Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.
Team B was ranked second by 2 voters and ranked third by 3 voters.
Team C was ranked second by 3 voters and ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team, and team B is the third.
Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation:
X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position.
Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter, so their votes are used for the ranking.
Constraints:
1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length for 0 <= i, j < votes.length.
votes[i][j] is an English uppercase letter.
All characters of votes[i] are unique.
All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length. | python 3 || simple O(n)/O(1) solution | 465 | rank-teams-by-votes | 0.586 | dereky4 | Medium | 20,554 | 1,366 |
linked list in binary tree | class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
#build longest prefix-suffix array
pattern, lps = [head.val], [0] #longest prefix-suffix array
j = 0
while head.next:
head = head.next
pattern.append(head.val)
while j and head.val != pattern[j]: j = lps[j-1]
if head.val == pattern[j]: j += 1
lps.append(j)
def dfs(root, i):
"""Return True of tree rooted at "root" match pattern"""
if i == len(pattern): return True
if not root: return False
while i > 0 and root.val != pattern[i]: i = lps[i-1]
if root.val == pattern[i]: i += 1
return dfs(root.left, i) or dfs(root.right, i)
return dfs(root, 0) | https://leetcode.com/problems/linked-list-in-binary-tree/discuss/525814/Python3-A-naive-dp-approach | 1 | Given a binary tree root and a linked list with head as the first node.
Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
Example 1:
Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Explanation: Nodes in blue form a subpath in the binary Tree.
Example 2:
Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Example 3:
Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: false
Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.
Constraints:
The number of nodes in the tree will be in the range [1, 2500].
The number of nodes in the list will be in the range [1, 100].
1 <= Node.val <= 100 for each node in the linked list and binary tree. | [Python3] A naive dp approach | 96 | linked-list-in-binary-tree | 0.435 | ye15 | Medium | 20,565 | 1,367 |
minimum cost to make at least one valid path in a grid | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
graph = {}
m, n = len(grid), len(grid[0])
def addEdges(i, j):
graph[(i, j)] = {}
neighbors = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
for each in neighbors:
x, y = each
if x < 0 or y < 0 or x > m - 1 or y > n - 1:
continue
else:
graph[(i, j)][(x, y)] = 1
if grid[i][j] == 1:
if j != n - 1:
graph[(i, j)][(i, j + 1)] = 0
elif grid[i][j] == 2:
if j != 0:
graph[(i, j)][(i, j - 1)] = 0
elif grid[i][j] == 3:
if i != m - 1:
graph[(i, j)][(i + 1, j)] = 0
else:
if i != 0:
graph[(i, j)][(i - 1, j)] = 0
for i in range(m):
for j in range(n):
addEdges(i, j)
# convert row, col to index value in distances array
def convert(x, y):
return x * n + y
def BFS(graph):
q = deque()
q.append([0, 0, 0])
distances = [float(inf)] * (m * n)
while q:
cost, x, y = q.popleft()
if (x, y) == (m - 1, n - 1):
return cost
idx = convert(x, y)
if distances[idx] < cost:
continue
distances[idx] = cost
for node, nxtCost in graph[(x, y)].items():
nxtIndex = convert(node[0], node[1])
if distances[nxtIndex] <= cost + nxtCost:
continue
distances[nxtIndex] = cost + nxtCost
if nxtCost == 0:
q.appendleft([cost, node[0], node[1]])
else:
q.append([cost + 1, node[0], node[1]])
def dijkstra(graph):
distances = [float(inf)] * (m * n)
myheap = [[0, 0, 0]]
#distances[0] = 0
while myheap:
cost, x, y = heappop(myheap)
if (x, y) == (m - 1, n - 1):
return cost
idx = convert(x, y)
if distances[idx] < cost:
continue
else:
distances[idx] = cost
for node, nxtCost in graph[(x, y)].items():
total = cost + nxtCost
nxtIndex = convert(node[0], node[1])
if distances[nxtIndex] <= total:
continue
else:
distances[nxtIndex] = total
heappush(myheap, [total, node[0], node[1]])
return distances[-1]
#return dijkstra(graph)
return BFS(graph) | https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1504913/Python-or-Template-or-0-1-BFS-vs-Dijkstra-or-Explanation | 3 | Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
Notice that there could be some signs on the cells of the grid that point outside the grid.
You will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
Example 1:
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
Example 2:
Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
Example 3:
Input: grid = [[1,2],[4,3]]
Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
1 <= grid[i][j] <= 4 | Python | Template | 0-1 BFS vs Dijkstra | Explanation | 290 | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0.613 | detective_dp | Hard | 20,573 | 1,368 |
increasing decreasing string | class Solution:
def sortString(self, s: str) -> str:
s = list(s)
# Big S: O(n)
result = []
# Logic is capture distinct char with set
# Remove found char from initial string
# Big O: O(n)
while len(s) > 0:
# Big O: O(n log n) Space: O(n)
smallest = sorted(set(s))
# Big O: O(s) - reduced set
for small in smallest:
result.append(small)
s.remove(small)
# Big O: O(n log n) Space: O(n)
largest = sorted(set(s), reverse = True)
# Big O: O(s) - reduced set
for large in largest:
result.append(large)
s.remove(large)
return ''.join(result)
# Summary: Big O(n)^2 Space: O(n) | https://leetcode.com/problems/increasing-decreasing-string/discuss/543172/Python-3-Using-Set-and-Sort-with-commentary | 11 | You are given a string s. Reorder the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.
Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Example 2:
Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters. | [Python 3] Using Set and Sort with commentary | 966 | increasing-decreasing-string | 0.774 | dentedghost | Easy | 20,582 | 1,370 |
find the longest substring containing vowels in even counts | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
ans = mask = 0
seen = {0: -1}
for i, c in enumerate(s):
if c in "aeiou":
mask ^= 1 << ("aeiou".find(c))
if mask in seen: ans = max(ans, i - seen[mask])
seen.setdefault(mask, i)
return ans | https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1125562/Python3-bitmask | 4 | Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
Example 2:
Input: s = "leetcodeisgreat"
Output: 5
Explanation: The longest substring is "leetc" which contains two e's.
Example 3:
Input: s = "bcbcbc"
Output: 6
Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
Constraints:
1 <= s.length <= 5 x 10^5
s contains only lowercase English letters. | [Python3] bitmask | 148 | find-the-longest-substring-containing-vowels-in-even-counts | 0.629 | ye15 | Medium | 20,609 | 1,371 |
longest zigzag path in a binary tree | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
LEFT = 0
RIGHT = 1
stack = []
if root.left:
stack.append((root.left, LEFT, 1))
if root.right:
stack.append((root.right, RIGHT, 1))
longest = 0
while stack:
node, direction, count = stack.pop()
longest = max(longest, count)
if direction == LEFT:
if node.left:
stack.append((node.left, LEFT, 1))
if node.right:
stack.append((node.right, RIGHT, count+1))
else:
if node.right:
stack.append((node.right, RIGHT, 1))
if node.left:
stack.append((node.left, LEFT, count+1))
return longest | https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2559539/Python3-Iterative-DFS-Using-Stack-99-time-91-space-O(N)-time-O(N)-space | 0 | You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to left or from left to right.
Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
Example 1:
Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output: 3
Explanation: Longest ZigZag path in blue nodes (right -> left -> right).
Example 2:
Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
Example 3:
Input: root = [1]
Output: 0
Constraints:
The number of nodes in the tree is in the range [1, 5 * 104].
1 <= Node.val <= 100 | [Python3] Iterative DFS Using Stack - 99% time 91% space, - O(N) time O(N) space | 35 | longest-zigzag-path-in-a-binary-tree | 0.598 | rt500 | Medium | 20,615 | 1,372 |
maximum sum bst in binary tree | class Solution:
def maxSumBST(self, root: TreeNode) -> int:
tot = -math.inf
def dfs(node):
nonlocal tot
if not node:
return 0, math.inf, -math.inf
l_res, l_min, l_max = dfs(node.left)
r_res, r_min, r_max = dfs(node.right)
# if maintains BST property
if l_max<node.val<r_min:
res = node.val + l_res + r_res
tot = max(tot, res)
# keep track the min and max values of the subtree
return res, min(l_min,node.val), max(r_max, node.val)
else:
return 0, -math.inf, math.inf
return max(dfs(root)[0], tot) | https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/1377976/Python-O(n)-short-readable-solution | 1 | Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.
Example 2:
Input: root = [4,3,null,1,2]
Output: 2
Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.
Example 3:
Input: root = [-4,-2,-5]
Output: 0
Explanation: All values are negatives. Return an empty BST.
Constraints:
The number of nodes in the tree is in the range [1, 4 * 104].
-4 * 104 <= Node.val <= 4 * 104 | Python O(n), short readable solution | 170 | maximum-sum-bst-in-binary-tree | 0.392 | arsamigullin | Hard | 20,624 | 1,373 |
generate a string with characters that have odd counts | class Solution:
def generateTheString(self, n: int) -> str:
a="a"
b="b"
if n%2==0:
return (((n-1)*a)+b)
return (n*a) | https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1232027/Easy-code-in-python-with-explanation. | 2 | Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
Example 1:
Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".
Example 2:
Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".
Example 3:
Input: n = 7
Output: "holasss"
Constraints:
1 <= n <= 500 | Easy code in python with explanation. | 183 | generate-a-string-with-characters-that-have-odd-counts | 0.776 | souravsingpardeshi | Easy | 20,630 | 1,374 |
number of times binary string is prefix aligned | class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
max = count = 0
for i in range(len(light)):
if max < light[i]:
max = light[i]
if max == i + 1:
count += 1
return count | https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/1330283/Python3-solution-O(n)-time-and-O(1)-space-complexity | 4 | You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step.
A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros.
Return the number of times the binary string is prefix-aligned during the flipping process.
Example 1:
Input: flips = [3,2,4,1,5]
Output: 2
Explanation: The binary string is initially "00000".
After applying step 1: The string becomes "00100", which is not prefix-aligned.
After applying step 2: The string becomes "01100", which is not prefix-aligned.
After applying step 3: The string becomes "01110", which is not prefix-aligned.
After applying step 4: The string becomes "11110", which is prefix-aligned.
After applying step 5: The string becomes "11111", which is prefix-aligned.
We can see that the string was prefix-aligned 2 times, so we return 2.
Example 2:
Input: flips = [4,1,2,3]
Output: 1
Explanation: The binary string is initially "0000".
After applying step 1: The string becomes "0001", which is not prefix-aligned.
After applying step 2: The string becomes "1001", which is not prefix-aligned.
After applying step 3: The string becomes "1101", which is not prefix-aligned.
After applying step 4: The string becomes "1111", which is prefix-aligned.
We can see that the string was prefix-aligned 1 time, so we return 1.
Constraints:
n == flips.length
1 <= n <= 5 * 104
flips is a permutation of the integers in the range [1, n]. | Python3 solution O(n) time and O(1) space complexity | 312 | number-of-times-binary-string-is-prefix-aligned | 0.659 | EklavyaJoshi | Medium | 20,652 | 1,375 |
time needed to inform all employees | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
def find(i):
if manager[i] != -1:
informTime[i] += find(manager[i])
manager[i] = -1
return informTime[i]
return max(map(find, range(n))) | https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1206574/Python3-Path-compression-(Clean-code-beats-99) | 10 | A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.
Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.
The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).
Return the number of minutes needed to inform all the employees about the urgent news.
Example 1:
Input: n = 1, headID = 0, manager = [-1], informTime = [0]
Output: 0
Explanation: The head of the company is the only employee in the company.
Example 2:
Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
Output: 1
Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.
Constraints:
1 <= n <= 105
0 <= headID < n
manager.length == n
0 <= manager[i] < n
manager[headID] == -1
informTime.length == n
0 <= informTime[i] <= 1000
informTime[i] == 0 if employee i has no subordinates.
It is guaranteed that all the employees can be informed. | [Python3] Path compression (Clean code, beats 99%) | 351 | time-needed-to-inform-all-employees | 0.584 | SPark9625 | Medium | 20,658 | 1,376 |
frog position after t seconds | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
if target==1:
if t>=1 and len(edges)>=1:
return 0
adj = collections.defaultdict(list)
for i in edges:
adj[min(i[0],i[1])].append(max(i[1],i[0]))
def traversal(curr, target,t):
if curr==target:
if t==0 or len(adj[curr])==0:
return 1
return 0
if t==0:
return 0
for child in adj[curr]:
prob = traversal(child, target, t-1)/len(adj[curr])
if prob>0:
return prob
return 0
return traversal(1,target,t) | https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1092590/Python-basic-DFS-from-a-new-grad | 1 | Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.
Return the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666.
Example 2:
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output: 0.3333333333333333
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1.
Constraints:
1 <= n <= 100
edges.length == n - 1
edges[i].length == 2
1 <= ai, bi <= n
1 <= t <= 50
1 <= target <= n | Python basic DFS from a new grad | 142 | frog-position-after-t-seconds | 0.361 | yb233 | Hard | 20,681 | 1,377 |
find a corresponding node of a binary tree in a clone of that tree | class Solution:
def getTargetCopy(self, node1: TreeNode, node2: TreeNode, target: TreeNode) -> TreeNode:
if not node1 or target == node1: # if node1 is null, node2 will also be null
return node2
return self.getTargetCopy(node1.left, node2.left, target) or self.getTargetCopy(node1.right, node2.right, target) | https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046151/Python-Simple-2-approaches-Recursion(3-liner)-and-Morris | 20 | Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.
Example 1:
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
Example 2:
Input: tree = [7], target = 7
Output: 7
Example 3:
Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4
Constraints:
The number of nodes in the tree is in the range [1, 104].
The values of the nodes of the tree are unique.
target node is a node from the original tree and is not null.
Follow up: Could you solve the problem if repeated values on the tree are allowed? | Python Simple 2 approaches - Recursion(3 liner) and Morris | 1,900 | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0.87 | constantine786 | Easy | 20,688 | 1,379 |
lucky numbers in a matrix | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
rmin = [min(x) for x in matrix]
cmax = [max(x) for x in zip(*matrix)]
return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0])) if rmin[i] == cmax[j]] | https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539748/Python3-store-row-min-and-column-max | 9 | Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
Example 1:
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 2:
Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
Example 3:
Input: matrix = [[7,8],[1,2]]
Output: [7]
Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
Constraints:
m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 105.
All elements in the matrix are distinct. | [Python3] store row min & column max | 1,500 | lucky-numbers-in-a-matrix | 0.705 | ye15 | Easy | 20,716 | 1,380 |
balance a binary search tree | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
"""inorder depth-first traverse bst"""
if not node: return
dfs(node.left)
value.append(node.val)
dfs(node.right)
value = [] #collect values
dfs(root)
def tree(lo, hi):
if lo > hi: return None
mid = (lo + hi)//2
ans = TreeNode(value[mid])
ans.left = tree(lo, mid-1)
ans.right = tree(mid+1, hi)
return ans
return tree(0, len(value)-1) | https://leetcode.com/problems/balance-a-binary-search-tree/discuss/539780/Python3-collect-values-and-reconstruct-bst-recursively | 6 | Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
Example 1:
Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.
Example 2:
Input: root = [2,1,3]
Output: [2,1,3]
Constraints:
The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 105 | [Python3] collect values & reconstruct bst recursively | 363 | balance-a-binary-search-tree | 0.807 | ye15 | Medium | 20,751 | 1,382 |
maximum performance of a team | class Solution:
def maxPerformance_simple(self, n, speed, efficiency):
people = sorted(zip(speed, efficiency), key=lambda x: -x[1])
result, sum_speed = 0, 0
for s, e in people:
sum_speed += s
result = max(result, sum_speed * e)
return result # % 1000000007 | https://leetcode.com/problems/maximum-performance-of-a-team/discuss/741822/Met-this-problem-in-my-interview!!!-(Python3-greedy-with-heap) | 58 | You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team with the maximum performance.
The performance of a team is the sum of its engineers' speeds multiplied by the minimum efficiency among its engineers.
Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.
Example 1:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
Output: 60
Explanation:
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.
Example 2:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
Output: 68
Explanation:
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.
Example 3:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
Output: 72
Constraints:
1 <= k <= n <= 105
speed.length == n
efficiency.length == n
1 <= speed[i] <= 105
1 <= efficiency[i] <= 108 | Met this problem in my interview!!! (Python3 greedy with heap) | 2,500 | maximum-performance-of-a-team | 0.489 | dashidhy | Hard | 20,764 | 1,383 |
find the distance value between two arrays | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
n = len(arr2)
arr2.sort()
res = 0
for num in arr1:
low, high = 0, n - 1
while low <= high:
mid = (low + high) // 2
if abs(num - arr2[mid]) <= d:
break
elif num < arr2[mid]:
high = mid - 1
else:
low = mid + 1
else:
res += 1
return res | https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2015283/python-3-oror-simple-binary-search-solution | 4 | Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.
The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.
Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Explanation:
For arr1[0]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1[1]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=2
Example 2:
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
Example 3:
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
Constraints:
1 <= arr1.length, arr2.length <= 500
-1000 <= arr1[i], arr2[j] <= 1000
0 <= d <= 100 | python 3 || simple binary search solution | 298 | find-the-distance-value-between-two-arrays | 0.654 | dereky4 | Easy | 20,782 | 1,385 |
cinema seat allocation | class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
seats = {}
for i, j in reservedSeats:
if i not in seats: seats[i] = 0
seats[i] |= 1 << j-1
ans = 2 * (n - len(seats))
for v in seats.values():
if not int("0111111110", 2) & v: ans += 2
elif not int("0111100000", 2) & v: ans += 1
elif not int("0001111000", 2) & v: ans += 1
elif not int("0000011110", 2) & v: ans += 1
return ans | https://leetcode.com/problems/cinema-seat-allocation/discuss/1124736/Python3-bitmask | 3 | A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.
Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
Example 1:
Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]
Output: 4
Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
Example 2:
Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]
Output: 2
Example 3:
Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]
Output: 4
Constraints:
1 <= n <= 10^9
1 <= reservedSeats.length <= min(10*n, 10^4)
reservedSeats[i].length == 2
1 <= reservedSeats[i][0] <= n
1 <= reservedSeats[i][1] <= 10
All reservedSeats[i] are distinct. | [Python3] bitmask | 256 | cinema-seat-allocation | 0.409 | ye15 | Medium | 20,818 | 1,386 |
sort integers by the power value | class Solution:
def getpower(self,num):
p=0
while(num!=1):
if num%2==0:
num=num//2
else:
num=(3*num)+1
p+=1
return p
def getKth(self, lo: int, hi: int, k: int) -> int:
temp=sorted(range(lo,hi+1),key=lambda x:self.getpower(x))
return temp[k-1]
``` | https://leetcode.com/problems/sort-integers-by-the-power-value/discuss/1597631/Python-using-sorted-function | 1 | The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:
if x is even then x = x / 2
if x is odd then x = 3 * x + 1
For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.
Return the kth integer in the range [lo, hi] sorted by the power value.
Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.
Example 1:
Input: lo = 12, hi = 15, k = 2
Output: 13
Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)
The power of 13 is 9
The power of 14 is 17
The power of 15 is 17
The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.
Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.
Example 2:
Input: lo = 7, hi = 11, k = 4
Output: 7
Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].
The interval sorted by power is [8, 10, 11, 7, 9].
The fourth number in the sorted array is 7.
Constraints:
1 <= lo <= hi <= 1000
1 <= k <= hi - lo + 1 | Python using sorted function | 118 | sort-integers-by-the-power-value | 0.7 | PrimeOp | Medium | 20,825 | 1,387 |
pizza with 3n slices | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
@cache
def fn(i, k, first):
"""Return max sum of k pieces from slices[i:]."""
if k == 0: return 0
if i >= len(slices) or first and i == len(slices)-1: return -inf
if i == 0: return max(fn(i+1, k, False), slices[i] + fn(i+2, k-1, True))
return max(fn(i+1, k, first), slices[i] + fn(i+2, k-1, first))
return fn(0, len(slices)//3, None) | https://leetcode.com/problems/pizza-with-3n-slices/discuss/1124752/Python3-top-down-dp | 2 | There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
Your friend Bob will pick the next slice in the clockwise direction of your pick.
Repeat until there are no more slices of pizzas.
Given an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.
Example 1:
Input: slices = [1,2,3,4,5,6]
Output: 10
Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
Example 2:
Input: slices = [8,9,8,6,1,1]
Output: 16
Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
Constraints:
3 * n == slices.length
1 <= slices.length <= 500
1 <= slices[i] <= 1000 | [Python3] top-down dp | 236 | pizza-with-3n-slices | 0.501 | ye15 | Hard | 20,852 | 1,388 |
create target array in the given order | class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
ans = []
for i in range(len(nums)):
ans.insert(index[i] , nums[i])
return ans | https://leetcode.com/problems/create-target-array-in-the-given-order/discuss/1163965/Python3-Simple-Solution | 5 | Given two arrays of integers nums and index. Your task is to create target array under the following rules:
Initially target array is empty.
From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
Repeat the previous step until there are no elements to read in nums and index.
Return the target array.
It is guaranteed that the insertion operations will be valid.
Example 1:
Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]
Output: [0,4,1,3,2]
Explanation:
nums index target
0 0 [0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
Example 2:
Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]
Output: [0,1,2,3,4]
Explanation:
nums index target
1 0 [1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
Example 3:
Input: nums = [1], index = [0]
Output: [1]
Constraints:
1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i | [Python3] Simple Solution | 252 | create-target-array-in-the-given-order | 0.859 | VoidCupboard | Easy | 20,857 | 1,389 |
four divisors | class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
res = 0
for num in nums:
divisor = set()
for i in range(1, floor(sqrt(num)) + 1):
if num % i == 0:
divisor.add(num//i)
divisor.add(i)
if len(divisor) > 4:
break
if len(divisor) == 4:
res += sum(divisor)
return res | https://leetcode.com/problems/four-divisors/discuss/547308/Python3-Short-Easy-Solution | 22 | Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.
Example 1:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
Example 2:
Input: nums = [21,21]
Output: 64
Example 3:
Input: nums = [1,2,3,4,5]
Output: 0
Constraints:
1 <= nums.length <= 104
1 <= nums[i] <= 105 | [Python3] Short Easy Solution | 2,500 | four-divisors | 0.413 | localhostghost | Medium | 20,910 | 1,390 |
check if there is a valid path in a grid | class Solution:
directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]
streetDirections = {
1: [1, 3],
2: [0, 2],
3: [2, 3],
4: [1, 2],
5: [0, 3],
6: [0, 1]
}
def hasValidPath(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
def dfs(i: int, j: int, oppositeDirection: int) -> None:
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] < 0:
return
v = grid[i][j]
sd = Solution.streetDirections[v]
direction = (oppositeDirection + 2) % 4
if direction not in sd:
return
grid[i][j] = -v
for d in sd:
delta = Solution.directions[d]
dfs(i+delta[0], j+delta[1], d)
dfs(0, 0, 0)
dfs(0, 0, 3)
return grid[m-1][n-1] < 0 | https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/discuss/635713/Python3-dfs-solution-Check-if-There-is-a-Valid-Path-in-a-Grid | 2 | You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:
1 which means a street connecting the left cell and the right cell.
2 which means a street connecting the upper cell and the lower cell.
3 which means a street connecting the left cell and the lower cell.
4 which means a street connecting the right cell and the lower cell.
5 which means a street connecting the left cell and the upper cell.
6 which means a street connecting the right cell and the upper cell.
You will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.
Notice that you are not allowed to change any street.
Return true if there is a valid path in the grid or false otherwise.
Example 1:
Input: grid = [[2,4,3],[6,5,2]]
Output: true
Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).
Example 2:
Input: grid = [[1,2,1],[1,2,1]]
Output: false
Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)
Example 3:
Input: grid = [[1,1,2]]
Output: false
Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6 | Python3 dfs solution - Check if There is a Valid Path in a Grid | 391 | check-if-there-is-a-valid-path-in-a-grid | 0.472 | r0bertz | Medium | 20,912 | 1,391 |
longest happy prefix | class Solution:
def longestPrefix(self, s: str) -> str:
n = [0] + [None] * (len(s) - 1)
for i in range(1, len(s)):
k = n[i - 1] # trying length k + 1
while (k > 0) and (s[i] != s[k]):
k = n[k - 1]
if s[i] == s[k]:
k += 1
n[i] = k
happy_border = n[-1]
return s[:happy_border] | https://leetcode.com/problems/longest-happy-prefix/discuss/2814375/Dynamic-programming-solution | 1 | A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Constraints:
1 <= s.length <= 105
s contains only lowercase English letters. | Dynamic programming solution | 24 | longest-happy-prefix | 0.45 | aknyazev87 | Hard | 20,919 | 1,392 |
find lucky integer in an array | class Solution:
def findLucky(self, arr: List[int]) -> int:
charMap = {}
for i in arr:
charMap[i] = 1 + charMap.get(i, 0)
res = []
for i in charMap:
if charMap[i] == i:
res.append(i)
res = sorted(res)
if len(res) > 0:
return res[-1]
return -1 | https://leetcode.com/problems/find-lucky-integer-in-an-array/discuss/2103066/PYTHON-or-Simple-python-solution | 1 | Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.
Return the largest lucky integer in the array. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Constraints:
1 <= arr.length <= 500
1 <= arr[i] <= 500 | PYTHON | Simple python solution | 145 | find-lucky-integer-in-an-array | 0.636 | shreeruparel | Easy | 20,928 | 1,394 |
count number of teams | class Solution:
def numTeams(self, rating: List[int]) -> int:
dp = [[1, 0, 0] for i in range(len(rating))]
for i in range(1, len(rating)):
for j in range(i):
if rating[i] > rating[j]:
dp[i][1] += dp[j][0]
dp[i][2] += dp[j][1]
a = sum(dp[i][2] for i in range(len(dp)))
#print(a)
dp = [[1, 0, 0] for i in range(len(rating))]
for i in range(1, len(rating)):
for j in range(i):
if rating[i] < rating[j]:
dp[i][1] += dp[j][0]
dp[i][2] += dp[j][1]
b = sum(dp[i][2] for i in range(len(dp)))
return a + b | https://leetcode.com/problems/count-number-of-teams/discuss/1465532/Python-or-O(n2)-or-Slow-but-very-easy-to-understand-or-Explanation | 5 | There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
Example 1:
Input: rating = [2,5,3,4,1]
Output: 3
Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
Example 2:
Input: rating = [2,1,3]
Output: 0
Explanation: We can't form any team given the conditions.
Example 3:
Input: rating = [1,2,3,4]
Output: 4
Constraints:
n == rating.length
3 <= n <= 1000
1 <= rating[i] <= 105
All the integers in rating are unique. | Python | O(n^2) | Slow but very easy to understand | Explanation | 595 | count-number-of-teams | 0.68 | detective_dp | Medium | 20,963 | 1,395 |
find all good strings | class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
lps = [0]
k = 0
for i in range(1, len(evil)):
while k and evil[k] != evil[i]: k = lps[k-1]
if evil[k] == evil[i]: k += 1
lps.append(k)
@cache
def fn(i, k, lower, upper):
"""Return number of good strings at position i and k prefix match."""
if k == len(evil): return 0 # boundary condition
if i == n: return 1
lo = ascii_lowercase.index(s1[i]) if lower else 0
hi = ascii_lowercase.index(s2[i]) if upper else 25
ans = 0
for x in range(lo, hi+1):
kk = k
while kk and evil[kk] != ascii_lowercase[x]:
kk = lps[kk-1]
if evil[kk] == ascii_lowercase[x]: kk += 1
ans += fn(i+1, kk, lower and x == lo, upper and x == hi)
return ans
return fn(0, 0, True, True) % 1_000_000_007 | https://leetcode.com/problems/find-all-good-strings/discuss/1133347/Python3-dp-and-kmp-...-finally | 3 | Given the strings s1 and s2 of size n and the string evil, return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.
Example 1:
Input: n = 2, s1 = "aa", s2 = "da", evil = "b"
Output: 51
Explanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".
Example 2:
Input: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"
Output: 0
Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.
Example 3:
Input: n = 2, s1 = "gx", s2 = "gz", evil = "x"
Output: 2
Constraints:
s1.length == n
s2.length == n
s1 <= s2
1 <= n <= 500
1 <= evil.length <= 50
All strings consist of lowercase English letters. | [Python3] dp & kmp ... finally | 351 | find-all-good-strings | 0.422 | ye15 | Hard | 20,973 | 1,397 |
count largest group | class Solution:
def countLargestGroup(self, n: int) -> int:
dp = {0: 0}
counts = [0] * (4 * 9)
for i in range(1, n + 1):
quotient, reminder = divmod(i, 10)
dp[i] = reminder + dp[quotient]
counts[dp[i] - 1] += 1
return counts.count(max(counts)) | https://leetcode.com/problems/count-largest-group/discuss/660765/Python-DP-O(N)-99100 | 43 | You are given an integer n.
Each number from 1 to n is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
Example 1:
Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].
There are 4 groups with largest size.
Example 2:
Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.
Constraints:
1 <= n <= 104 | Python DP O(N) 99%/100% | 2,000 | count-largest-group | 0.672 | xshoan | Easy | 20,975 | 1,399 |
construct k palindrome strings | class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if k > len(s):
return False
dic = {}
for i in s:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
c = 0
for i in dic.values():
if i % 2 == 1:
c += 1
if c > k:
return False
return True | https://leetcode.com/problems/construct-k-palindrome-strings/discuss/1806250/Python-Solution | 1 | Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.
Example 1:
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"
Example 2:
Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.
Example 3:
Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= 105 | Python Solution | 91 | construct-k-palindrome-strings | 0.632 | MS1301 | Medium | 20,995 | 1,400 |
circle and rectangle overlapping | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
x = 0 if x1 <= x_center <= x2 else min(abs(x1-x_center), abs(x2-x_center))
y = 0 if y1 <= y_center <= y2 else min(abs(y1-y_center), abs(y2-y_center))
return x**2 + y**2 <= radius**2 | https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/639682/Python3-two-solutions-Circle-and-Rectangle-Overlapping | 2 | You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.
Return true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.
Example 1:
Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
Output: true
Explanation: Circle and rectangle share the point (1,0).
Example 2:
Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
Output: false
Example 3:
Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
Output: true
Constraints:
1 <= radius <= 2000
-104 <= xCenter, yCenter <= 104
-104 <= x1 < x2 <= 104
-104 <= y1 < y2 <= 104 | Python3 two solutions - Circle and Rectangle Overlapping | 386 | circle-and-rectangle-overlapping | 0.442 | r0bertz | Medium | 21,001 | 1,401 |
reducing dishes | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort(reverse=True)
maxSatisfaction = dishSum = 0
for dish in satisfaction:
dishSum += dish
if dishSum <= 0:
break
maxSatisfaction += dishSum
return maxSatisfaction | https://leetcode.com/problems/reducing-dishes/discuss/2152786/python-3-oror-simple-sorting-solution | 1 | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].
Return the maximum sum of like-time coefficient that the chef can obtain after preparing some amount of dishes.
Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
Example 1:
Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.
Example 2:
Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:
Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.
Constraints:
n == satisfaction.length
1 <= n <= 500
-1000 <= satisfaction[i] <= 1000 | python 3 || simple sorting solution | 102 | reducing-dishes | 0.72 | dereky4 | Hard | 21,005 | 1,402 |
minimum subsequence in non increasing order | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
l = []
while sum(l) <= sum(nums):
l.append(nums.pop())
return l | https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1041468/Python3-simple-solution | 9 | Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.
Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.
Example 1:
Input: nums = [4,3,10,9,8]
Output: [10,9]
Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements.
Example 2:
Input: nums = [4,4,7,6,7]
Output: [7,7,6]
Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 100 | Python3 simple solution | 297 | minimum-subsequence-in-non-increasing-order | 0.721 | EklavyaJoshi | Easy | 21,020 | 1,403 |
number of steps to reduce a number in binary representation to one | class Solution:
def numSteps(self, s):
return len(s) + s.rstrip('0').count('0') + 2 * (s.count('1') != 1) - 1 | https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2809472/Python3-Solution-or-One-Line | 1 | Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
Example 1:
Input: s = "1101"
Output: 6
Explanation: "1101" corressponds to number 13 in their decimal representation.
Step 1) 13 is odd, add 1 and obtain 14.
Step 2) 14 is even, divide by 2 and obtain 7.
Step 3) 7 is odd, add 1 and obtain 8.
Step 4) 8 is even, divide by 2 and obtain 4.
Step 5) 4 is even, divide by 2 and obtain 2.
Step 6) 2 is even, divide by 2 and obtain 1.
Example 2:
Input: s = "10"
Output: 1
Explanation: "10" corressponds to number 2 in their decimal representation.
Step 1) 2 is even, divide by 2 and obtain 1.
Example 3:
Input: s = "1"
Output: 0
Constraints:
1 <= s.length <= 500
s consists of characters '0' or '1'
s[0] == '1' | ✔ Python3 Solution | One Line | 98 | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | 0.522 | satyam2001 | Medium | 21,056 | 1,404 |
longest happy string | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
count = collections.Counter({'a':a, 'b':b, 'c':c})
res = ['#']
while True:
(a1, _), (a2, _) = count.most_common(2)
if a1 == res[-1] == res[-2]:
a1 = a2
if not count[a1]:
break
res.append(a1)
count[a1] -= 1
return ''.join(res[1:]) | https://leetcode.com/problems/longest-happy-string/discuss/1226968/Python-9-line-greedy-solution-by-using-Counter | 5 | A string s is called happy if it satisfies the following conditions:
s only contains the letters 'a', 'b', and 'c'.
s does not contain any of "aaa", "bbb", or "ccc" as a substring.
s contains at most a occurrences of the letter 'a'.
s contains at most b occurrences of the letter 'b'.
s contains at most c occurrences of the letter 'c'.
Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100
a + b + c > 0 | [Python] 9-line greedy solution by using Counter | 524 | longest-happy-string | 0.574 | licpotis | Medium | 21,069 | 1,405 |
stone game iii | class Solution(object):
def stoneGameIII(self, stoneValue):
"""
:type stoneValue: List[int]
:rtype: str
"""
dp = [0 for _ in range(len(stoneValue))]
if len(dp) >= 1:
dp[-1] = stoneValue[-1]
if len(dp) >= 2:
dp[-2] = max(stoneValue[-1] + stoneValue[-2], stoneValue[-2] - dp[-1])
if len(dp) >= 3:
dp[-3] = max(stoneValue[-3] + stoneValue[-1] + stoneValue[-2], stoneValue[-3] - dp[-2], stoneValue[-3] + stoneValue[-2] - dp[-1])
for i in range(len(stoneValue) - 4, -1, -1):
dp[i] = max([sum(stoneValue[i: i + j]) - dp[i + j] for j in range(1, 4)])
if dp[0] > 0:
return "Alice"
if dp[0] == 0:
return "Tie"
return "Bob" | https://leetcode.com/problems/stone-game-iii/discuss/815655/Python3-beats-93-DP | 4 | Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.
The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
Assume Alice and Bob play optimally.
Return "Alice" if Alice will win, "Bob" if Bob will win, or "Tie" if they will end the game with the same score.
Example 1:
Input: stoneValue = [1,2,3,7]
Output: "Bob"
Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.
Example 2:
Input: stoneValue = [1,2,3,-9]
Output: "Alice"
Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.
If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.
If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.
Remember that both play optimally so here Alice will choose the scenario that makes her win.
Example 3:
Input: stoneValue = [1,2,3,6]
Output: "Tie"
Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.
Constraints:
1 <= stoneValue.length <= 5 * 104
-1000 <= stoneValue[i] <= 1000 | Python3 beats 93% DP | 166 | stone-game-iii | 0.596 | ethuoaiesec | Hard | 21,082 | 1,406 |
string matching in an array | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
def add(word: str):
node = trie
for c in word:
node = node.setdefault(c, {})
def get(word: str) -> bool:
node = trie
for c in word:
if (node := node.get(c)) is None: return False
return True
words.sort(key=len, reverse=True)
trie, result = {}, []
for word in words:
if get(word): result.append(word)
for i in range(len(word)):
add(word[i:])
return result | https://leetcode.com/problems/string-matching-in-an-array/discuss/575147/Clean-Python-3-suffix-trie-O(NlogN-%2B-N-*-S2) | 48 | Given an array of string words, return all strings in words that is a substring of another word. You can return the answer in any order.
A substring is a contiguous sequence of characters within a string
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Explanation: No string of words is substring of another string.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i] contains only lowercase English letters.
All the strings of words are unique. | Clean Python 3, suffix trie O(NlogN + N * S^2) | 5,500 | string-matching-in-an-array | 0.639 | lenchen1112 | Easy | 21,089 | 1,408 |
queries on a permutation with key | class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
permuteArr=[i for i in range(1,m+1)]
query_len=len(queries)
answer=[]
left,right=[],[]
for query in range(query_len):
index=permuteArr.index(queries[query])
answer.append(index)
left=permuteArr[:index]
right=permuteArr[index+1:]
permuteArr=[permuteArr[index]]+left+right
return answer | https://leetcode.com/problems/queries-on-a-permutation-with-key/discuss/1702309/Understandable-code-for-beginners-in-python!!! | 1 | Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].
Return an array containing the result for the given queries.
Example 1:
Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1]
Explanation: The queries are processed as follow:
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].
Therefore, the array containing the result is [2,1,2,1].
Example 2:
Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]
Example 3:
Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]
Constraints:
1 <= m <= 10^3
1 <= queries.length <= m
1 <= queries[i] <= m | Understandable code for beginners in python!!! | 46 | queries-on-a-permutation-with-key | 0.833 | kabiland | Medium | 21,128 | 1,409 |
html entity parser | class Solution:
def entityParser(self, text: str) -> str:
html_symbol = [ '&quot;', '&apos;', '&gt;', '&lt;', '&frasl;', '&amp;']
formal_symbol = [ '"', "'", '>', '<', '/', '&']
for html_sym, formal_sym in zip(html_symbol, formal_symbol):
text = text.replace( html_sym , formal_sym )
return text | https://leetcode.com/problems/html-entity-parser/discuss/575248/Python-sol-by-replace-and-regex.-85%2B-w-Hint | 11 | HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
Quotation Mark: the entity is " and symbol character is ".
Single Quote Mark: the entity is ' and symbol character is '.
Ampersand: the entity is & and symbol character is &.
Greater Than Sign: the entity is > and symbol character is >.
Less Than Sign: the entity is < and symbol character is <.
Slash: the entity is ⁄ and symbol character is /.
Given the input text string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
Example 1:
Input: text = "& is an HTML entity but &ambassador; is not."
Output: "& is an HTML entity but &ambassador; is not."
Explanation: The parser will replace the & entity by &
Example 2:
Input: text = "and I quote: "...""
Output: "and I quote: \"...\""
Constraints:
1 <= text.length <= 105
The string may contain any possible characters out of all the 256 ASCII characters. | Python sol by replace and regex. 85%+ [w/ Hint ] | 740 | html-entity-parser | 0.52 | brianchiang_tw | Medium | 21,141 | 1,410 |
number of ways to paint n × 3 grid | class Solution:
def numOfWays(self, n: int) -> int:
mod = 10 ** 9 + 7
two_color, three_color = 6, 6
for _ in range(n - 1):
two_color, three_color = (two_color * 3 + three_color * 2) % mod, (two_color * 2 + three_color * 2) % mod
return (two_color + three_color) % mod | https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/1648004/dynamic-programming-32ms-beats-99.44-in-Python | 2 | You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).
Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.
Example 1:
Input: n = 1
Output: 12
Explanation: There are 12 possible way to paint the grid as shown.
Example 2:
Input: n = 5000
Output: 30228214
Constraints:
n == grid.length
1 <= n <= 5000 | dynamic programming, 32ms, beats 99.44% in Python | 205 | number-of-ways-to-paint-n-3-grid | 0.623 | kryuki | Hard | 21,149 | 1,411 |
minimum value to get positive step by step sum | class Solution:
def minStartValue(self, nums: List[int]) -> int:
for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1]
return 1 if min(nums) >= 1 else abs(min(nums)) + 1 | https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/discuss/1431774/2-Lines-Easy-Python-Solution | 5 | Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1 | (5 -3 ) = 2 | -3
(1 +2 ) = 3 | (2 +2 ) = 4 | 2
(3 -3 ) = 0 | (4 -3 ) = 1 | -3
(0 +4 ) = 4 | (1 +4 ) = 5 | 4
(4 +2 ) = 6 | (5 +2 ) = 7 | 2
Example 2:
Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive.
Example 3:
Input: nums = [1,-2,-3]
Output: 5
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100 | 2 Lines Easy Python Solution | 305 | minimum-value-to-get-positive-step-by-step-sum | 0.68 | caffreyu | Easy | 21,154 | 1,413 |
find the minimum number of fibonacci numbers whose sum is k | class Solution:
def findMinFibonacciNumbers(self, n: int) -> int:
def check(z):
key = [1,1]
while key[-1] + key[-2] <= z:
key.append(key[-1]+key[-2])
print(key,z)
if z in key:
return 1
return 1 + check(z-key[-1])
return check(n) | https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/1341772/Python3-easy-solution-using-recursion | 1 | Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 109 | Python3 easy solution using recursion | 333 | find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k | 0.654 | EklavyaJoshi | Medium | 21,193 | 1,414 |
the k th lexicographical string of all happy strings of length n | class Solution:
def getHappyString(self, n: int, k: int) -> str:
char = ["a", "b", "c"]
# Edge case, n = 1
if n == 1: return char[k - 1] if k <= 3 else ""
# There will be $part$ number of strings starting with each character (a, b, c)
part = 2 ** (n - 1)
# If k is too large
if k > part * 3: return ""
res = []
# Edge case is k = n * i, where i is an integer in range [1, 3]
res.append(char[k // part if k % part != 0 else k // part - 1])
k = k % part if k % part != 0 else part
for i in range(n - 2, -1, -1):
char = ["a", "b", "c"]
char.remove(res[-1]) # Make sure the adjacent characters will be different
if len(res) + 1 == n: # Edge case, assigning the last element
if k == 1: res.append(char[0])
elif k == 2: res.append(char[-1])
elif k > 2 ** i: # Go to the right side
res.append(char[-1])
k -= 2 ** i
else: res.append(char[0]) # Go to the left side
return "".join(res) | https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1420200/Python3-or-Ez-for-loop-solves-ALL!-With-detailed-comments-and-graphical-examples | 2 | A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k happy strings of length n.
Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"
Constraints:
1 <= n <= 10
1 <= k <= 100 | Python3 | Ez for loop solves ALL! With detailed comments and graphical examples | 73 | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 0.721 | caffreyu | Medium | 21,202 | 1,415 |
restore the array | class Solution(object):
def numberOfArrays(self, s, k):
n=len(s)
new=[0]*n
new[0]=1
m=len(str(k))
for i in range(1,n):
for j in range(max(0,i-m+1),i+1):
if s[j]!="0" and int(s[j:i+1])<=k:
if j==0:
new[i]=1
else:
new[i]+=new[j-1]
#print(new)
return new[-1]%(10**9+7) | https://leetcode.com/problems/restore-the-array/discuss/1165871/python-or-simple-dp | 1 | A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: s = "1000", k = 10000
Output: 1
Explanation: The only possible array is [1000]
Example 2:
Input: s = "1000", k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
Example 3:
Input: s = "1317", k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
Constraints:
1 <= s.length <= 105
s consists of only digits and does not contain leading zeros.
1 <= k <= 109 | python | simple dp | 185 | restore-the-array | 0.388 | heisenbarg | Hard | 21,218 | 1,416 |
reformat the string | class Solution:
def reformat(self, s: str) -> str:
nums, chars = [], []
[(chars, nums)[char.isdigit()].append(str(char)) for char in s]
nums_len, chars_len = len(nums), len(chars)
if 2 > nums_len - chars_len > -2:
a, b = ((chars, nums), (nums, chars))[nums_len > chars_len]
return reduce(lambda x, y: x + y[0] + y[1], itertools.zip_longest(a, b, fillvalue=''), '')
return '' | https://leetcode.com/problems/reformat-the-string/discuss/1863653/Python3-Solution | 1 | You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return the reformatted string or return an empty string if it is impossible to reformat the string.
Example 1:
Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.
Example 3:
Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits. | Python3 Solution | 62 | reformat-the-string | 0.556 | hgalytoby | Easy | 21,220 | 1,417 |
display table of food orders in a restaurant | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
order = defaultdict(lambda : {})
foods = set()
ids = []
for i , t , name in orders:
t = int(t)
if(name in order[t]):
order[t][name] += 1
else:
order[t][name] = 1
if(int(t) not in ids):
ids.append(int(t))
foods.add(name)
ids.sort()
foods = list(foods)
foods.sort()
tables = [['Table'] + foods]
k = 0
order = dict(sorted(order.items() , key=lambda x: x[0]))
for _ , j in order.items():
ans = [str(ids[k])]
for i in foods:
if(i in j):
ans.append(str(j[i]))
else:
ans.append("0")
tables.append(ans)
k += 1
return tables | https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1236252/Python3-Brute-Force-Solution | 3 | Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
Example 1:
Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]]
Explanation:
The displaying table looks like:
Table,Beef Burrito,Ceviche,Fried Chicken,Water
3 ,0 ,2 ,1 ,0
5 ,0 ,1 ,0 ,1
10 ,1 ,0 ,0 ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito".
Example 2:
Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]
Explanation:
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
Example 3:
Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
Output: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
Constraints:
1 <= orders.length <= 5 * 10^4
orders[i].length == 3
1 <= customerNamei.length, foodItemi.length <= 20
customerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.
tableNumberi is a valid integer between 1 and 500. | [Python3] Brute Force Solution | 163 | display-table-of-food-orders-in-a-restaurant | 0.738 | VoidCupboard | Medium | 21,241 | 1,418 |
minimum number of frogs croaking | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
cnt, s = collections.defaultdict(int), 'croak'
ans, cur, d = 0, 0, {c:i for i, c in enumerate(s)} # d: mapping for letter & its index
for letter in croakOfFrogs: # iterate over the string
if letter not in s: return -1 # if any letter other than "croak" is met, then invalid
cnt[letter] += 1 # increase cnt for letter
if letter == 'c': cur += 1 # 'c' is met, increase current ongoing croak `cur`
elif cnt[s[d[letter]-1]] <= 0: return -1 # if previous character fall below to 0, return -1
else: cnt[s[d[letter]-1]] -= 1 # otherwise, decrease cnt for previous character
ans = max(ans, cur) # update answer using `cur`
if letter == 'k': # when 'k' is met, decrease cnt and cur
cnt[letter] -= 1
cur -= 1
return ans if not cur else -1 # return ans if current ongoing "croak" is 0 | https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/1200924/Python-3-or-Greedy-Simulation-Clean-code-or-Explanantion | 6 | You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Constraints:
1 <= croakOfFrogs.length <= 105
croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'. | Python 3 | Greedy, Simulation, Clean code | Explanantion | 384 | minimum-number-of-frogs-croaking | 0.501 | idontknoooo | Medium | 21,250 | 1,419 |
build array where you can find the maximum exactly k comparisons | class Solution:
def numOfArrays(self, n: int, m: int, K: int) -> int:
MOD = 10 ** 9 + 7
# f[i][j][k] cumulative sum, first i elements, current max less than or equal to j, k more maximum to fill
f = [[[0 for _ in range(K + 1)] for _ in range(m + 1)] for _ in range(n + 1)]
for j in range(m + 1):
f[0][j][K] = 1
for i in range(n + 1):
for j in range(1, m + 1):
for k in range(K):
# prev value a[i] <= pref high a[i] = j refresh high
f[i][j][k] = (f[i][j - 1][k] + j * (f[i - 1][j][k] - f[i - 1][j - 1][k]) + f[i - 1][j - 1][k + 1]) % MOD
return f[n][m][0] | https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/2785539/Python-DP-cleaner-than-most-answers | 0 | You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr has exactly n integers.
1 <= arr[i] <= m where (0 <= i < n).
After applying the mentioned algorithm to arr, the value search_cost is equal to k.
Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.
Example 1:
Input: n = 2, m = 3, k = 1
Output: 6
Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
Example 2:
Input: n = 5, m = 2, k = 3
Output: 0
Explanation: There are no possible arrays that satisfy the mentioned conditions.
Example 3:
Input: n = 9, m = 1, k = 1
Output: 1
Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n | [Python] DP cleaner than most answers | 4 | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | 0.635 | chaosrw | Hard | 21,256 | 1,420 |
maximum score after splitting a string | class Solution:
def maxScore(self, s: str) -> int:
zeros = ones = 0
ans = float("-inf")
for i in range(len(s)-1):
if s[i] == "0": zeros += 1
else: ones -= 1
ans = max(ans, zeros + ones)
return ans - ones + (1 if s[-1] == "1" else 0) | https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/597944/Python3-linear-scan | 5 | Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
Example 1:
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
Example 3:
Input: s = "1111"
Output: 3
Constraints:
2 <= s.length <= 500
The string s consists of characters '0' and '1' only. | [Python3] linear scan | 482 | maximum-score-after-splitting-a-string | 0.578 | ye15 | Easy | 21,260 | 1,422 |
maximum points you can obtain from cards | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
total = sum(cardPoints)
remaining_length = n - k
subarray_sum = sum(cardPoints[:remaining_length])
min_sum = subarray_sum
for i in range(remaining_length, n):
# Update the sliding window sum to the subarray ending at index i
subarray_sum += cardPoints[i]
subarray_sum -= cardPoints[i - remaining_length]
# Update min_sum to track the overall minimum sum so far
min_sum = min(min_sum, subarray_sum)
return total - min_sum | https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2197728/Python3-O(n)-Clean-and-Simple-Sliding-Window-Solution | 38 | There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum score you can obtain.
Example 1:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
Example 2:
Input: cardPoints = [2,2,2], k = 2
Output: 4
Explanation: Regardless of which two cards you take, your score will always be 4.
Example 3:
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
Explanation: You have to take all the cards. Your score is the sum of points of all cards.
Constraints:
1 <= cardPoints.length <= 105
1 <= cardPoints[i] <= 104
1 <= k <= cardPoints.length | [Python3] O(n) - Clean and Simple Sliding Window Solution | 2,200 | maximum-points-you-can-obtain-from-cards | 0.523 | TLDRAlgos | Medium | 21,278 | 1,423 |
diagonal traverse ii | class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
d = collections.defaultdict(list)
for i in range(len(nums)):
for j in range(len(nums[i])):
d[(i+j)].append(nums[i][j])
ans = []
for key in d:
ans += d[key][::-1]
return ans | https://leetcode.com/problems/diagonal-traverse-ii/discuss/1866412/Python-easy-to-read-and-understand-or-hashmap | 0 | Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Example 1:
Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]
Example 2:
Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
Constraints:
1 <= nums.length <= 105
1 <= nums[i].length <= 105
1 <= sum(nums[i].length) <= 105
1 <= nums[i][j] <= 105 | Python easy to read and understand | hashmap | 58 | diagonal-traverse-ii | 0.504 | sanial2001 | Medium | 21,330 | 1,424 |
constrained subsequence sum | class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [0]*n
q = deque()
for i, num in enumerate(nums):
if i > k and q[0] == dp[i-k-1]:
q.popleft()
dp[i] = max(q[0] if q else 0, 0)+num
while q and q[-1] < dp[i]:
q.pop()
q.append(dp[i])
return max(dp) | https://leetcode.com/problems/constrained-subsequence-sum/discuss/2672473/Python-or-Deque | 0 | Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104 | Python | Deque | 6 | constrained-subsequence-sum | 0.474 | jainsiddharth99 | Hard | 21,332 | 1,425 |
kids with the greatest number of candies | class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [x+extraCandies >= max(candies) for x in candies] | https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/discuss/2269844/Python-3-ONE-LINER | 6 | There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.
Note that multiple kids can have the greatest number of candies.
Example 1:
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
Example 2:
Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
Example 3:
Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
Constraints:
n == candies.length
2 <= n <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50 | Python 3 [ONE LINER] | 143 | kids-with-the-greatest-number-of-candies | 0.875 | omkarxpatel | Easy | 21,339 | 1,431 |
max difference you can get from changing an integer | class Solution:
def maxDiff(self, num: int) -> int:
num = str(num)
i = next((i for i in range(len(num)) if num[i] != "9"), -1) #first non-9 digit
hi = int(num.replace(num[i], "9"))
if num[0] != "1": lo = int(num.replace(num[0], "1"))
else:
i = next((i for i in range(len(num)) if num[i] not in "01"), -1)
lo = int(num.replace(num[i], "0") if i > 0 else num)
return hi - lo | https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/discuss/608687/Python3-scan-through-digits | 4 | You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Constraints:
1 <= num <= 108 | [Python3] scan through digits | 151 | max-difference-you-can-get-from-changing-an-integer | 0.429 | ye15 | Medium | 21,387 | 1,432 |
check if a string can break another string | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
return all(a<=b for a,b in zip(min(sorted(s1),sorted(s2)),max(sorted(s1),sorted(s2))))``` | https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/1415509/ONLY-CODE-N-log-N-sort-and-compare-%3A)-clean-3-liner-and-then-1-liner | 1 | Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.
Example 1:
Input: s1 = "abc", s2 = "xya"
Output: true
Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
Example 2:
Input: s1 = "abe", s2 = "acd"
Output: false
Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
Example 3:
Input: s1 = "leetcodee", s2 = "interview"
Output: true
Constraints:
s1.length == n
s2.length == n
1 <= n <= 10^5
All strings consist of lowercase English letters. | [ONLY CODE] N log N sort and compare :) clean 3 liner and then 1 liner | 60 | check-if-a-string-can-break-another-string | 0.689 | yozaam | Medium | 21,392 | 1,433 |
number of ways to wear different hats to each other | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
n = len(hats)
h2p = collections.defaultdict(list)
for p, hs in enumerate(hats):
for h in hs:
h2p[h].append(p)
full_mask = (1 << n) - 1
mod = 10**9 + 7
@functools.lru_cache(maxsize=None)
def count(h, mask):
# everyone wears a hat
if mask == full_mask:
return 1
# ran out of hats
if h == 41:
return 0
# skip the current hat h
ans = count(h + 1, mask)
for p in h2p[h]:
# if person p already has a hat
if mask & (1 << p):
continue
# let person p wear hat h
ans += count(h + 1, mask | (1 << p))
ans %= mod
return ans
# start from the first hat and no one wearing any hat
return count(1, 0) | https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608721/Python-dp-with-bit-mask-memorization | 2 | There are n people and 40 types of hats labeled from 1 to 40.
Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.
Return the number of ways that the n people wear different hats to each other.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: hats = [[3,4],[4,5],[5]]
Output: 1
Explanation: There is only one way to choose hats given the conditions.
First person choose hat 3, Second person choose hat 4 and last one hat 5.
Example 2:
Input: hats = [[3,5,1],[3,5]]
Output: 4
Explanation: There are 4 ways to choose hats:
(3,5), (5,3), (1,3) and (1,5)
Example 3:
Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Output: 24
Explanation: Each person can choose hats labeled from 1 to 4.
Number of Permutations of (1,2,3,4) = 24.
Constraints:
n == hats.length
1 <= n <= 10
1 <= hats[i].length <= 40
1 <= hats[i][j] <= 40
hats[i] contains a list of unique integers. | Python dp with bit mask memorization | 246 | number-of-ways-to-wear-different-hats-to-each-other | 0.429 | ChelseaChenC | Hard | 21,407 | 1,434 |
destination city | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
lst=[]
arr=[]
for i in paths:
lst.append(i[0])
arr.append(i[1])
ptr=set(lst)
ptr2=set(arr)
return list(ptr2-ptr)[0] | https://leetcode.com/problems/destination-city/discuss/1664716/98-faster-easy-python-solution-based-on-question-no.-997 | 9 | You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
Example 1:
Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output: "Sao Paulo"
Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".
Example 2:
Input: paths = [["B","C"],["D","B"],["C","A"]]
Output: "A"
Explanation: All possible trips are:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
Clearly the destination city is "A".
Example 3:
Input: paths = [["A","Z"]]
Output: "Z"
Constraints:
1 <= paths.length <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
All strings consist of lowercase and uppercase English letters and the space character. | 98% faster easy python solution based on question no. 997 | 437 | destination-city | 0.776 | amannarayansingh10 | Easy | 21,411 | 1,436 |
check if all 1s are at least length k places away | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
indices = [i for i, x in enumerate(nums) if x == 1]
if not indices:
return True
for i in range(1, len(indices)):
if indices[i] - indices[i-1] < k + 1:
return False
return True | https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609823/Python-O(n)-Easy-(For-Loop-List-Comprehension) | 2 | Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.
Example 1:
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Example 2:
Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Constraints:
1 <= nums.length <= 105
0 <= k <= nums.length
nums[i] is 0 or 1 | Python O(n) Easy (For Loop, List Comprehension) | 180 | check-if-all-1s-are-at-least-length-k-places-away | 0.591 | sonaksh | Easy | 21,442 | 1,437 |
longest continuous subarray with absolute diff less than or equal to limit | class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
#[8,2,4,3,6,11] limit = 5
#if the new number is greater than max this becomes new max,
#if new number is less than min this becomes new min
#if max - min exceeds limit, pop the left most element -> if the left most element was max or min, recompute max - min and see if it goes limit
q = []
min_heap = []
max_heap = []
max_ans = 1
popped_index = set()
for i,v in enumerate(nums):
q.append((v,i))
# max_ans = max(max_ans,len(q))
heapq.heappush(min_heap,(v,i))
heapq.heappush(max_heap,(v*-1,i))
while(max_heap[0][0]*-1 - min_heap[0][0] > limit):
temp = q.pop(0)
popped_ele = temp[0]
popped_index.add(temp[1])
while(min_heap[0][1] in popped_index):
heapq.heappop(min_heap)
while(max_heap[0][1] in popped_index):
heapq.heappop(max_heap)
if len(q) > max_ans:
max_ans = len(q)
return max_ans | https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/2798749/nlogn-solution-by-this-dude | 0 | Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4.
Therefore, the size of the longest subarray is 2.
Example 2:
Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4
Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
Example 3:
Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= limit <= 109 | nlogn solution by this dude | 6 | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | 0.481 | ariboi27 | Medium | 21,464 | 1,438 |
find the kth smallest sum of a matrix with sorted rows | class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
row=len(mat)
col=len(mat[0])
temp=[i for i in mat[0]]
for i in range(1,row):
currSum=[]
for j in range(col):
for it in range(len(temp)):
currSum.append(temp[it]+mat[i][j])
currSum.sort()
temp.clear()
maxSize=min(k,len(currSum))
for size in range(maxSize):
temp.append(currSum[size])
return temp[k-1] | https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/1928887/Python3-or-O(m-*-knlogkn) | 2 | You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
Example 2:
Input: mat = [[1,3,11],[2,4,6]], k = 9
Output: 17
Example 3:
Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
Output: 9
Explanation: Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.
Constraints:
m == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i] is a non-decreasing array. | [Python3] | O(m * knlogkn) | 66 | find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows | 0.614 | swapnilsingh421 | Hard | 21,467 | 1,439 |
build an array with stack operations | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[]
for i in range(1,n+1):
if(i in target):
stack.append("Push")
else:
stack.append("Push")
stack.append("Pop")
if(i==(target[-1])):
break
return stack | https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1291707/Easy-Python-Solution(96.97) | 6 | You are given an integer array target and an integer n.
You have an empty stack with the two following operations:
"Push": pushes an integer to the top of the stack.
"Pop": removes the integer on the top of the stack.
You also have a stream of the integers in the range [1, n].
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:
If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
If the stack is not empty, pop the integer at the top of the stack.
If, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.
Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.
Example 1:
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Pop the integer on the top of the stack. s = [1].
Read 3 from the stream and push it to the stack. s = [1,3].
Example 2:
Input: target = [1,2,3], n = 3
Output: ["Push","Push","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Read 3 from the stream and push it to the stack. s = [1,2,3].
Example 3:
Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: Initially the stack s is empty. The last element is the top of the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
The answers that read integer 3 from the stream are not accepted.
Constraints:
1 <= target.length <= 100
1 <= n <= 100
1 <= target[i] <= n
target is strictly increasing. | Easy Python Solution(96.97%) | 407 | build-an-array-with-stack-operations | 0.714 | Sneh17029 | Medium | 21,468 | 1,441 |
count triplets that can form two arrays of equal xor | class Solution:
def countTriplets(self, arr: List[int]) -> int:
import collections
if len(arr) < 2:
return 0
xors = arr[0]
cnt = collections.Counter()
cnt_sums = collections.Counter()
result = 0
cnt[xors] = 1
cnt_sums[xors] = 0
for k in range(1, len(arr)):
xors ^= arr[k]
if xors == 0:
result += k
result += (k - 1)*cnt[xors] - cnt_sums[xors]
cnt_sums[xors] += k
cnt[xors] += 1
return result | https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1271870/Python-O(n)-hash-table | 1 | Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Where a == b.
Example 1:
Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
Example 2:
Input: arr = [1,1,1,1,1]
Output: 10
Constraints:
1 <= arr.length <= 300
1 <= arr[i] <= 108 | Python O(n) hash table | 164 | count-triplets-that-can-form-two-arrays-of-equal-xor | 0.756 | CiFFiRO | Medium | 21,501 | 1,442 |
minimum time to collect all apples in a tree | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
self.res = 0
d = collections.defaultdict(list)
for e in edges: # construct the graph
d[e[0]].append(e[1])
d[e[1]].append(e[0])
seen = set() # initialise seen set for visited nodes
seen.add(0) # add root to visited
def dfs(key):
# we initialize the go_thru state as 0, meaning we do not go through this node from root
# there are two cases where we would set go_thru == 1:
#(1) when this is the apple node, so we must visit it and go back up
#(2) when this node has apple nodes as descendants below, we must go down and come back
go_thru = 0
if hasApple[key]: # case 1
go_thru = 1
for i in d[key]:
if i not in seen:
seen.add(i)
a = dfs(i)
if a: # case 2, note that having just one path with an apple node below would require us to go through our current node,
# i.e we don't need both the paths to have apples
go_thru = 1
if key != 0: # since 0 is already the root, there is no way we can go through 0 to a node above
self.res += 2 * go_thru # passing one node means forward and backward, so 1 * 2 for going through, 0 * 2 for not
return go_thru
dfs(0)
return self.res | https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1460342/Python-Recursive-DFS-Solution-with-detailed-explanation-in-comments | 1 | Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.
Example 1:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
Output: 8
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
Output: 6
Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
Example 3:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0
Constraints:
1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai < bi <= n - 1
hasApple.length == n | [Python] Recursive DFS Solution with detailed explanation in comments | 192 | minimum-time-to-collect-all-apples-in-a-tree | 0.56 | lukefall425 | Medium | 21,508 | 1,443 |
number of ways of cutting a pizza | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
rows, cols = len(pizza), len(pizza[0])
# first, need way to query if a section contains an apple given a top left (r1, c1) and bottom right (r2, c2)
# we can do this in constant time by keeping track of the number of apples above and to the left of any given cell
apples = [[0] * cols for _ in range(rows)]
for row in range(rows):
apples_left = 0
for col in range(cols):
if pizza[row][col] == 'A':
apples_left += 1
apples[row][col] = apples[row-1][col] + apples_left
# query if there is an apple in this rectangle using the prefix sums
def has_apple(r1, c1, r2 = rows-1, c2 = cols-1) -> bool:
if r1 > r2 or c1 > c2:
return False
tot = apples[r2][c2]
left_sub = apples[r2][c1-1] if c1 > 0 else 0
up_sub = apples[r1-1][c2] if r1 > 0 else 0
upleft_sub = apples[r1-1][c1-1] if r1 > 0 < c1 else 0
in_rect = tot - left_sub - up_sub + upleft_sub
return in_rect > 0
# memory optimized dp, keep track of only one matrix of rows x cols
# bc we only need to access the values at the previous number of cuts
dp = [[1 if has_apple(r, c) else 0 for c in range(cols + 1)] for r in range(rows + 1)]
for cuts in range(1, k):
new_dp = [[0] * (cols + 1) for _ in range(rows + 1)]
for row in range(rows-1, -1, -1):
for col in range(cols-1, -1, -1):
for r2 in range(row, rows):
if has_apple(row, col, r2):
new_dp[row][col] += dp[r2+1][col]
for c2 in range(col, cols):
if has_apple(row, col, rows-1, c2):
new_dp[row][col] += dp[row][c2+1]
dp = new_dp
return dp[0][0] % (10**9 + 7) | https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/2677389/Python3-or-Space-Optimized-Bottom-Up-DP-or-O(k-*-r-*-c-*-(r-%2B-c))-Time-O(r-*-c)-Space | 3 | Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
Example 1:
Input: pizza = ["A..","AAA","..."], k = 3
Output: 3
Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
Example 2:
Input: pizza = ["A..","AA.","..."], k = 3
Output: 1
Example 3:
Input: pizza = ["A..","A..","..."], k = 1
Output: 1
Constraints:
1 <= rows, cols <= 50
rows == pizza.length
cols == pizza[i].length
1 <= k <= 10
pizza consists of characters 'A' and '.' only. | Python3 | Space Optimized Bottom-Up DP | O(k * r * c * (r + c)) Time, O(r * c) Space | 293 | number-of-ways-of-cutting-a-pizza | 0.579 | ryangrayson | Hard | 21,515 | 1,444 |
consecutive characters | class Solution:
def maxPower(self, s: str) -> int:
# the minimum value for consecutive is 1
local_max, global_max = 1, 1
# dummy char for initialization
prev = '#'
for char in s:
if char == prev:
# keeps consecutive, update local max
local_max += 1
# update global max length with latest one
global_max = max( global_max, local_max )
else:
# lastest consective chars stops, reset local max
local_max = 1
# update previous char as current char for next iteration
prev = char
return global_max | https://leetcode.com/problems/consecutive-characters/discuss/637217/Python-O(n)-by-linear-scan.-w-Comment | 7 | The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s, return the power of s.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters. | Python O(n) by linear scan. [w/ Comment] | 1,100 | consecutive-characters | 0.616 | brianchiang_tw | Easy | 21,519 | 1,446 |
simplified fractions | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
if n == 1:
return []
else:
numerator = list(range(1,n))
denominator = list(range(2,n+1))
res = set()
values = set()
for i in numerator:
for j in denominator:
if i < j and i/j not in values:
res.add(f'{i}/{j}')
values.add(i/j)
return res | https://leetcode.com/problems/simplified-fractions/discuss/1336226/Python3-solution-using-set | 3 | Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.
Example 1:
Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
Example 2:
Input: n = 3
Output: ["1/2","1/3","2/3"]
Example 3:
Input: n = 4
Output: ["1/2","1/3","1/4","2/3","3/4"]
Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".
Constraints:
1 <= n <= 100 | Python3 solution using set | 102 | simplified-fractions | 0.648 | EklavyaJoshi | Medium | 21,556 | 1,447 |
count good nodes in binary tree | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def solve(root,val):
if root:
k = solve(root.left, max(val,root.val)) + solve(root.right, max(val,root.val))
if root.val >= val:
k+=1
return k
return 0
return solve(root,root.val) | https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511520/C%2B%2B-or-PYTHON-oror-EXPLAINED-oror | 43 | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4]. | 🥇 C++ | PYTHON || EXPLAINED || ; ] | 2,600 | count-good-nodes-in-binary-tree | 0.746 | karan_8082 | Medium | 21,566 | 1,448 |
form largest integer with digits that add up to target | class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
@cache
def fn(x):
"""Return max integer given target x."""
if x == 0: return 0
if x < 0: return -inf
return max(fn(x - c) * 10 + i + 1 for i, c in enumerate(cost))
return str(max(0, fn(target))) | https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/discuss/1113027/Python3-top-down-dp | 1 | Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".
Example 1:
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit cost
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
Example 2:
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.
Example 3:
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It is impossible to paint any integer with total cost equal to target.
Constraints:
cost.length == 9
1 <= cost[i], target <= 5000 | [Python3] top-down dp | 117 | form-largest-integer-with-digits-that-add-up-to-target | 0.472 | ye15 | Hard | 21,606 | 1,449 |
number of students doing homework at a given time | class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
count = 0 # If a value meets the criteria, one will be added here.
for x, y in zip(startTime, endTime): # Zipping the two lists to allow us to iterate over them using x,y as our variables.
if x <= queryTime <= y: # Checking if the queryTime number is between startTime and endTime, adding one to count if it is.
count += 1
return count # Returning the value in count | https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/discuss/1817462/Python-Simple-Solution-or-Zip-and-Iterate-86-37ms | 4 | Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Example 1:
Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.
Example 2:
Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.
Constraints:
startTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000 | Python Simple Solution | Zip & Iterate - 86% 37ms | 110 | number-of-students-doing-homework-at-a-given-time | 0.759 | IvanTsukei | Easy | 21,607 | 1,450 |
rearrange words in a sentence | class Solution:
def arrangeWords(self, text: str) -> str:
return " ".join(sorted(text.split(), key=len)).capitalize() | https://leetcode.com/problems/rearrange-words-in-a-sentence/discuss/636348/Python3-one-line | 40 | Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Example 1:
Input: text = "Leetcode is cool"
Output: "Is cool leetcode"
Explanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.
Output is ordered by length and the new first word starts with capital letter.
Example 2:
Input: text = "Keep calm and code on"
Output: "On and keep calm code"
Explanation: Output is ordered as follows:
"On" 2 letters.
"and" 3 letters.
"keep" 4 letters in case of tie order by position in original text.
"calm" 4 letters.
"code" 4 letters.
Example 3:
Input: text = "To be or not to be"
Output: "To be or to be not"
Constraints:
text begins with a capital letter and then contains lowercase letters and single space between words.
1 <= text.length <= 10^5 | [Python3] one line | 2,600 | rearrange-words-in-a-sentence | 0.626 | ye15 | Medium | 21,649 | 1,451 |
people whose list of favorite companies is not a subset of another list | class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
n = len(favoriteCompanies)
comp = []
for f in favoriteCompanies:
comp += f
comp = list(set(comp))
dictBit = {comp[i] : 1 << i for i in range(len(comp))}
def getBit(cList):
output = 0
for c in cList:
output |= dictBit[c]
return output
bitFav = [getBit(favoriteCompanies[i]) for i in range(n)]
output = []
for i in range(n):
isGood = True
for j in range(n):
if(i != j and bitFav[i] & bitFav[j] == bitFav[i]):
isGood = False
break
if(isGood):
output.append(i)
return output | https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/discuss/2827639/Python-or-Dictionary-%2B-Bitwise-operation | 0 | Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
Constraints:
1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
All strings in favoriteCompanies[i] are distinct.
All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
All strings consist of lowercase English letters only. | Python | Dictionary + Bitwise operation | 3 | people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list | 0.568 | CosmosYu | Medium | 21,674 | 1,452 |
maximum number of darts inside of a circular dartboard | class Solution:
def numPoints(self, points: List[List[int]], r: int) -> int:
ans = 1
for x, y in points:
angles = []
for x1, y1 in points:
if (x1 != x or y1 != y) and (d:=sqrt((x1-x)**2 + (y1-y)**2)) <= 2*r:
angle = atan2(y1-y, x1-x)
delta = acos(d/(2*r))
angles.append((angle-delta, +1)) #entry
angles.append((angle+delta, -1)) #exit
angles.sort(key=lambda x: (x[0], -x[1]))
val = 1
for _, entry in angles:
ans = max(ans, val := val+entry)
return ans | https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/discuss/636439/Python3-angular-sweep-O(N2-logN) | 38 | Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.
Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lie on the dartboard.
Given the integer r, return the maximum number of darts that can lie on the dartboard.
Example 1:
Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
Output: 4
Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.
Example 2:
Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
Output: 5
Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).
Constraints:
1 <= darts.length <= 100
darts[i].length == 2
-104 <= xi, yi <= 104
All the darts are unique
1 <= r <= 5000 | [Python3] angular sweep O(N^2 logN) | 1,400 | maximum-number-of-darts-inside-of-a-circular-dartboard | 0.369 | ye15 | Hard | 21,677 | 1,453 |
check if a word occurs as a prefix of any word in a sentence | class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i , j in enumerate(sentence.split()):
if(j.startswith(searchWord)):
return i + 1
return -1 | https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/discuss/1170901/Python3-Simple-And-Readable-Solution-With-Explanation | 3 | Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Explanation: "burg" is prefix of "burger" which is the 4th word in the sentence.
Example 2:
Input: sentence = "this problem is an easy problem", searchWord = "pro"
Output: 2
Explanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.
Example 3:
Input: sentence = "i am tired", searchWord = "you"
Output: -1
Explanation: "you" is not a prefix of any word in the sentence.
Constraints:
1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence consists of lowercase English letters and spaces.
searchWord consists of lowercase English letters. | [Python3] Simple And Readable Solution With Explanation | 67 | check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence | 0.642 | VoidCupboard | Easy | 21,679 | 1,455 |
maximum number of vowels in a substring of given length | class Solution:
def maxVowels(self, s: str, k: int) -> int:
x = 0
for i in range(k):
if s[i] in ('a', 'e', 'i', 'o', 'u'):
x += 1
ans = x
for i in range(k,len(s)):
if s[i] in ('a', 'e', 'i', 'o', 'u'):
x += 1
if s[i-k] in ('a', 'e', 'i', 'o', 'u'):
x -= 1
ans = max(ans,x)
return ans | https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/discuss/1504290/Python3-simple-soluton | 2 | Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
1 <= k <= s.length | Python3 simple soluton | 89 | maximum-number-of-vowels-in-a-substring-of-given-length | 0.581 | EklavyaJoshi | Medium | 21,705 | 1,456 |
pseudo palindromic paths in a binary tree | class Solution:
def pseudoPalindromicPaths (self, root: Optional[TreeNode], cnt = 0) -> int:
if not root: return 0
cnt ^= 1 << (root.val - 1)
if root.left is None and root.right is None:
return 1 if cnt & (cnt - 1) == 0 else 0
return self.pseudoPalindromicPaths(root.left, cnt) + self.pseudoPalindromicPaths(root.right, cnt) | https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/discuss/2573237/LeetCode-The-Hard-Way-Explained-Line-By-Line | 68 | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1,null,1]
Output: 2
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 2:
Input: root = [2,1,1,1,3,null,null,null,null,null,1]
Output: 1
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Example 3:
Input: root = [9]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 9 | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 2,600 | pseudo-palindromic-paths-in-a-binary-tree | 0.68 | wingkwong | Medium | 21,725 | 1,457 |
max dot product of two subsequences | class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n=len(nums1)
m=len(nums2)
dp=[[0]*(m+1) for i in range(n+1)]
for i in range(m+1):
dp[0][i]=-1e9
for i in range(n+1):
dp[i][0]=-1e9
for i in range(1, n+1):
for j in range(1, m+1):
val=nums1[i-1]*nums2[j-1]+max(0, dp[i-1][j-1])
dp[i][j]=max(val, max(dp[i-1][j], dp[i][j-1]))
return dp[n][m] | https://leetcode.com/problems/max-dot-product-of-two-subsequences/discuss/2613290/Python-Solution-or-DP-or-LCS | 0 | Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]
Output: 18
Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1]
Output: -1
Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000 | Python Solution | DP | LCS | 8 | max-dot-product-of-two-subsequences | 0.463 | Siddharth_singh | Hard | 21,749 | 1,458 |
make two arrays equal by reversing subarrays | class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
n, m = len(target), len(arr)
if m > n:
return False
t = Counter(target)
a = Counter(arr)
for k, v in a.items():
if k in t and v == t[k]:
continue
else:
return False
return True | https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/discuss/2730962/Easy-solution-using-dictionary-in-python | 7 | You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]
2- Reverse subarray [4,2], arr becomes [1,2,4,3]
3- Reverse subarray [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.
Example 3:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr does not have value 9 and it can never be converted to target.
Constraints:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000 | Easy solution using dictionary in python | 89 | make-two-arrays-equal-by-reversing-subarrays | 0.722 | ankurbhambri | Easy | 21,751 | 1,460 |
check if a string contains all binary codes of size k | class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
return len({s[i:i+k] for i in range(len(s)-k+1)}) == 2 ** k | https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092441/Python-oror-2-Easy-oror-One-liner-with-explanation | 26 | Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
Example 2:
Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
Example 3:
Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and does not exist in the array.
Constraints:
1 <= s.length <= 5 * 105
s[i] is either '0' or '1'.
1 <= k <= 20 | ✅ Python || 2 Easy || One liner with explanation | 1,900 | check-if-a-string-contains-all-binary-codes-of-size-k | 0.568 | constantine786 | Medium | 21,782 | 1,461 |
course schedule iv | class Solution:
def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
#Let m = len(prereqs) and z = len(queries)
#Time: O(m + n + n*n + z) -> O(n^2)
#Space: O(n*n + n + n*n + n + z) -> O(n^2)
#process the prerequisites and build an adjacency list graph
#where edges go from prerequisite to the course that depends on the prereq!
n = numCourses
#Adjacency List graph!
adj = [set() for _ in range(n)]
#indegrees array!
indegrees = [0] * n
#tell us every ith node's set of ancestors or all prereqs to take ith course!
ancestors = [set() for _ in range(n)]
#iterate through prereqs and update indegrees array as well as the adj list!
for i in range(len(prerequisites)):
prereq, main = prerequisites[i][0], prerequisites[i][1]
adj[prereq].add(main)
indegrees[main] += 1
queue = deque()
#iterate through the indegrees array and add all courses that have no
#ancestors(no prerequisites to take it!)
for a in range(len(indegrees)):
#ath course can be taken without any prereqs -> first to be processed in
#the Kahn's BFS algo!
if(indegrees[a] == 0):
queue.append(a)
#proceed with Kahn's algo!
while queue:
cur_course = queue.pop()
neighbors = adj[cur_course]
for neighbor in neighbors:
#neighbor has one less incoming edge!
indegrees[neighbor] -= 1
#current course is a prerequisite to every neighboring node!
ancestors[neighbor].add(cur_course)
#but also, all prereqs of cur_course is also indirectly a prereq
#to each and every neighboring courses!
ancestors[neighbor].update(ancestors[cur_course])
#if neighboring node suddenly becomes can take with no prereqs,
#add it to the queue!
if(indegrees[neighbor] == 0):
queue.append(neighbor)
#once the algorithm ends, our ancestors array will have info regarding
#prerequisites in order to take every course from 0 to n-1!
output = []
for query in queries:
prereq2, main2 = query[0], query[1]
all_prereqs = ancestors[main2]
#check if prereq2 is an ancestor or required prereq course to take main2!
if(prereq2 in all_prereqs):
output.append(True)
continue
else:
output.append(False)
return output | https://leetcode.com/problems/course-schedule-iv/discuss/2337629/Python3-or-Solved-Using-Ancestors-of-every-DAG-Graph-Node-approach(Kahn's-Algo-BFS) | 1 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
Output: [true,true]
Constraints:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
All the pairs [ai, bi] are unique.
The prerequisites graph has no cycles.
1 <= queries.length <= 104
0 <= ui, vi <= n - 1
ui != vi | Python3 | Solved Using Ancestors of every DAG Graph Node approach(Kahn's Algo BFS) | 28 | course-schedule-iv | 0.489 | JOON1234 | Medium | 21,813 | 1,462 |
cherry pickup ii | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]
def get_next_max(row, col_r1, col_r2):
res = 0
for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):
for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):
res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])
return res
for row in reversed(range(rows)):
for col_r1 in range(min(cols, row + 2)):
for col_r2 in range(max(0, cols - row - 1), cols):
reward = grid[row][col_r1] + grid[row][col_r2]
if col_r1 == col_r2:
reward /= 2
dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)
return dp[0][1][cols] | https://leetcode.com/problems/cherry-pickup-ii/discuss/1674033/Python3-DYNAMIC-PROGRAMMING-(*)-Explained | 14 | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner (0, cols - 1).
Return the maximum number of cherries collection using both robots by following the rules below:
From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).
When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
When both robots stay in the same cell, only one takes the cherries.
Both robots cannot move outside of the grid at any moment.
Both robots should reach the bottom row in grid.
Example 1:
Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]
Output: 24
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
Example 2:
Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]
Output: 28
Explanation: Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
Constraints:
rows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100 | ❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained | 506 | cherry-pickup-ii | 0.701 | artod | Hard | 21,816 | 1,463 |
maximum product of two elements in an array | class Solution:
def maxProduct(self, nums: List[int]) -> int:
# approach 1: find 2 max numbers in 2 loops. T = O(n). S = O(1)
# approach 2: sort and then get the last 2 max elements. T = O(n lg n). S = O(1)
# approach 3: build min heap of size 2. T = O(n lg n). S = O(1)
# python gives only min heap feature. heaq.heappush(list, item). heapq.heappop(list)
heap = [-1]
for num in nums:
if num > heap[0]:
if len(heap) == 2:
heapq.heappop(heap)
heapq.heappush(heap, num)
return (heap[0]-1) * (heap[1]-1) | https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1975858/Python-3-greater-Using-heap | 3 | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Example 2:
Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.
Example 3:
Input: nums = [3,7]
Output: 12
Constraints:
2 <= nums.length <= 500
1 <= nums[i] <= 10^3 | Python 3 -> Using heap | 195 | maximum-product-of-two-elements-in-an-array | 0.794 | mybuddy29 | Easy | 21,834 | 1,464 |
maximum area of a piece of cake after horizontal and vertical cuts | class Solution:
def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:
hc.sort()
vc.sort()
maxh = hc[0]
maxv = vc[0]
for i in range(1, len(hc)):
maxh = max(maxh, hc[i] - hc[i-1])
maxh = max(maxh, h - hc[-1])
for i in range(1, len(vc)):
maxv = max(maxv, vc[i] - vc[i-1])
maxv = max(maxv, w - vc[-1])
return maxh*maxv % (10**9 + 7) | https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227297/Python-easy-solution | 3 | You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.
Example 1:
Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
Example 2:
Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9
Constraints:
2 <= h, w <= 109
1 <= horizontalCuts.length <= min(h - 1, 105)
1 <= verticalCuts.length <= min(w - 1, 105)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
All the elements in horizontalCuts are distinct.
All the elements in verticalCuts are distinct. | Python easy solution | 81 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | 0.409 | lokeshsenthilkumar | Medium | 21,882 | 1,465 |
reorder routes to make all paths lead to the city zero | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
cmap = {0}
count = 0
dq = deque(connections)
while dq:
u, v = dq.popleft()
if v in cmap:
cmap.add(u)
elif u in cmap:
cmap.add(v)
count += 1
else:
dq.append([u, v])
return count | https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1071235/Pythonor-Easy-and-fast-or-Beats-99 | 8 | Python| Easy and fast | Beats 99% | 406 | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0.618 | SlavaHerasymov | Medium | 21,926 | 1,466 |
|
probability of a two boxes having the same number of distinct balls | class Solution:
def getProbability(self, balls: List[int]) -> float:
n = sum(balls)//2
@cache
def fn(i, s0, s1, c0, c1):
"""Return number of ways to distribute boxes successfully (w/o considering relative order)."""
if s0 > n or s1 > n: return 0 # impossible
if i == len(balls): return int(c0 == c1)
ans = 0
for x in range(balls[i]+1):
ans += fn(i+1, s0+x, s1+balls[i]-x, c0+(x > 0), c1+(x < balls[i])) * comb(balls[i], x)
return ans
return fn(0, 0, 0, 0, 0) / comb(2*n, n) | https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/discuss/1214891/Python3-top-down-dp | 0 | Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.
All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).
Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.
Example 1:
Input: balls = [1,1]
Output: 1.00000
Explanation: Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
Example 2:
Input: balls = [2,1,1]
Output: 0.66667
Explanation: We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
Example 3:
Input: balls = [1,2,1,2]
Output: 0.60000
Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
Constraints:
1 <= balls.length <= 8
1 <= balls[i] <= 6
sum(balls) is even. | [Python3] top-down dp | 130 | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0.611 | ye15 | Hard | 21,939 | 1,467 |
shuffle the array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l=[]
for i in range(n):
l.append(nums[i])
l.append(nums[n+i])
return l | https://leetcode.com/problems/shuffle-the-array/discuss/941189/Simple-Python-Solution | 10 | Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]
Constraints:
1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3 | Simple Python Solution | 947 | shuffle-the-array | 0.885 | lokeshsenthilkumar | Easy | 21,940 | 1,470 |
the k strongest values in an array | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
new_arr = []
arr.sort()
med = arr[int((len(arr) - 1)//2)]
for num in arr :
new_arr.append([int(abs(num - med)), num])
new_arr = sorted(new_arr, key = lambda x : (x[0], x[1]))
output, counter = [], 0
for i in reversed(range(len(new_arr))) :
output.append(new_arr[i][1])
counter += 1
if counter == k :
return output
return output | https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/2516738/easy-python-solution | 0 | Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).
For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.
Example 1:
Input: arr = [1,2,3,4,5], k = 2
Output: [5,1]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
Example 2:
Input: arr = [1,1,3,5,5], k = 2
Output: [5,5]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].
Example 3:
Input: arr = [6,7,11,7,6,8], k = 5
Output: [11,8,6,6,7]
Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
Any permutation of [11,8,6,6,7] is accepted.
Constraints:
1 <= arr.length <= 105
-105 <= arr[i] <= 105
1 <= k <= arr.length | easy python solution | 15 | the-k-strongest-values-in-an-array | 0.602 | sghorai | Medium | 21,987 | 1,471 |
paint house iii | class Solution:
def minCost1(self, houses: List[int], cost: List[List[int]], R: int, C: int, target: int) -> int:
# think as if we are traveling downward
# at any point, if switch our column then (target--)
@functools.cache
def dp(x,y,k): # O(100*20*100) time space
if x == R:
return 0 if k == 0 else math.inf
elif k <= 0:
return math.inf
# if this house is already colored, dont recolor!!
if houses[x] > 0 and houses[x] != y+1: return math.inf
cur_cost = 0 if houses[x] == y+1 else cost[x][y]
# now try all columns! O(20) time
res = math.inf
for c in range(C):
if c == y:
res = min(res, cur_cost + dp(x+1,c,k))
else:
res = min(res, cur_cost + dp(x+1,c,k-1))
# print('dp',x,y,k,'=',res)
return res
ans = min(dp(0,y,target) for y in range(C))
return -1 if ans == math.inf else ans | https://leetcode.com/problems/paint-house-iii/discuss/1397505/Explained-Commented-Top-Down-greater-Bottom-Up-greater-Space-Optimized-Bottom-Up | 3 | There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].
Given an array houses, an m x n matrix cost and an integer target where:
houses[i]: is the color of the house i, and 0 if the house is not painted yet.
cost[i][j]: is the cost of paint the house i with the color j + 1.
Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.
Example 1:
Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 9
Explanation: Paint houses of this way [1,2,2,1,1]
This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].
Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.
Example 2:
Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 11
Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]
This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}].
Cost of paint the first and last house (10 + 1) = 11.
Example 3:
Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
Output: -1
Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.
Constraints:
m == houses.length == cost.length
n == cost[i].length
1 <= m <= 100
1 <= n <= 20
1 <= target <= m
0 <= houses[i] <= n
1 <= cost[i][j] <= 104 | Explained Commented Top Down -> Bottom Up -> Space Optimized Bottom Up | 257 | paint-house-iii | 0.619 | yozaam | Hard | 21,994 | 1,473 |
final prices with a special discount in a shop | class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
len_prices = len(prices)
i = 0
while i <= len_prices-2:
for j in range(i+1, len(prices)):
if prices[i] >= prices[j] and j > i:
prices[i] = prices[i] - prices[j]
break
i += 1
return prices | https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/discuss/685429/PythonPython3-Final-Prices-with-a-Special-Discount-in-a-Shop | 4 | You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.
Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.
Example 1:
Input: prices = [8,4,6,2,3]
Output: [4,2,4,2,3]
Explanation:
For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.
For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.
For items 3 and 4 you will not receive any discount at all.
Example 2:
Input: prices = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: In this case, for all items, you will not receive any discount at all.
Example 3:
Input: prices = [10,1,1,6]
Output: [9,0,1,6]
Constraints:
1 <= prices.length <= 500
1 <= prices[i] <= 1000 | [Python/Python3] Final Prices with a Special Discount in a Shop | 541 | final-prices-with-a-special-discount-in-a-shop | 0.755 | newborncoder | Easy | 22,005 | 1,475 |
find two non overlapping sub arrays each with target sum | class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
l, windowSum, res = 0, 0, float('inf')
min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.
for r, num in enumerate(arr): # r:right pointer and index of num in arr
windowSum += num
while windowSum > target:
# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target
windowSum -= arr[l]
l += 1
# the case when we found a new target sub-array, i.e. current window
if windowSum == target:
# length of current window
curLen = r - l + 1
# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window:
# avoid overlap with cur window
# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping
# , if < res, update res.
res = min(res, curLen + min_till[l - 1])
# Everytime we found a target window, update the min_till of current right end of the window,
# for future use when sum up to new length of sum_of_two_subarray and update the res.
min_till[r] = min(curLen, min_till[r - 1])
else:
# If windowSum < target: window with current arr[r] as right end does not have any target subarry,
# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1.
min_till[r] = min_till[r - 1]
return res if res < float('inf') else -1
Time = O(n): when sliding the window, left and right pointers traverse the array once.
Space = O(n): we use one additional list min_till[] to record min length of target subarray till index i. | https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/discuss/1987219/Python-Sliding-Window-O(n)-with-detail-comments. | 5 | You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Example 1:
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
Example 2:
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
Constraints:
1 <= arr.length <= 105
1 <= arr[i] <= 1000
1 <= target <= 108 | Python - Sliding Window - O(n) with detail comments. | 323 | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0.37 | changyou1009 | Medium | 22,034 | 1,477 |
allocate mailboxes | class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
n = len(houses)
houses.sort()
cost = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(i+1,n):
mid_house = houses[(i+j)//2]
for t in range(i,j+1):
cost[i][j]+= abs(mid_house-houses[t])
@lru_cache(None)
def dp(k,ind):
if k==0 and ind==n: return 0
if k==0 or ind==n: return float('inf')
res = float('inf')
for j in range(ind,n):
c = cost[ind][j]
res = min(res, c + dp(k-1,j+1))
return res
return dp(k,0) | https://leetcode.com/problems/allocate-mailboxes/discuss/1496112/Beginner-Friendly-oror-Easy-to-understand-oror-DP-solution | 3 | Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: houses = [1,4,8,10,20], k = 3
Output: 5
Explanation: Allocate mailboxes in position 3, 9 and 20.
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
Example 2:
Input: houses = [2,3,5,12,18], k = 2
Output: 9
Explanation: Allocate mailboxes in position 3 and 14.
Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
Constraints:
1 <= k <= houses.length <= 100
1 <= houses[i] <= 104
All the integers of houses are unique. | 📌📌 Beginner-Friendly || Easy-to-understand || DP solution 🐍 | 379 | allocate-mailboxes | 0.556 | abhi9Rai | Hard | 22,041 | 1,478 |
running sum of 1d array | class Solution(object):
def runningSum(self, nums):
result = []
current_sum = 0
for i in range(0, len(nums)):
result.append(current_sum + nums[i])
current_sum = result[i]
return result | https://leetcode.com/problems/running-sum-of-1d-array/discuss/2306599/Easy-to-understand-Python-solution | 13 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6 | Easy to understand Python solution | 324 | running-sum-of-1d-array | 0.892 | Balance-Coffee | Easy | 22,044 | 1,480 |
least number of unique integers after k removals | class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
count = Counter(arr)
ans = len(count)
for i in sorted(count.values()):
k -= i
if k < 0:
break
ans -= 1
return ans | https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/discuss/1269930/Beats-99-runtime-oror-98-memory-oror-python-oror-easy | 11 | Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length | Beats 99% runtime || 98% memory || python || easy | 1,000 | least-number-of-unique-integers-after-k-removals | 0.569 | chikushen99 | Medium | 22,096 | 1,481 |
minimum number of days to make m bouquets | class Solution:
def checker(self,arr, d, m, k) -> bool:
'''
d -> days
m -> bouquets
k -> adjacent flowers
return bool
'''
arr = [10**9] + arr + [10**9] #appending array with maximum values
idx = []
for i in range(len(arr)):
if arr[i] > d:
idx.append(i)
cnt = 0
for i in range(len(idx)-1):
# how many bouquet can we make out of an interval of valid flowers
cnt += (idx[i+1] - idx[i] - 1) // k
# return if count >= m
return cnt >= m
def minDays(self, arr: List[int], m: int, k: int) -> int:
if m*k > len(arr):
return -1
lo, hi = 1, max(arr)
while(hi >= lo):
mid = (hi+lo)//2
if(self.checker(arr, mid, m, k) == True):
hi = mid
else:
lo = mid+1
if(hi == lo): break
if self.checker(arr, lo, m, k):
return lo
else:
return hi | https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/discuss/707611/Python-Binary-Search-or-Mathematical-function-definition-(75-Speed) | 3 | You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1
Output: 3
Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: [x, _, _, _, _] // we can only make one bouquet.
After day 2: [x, _, _, _, x] // we can only make two bouquets.
After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2
Output: -1
Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3
Output: 12
Explanation: We need 2 bouquets each should have 3 flowers.
Here is the garden after the 7 and 12 days:
After day 7: [x, x, x, x, _, x, x]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: [x, x, x, x, x, x, x]
It is obvious that we can make two bouquets in different ways.
Constraints:
bloomDay.length == n
1 <= n <= 105
1 <= bloomDay[i] <= 109
1 <= m <= 106
1 <= k <= n | [Python] Binary Search | Mathematical function definition (75% Speed) | 223 | minimum-number-of-days-to-make-m-bouquets | 0.557 | uds5501 | Medium | 22,104 | 1,482 |
xor operation in an array | class Solution:
def xorOperation(self, n: int, start: int) -> int:
ans=0
for i in range(n):
ans^=start+(2*i)
return ans | https://leetcode.com/problems/xor-operation-in-an-array/discuss/942598/Simple-Python-Solutions | 8 | You are given an integer n and an integer start.
Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.
Return the bitwise XOR of all elements of nums.
Example 1:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^" corresponds to bitwise XOR operator.
Example 2:
Input: n = 4, start = 3
Output: 8
Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.
Constraints:
1 <= n <= 1000
0 <= start <= 1000
n == nums.length | Simple Python Solutions | 604 | xor-operation-in-an-array | 0.842 | lokeshsenthilkumar | Easy | 22,117 | 1,486 |
making file names unique | class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
# names : array of names
# n : size of names
# create folders at the i'th minute for each name = names[i]
# If name was used previously, append a suffix "(k)" - note parenthesis - where k is the smallest pos int
# return an array of strings where ans[i] is the actual saved variant of names[i]
n = len(names)
dictNames = {}
ans = ['']*n
# enumerate to grab index so we can return ans list in order
for idx, name in enumerate(names):
# check if we have seen this name before
if name in dictNames:
# if we have grab the next k using last successful low (k) suffix
k = dictNames[name]
# track the name we started so we can update the dict
namestart = name
# cycle through values of increasing k until we are not in a previously used name
while name in dictNames:
name = namestart + f"({k})"
k += 1
# update the name we started with to the new lowest value of k
dictNames[namestart] = k
# add the new name with k = 1 so if we see this name with the suffix
dictNames[name] = 1
else:
# we havent seen this name so lets start with 1
dictNames[name] = 1
# build the solution
ans[idx] = name
return ans | https://leetcode.com/problems/making-file-names-unique/discuss/1646944/Very-simple-python3-solution-using-hashmap-and-comments | 3 | Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.
Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.
Example 1:
Input: names = ["pes","fifa","gta","pes(2019)"]
Output: ["pes","fifa","gta","pes(2019)"]
Explanation: Let's see how the file system creates folder names:
"pes" --> not assigned before, remains "pes"
"fifa" --> not assigned before, remains "fifa"
"gta" --> not assigned before, remains "gta"
"pes(2019)" --> not assigned before, remains "pes(2019)"
Example 2:
Input: names = ["gta","gta(1)","gta","avalon"]
Output: ["gta","gta(1)","gta(2)","avalon"]
Explanation: Let's see how the file system creates folder names:
"gta" --> not assigned before, remains "gta"
"gta(1)" --> not assigned before, remains "gta(1)"
"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"
"avalon" --> not assigned before, remains "avalon"
Example 3:
Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".
Constraints:
1 <= names.length <= 5 * 104
1 <= names[i].length <= 20
names[i] consists of lowercase English letters, digits, and/or round brackets. | Very simple python3 solution using hashmap and comments | 307 | making-file-names-unique | 0.359 | jumpstarter | Medium | 22,153 | 1,487 |
avoid flood in the city | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
pq = []
fill = set()
d = collections.defaultdict(list)
ans = []
for i, rain in enumerate(rains):
d[rain].append(i)
for rain in rains:
if rain > 0:
if rain in fill:
return []
fill.add(rain)
d[rain].pop(0)
if d[rain]:
heapq.heappush(pq, d[rain][0])
ans.append(-1)
else:
if pq:
ind = heapq.heappop(pq)
ans.append(rains[ind])
fill.remove(rains[ind])
else:
ans.append(1)
return ans | https://leetcode.com/problems/avoid-flood-in-the-city/discuss/1842629/Python-easy-to-read-and-understand-or-heap | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.
Given an integer array rains where:
rains[i] > 0 means there will be rains over the rains[i] lake.
rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
Return an array ans where:
ans.length == rains.length
ans[i] == -1 if rains[i] > 0.
ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
Example 1:
Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.
Example 2:
Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
Example 3:
Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
Constraints:
1 <= rains.length <= 105
0 <= rains[i] <= 109 | Python easy to read and understand | heap | 193 | avoid-flood-in-the-city | 0.261 | sanial2001 | Medium | 22,158 | 1,488 |
find critical and pseudo critical edges in minimum spanning tree | class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
graph = dict()
for u, v, w in edges:
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []).append((u, w))
ref = self.mst(n, graph)
critical, pseudo = [], []
for i in range(len(edges)):
if self.mst(n, graph, exclude=edges[i][:2]) > ref: critical.append(i)
elif self.mst(n, graph, init=edges[i]) == ref: pseudo.append(i)
return [critical, pseudo]
def mst(self, n, graph, init=None, exclude=None):
"""Return weight of MST of given graph using Prim's algo"""
def visit(u):
"""Mark node and put its edges to priority queue"""
marked[u] = True
for v, w in graph.get(u, []):
if exclude and u in exclude and v in exclude: continue
if not marked[v]: heappush(pq, (w, u, v))
ans = 0
marked = [False]*n
pq = [] #min prioirty queue
if init:
u, v, w = init
ans += w
marked[u] = marked[v] = True
visit(u) or visit(v)
else:
visit(0)
while pq:
w, u, v = heappop(pq)
if marked[u] and marked[v]: continue
ans += w
if not marked[u]: visit(u)
if not marked[v]: visit(v)
return ans if all(marked) else inf | https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/discuss/702027/Python3-Prim's-algo | 4 | Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
Example 1:
Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]
Output: [[0,1],[2,3,4,5]]
Explanation: The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
Example 2:
Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]
Output: [[],[0,1,2,3]]
Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
Constraints:
2 <= n <= 100
1 <= edges.length <= min(200, n * (n - 1) / 2)
edges[i].length == 3
0 <= ai < bi < n
1 <= weighti <= 1000
All pairs (ai, bi) are distinct. | [Python3] Prim's algo | 355 | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0.526 | ye15 | Hard | 22,160 | 1,489 |