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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
baseball game | class Solution:
def calPoints(self, s: List[str]) -> int:
p = []
for i in s:
if i == 'C': p.pop()
elif i == 'D': p.append(2*p[-1])
elif i == '+': p.append(p[-1]+p[-2])
else: p.append(int(i))
return sum(p) | https://leetcode.com/problems/baseball-game/discuss/380544/Two-Solutions-in-Python-3-(beats-~99) | 7 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
An integer x.
Record a new score of x.
'+'.
Record a new score that is the sum of the previous two scores.
'D'.
Record a new score that is the double of the previous score.
'C'.
Invalidate the previous score, removing it from the record.
Return the sum of all the scores on the record after applying all the operations.
The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
Example 1:
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
Example 2:
Input: ops = ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation:
"5" - Add 5 to the record, record is now [5].
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
Example 3:
Input: ops = ["1","C"]
Output: 0
Explanation:
"1" - Add 1 to the record, record is now [1].
"C" - Invalidate and remove the previous score, record is now [].
Since the record is empty, the total sum is 0.
Constraints:
1 <= operations.length <= 1000
operations[i] is "C", "D", "+", or a string representing an integer in the range [-3 * 104, 3 * 104].
For operation "+", there will always be at least two previous scores on the record.
For operations "C" and "D", there will always be at least one previous score on the record. | Two Solutions in Python 3 (beats ~99%) | 928 | baseball-game | 0.737 | junaidmansuri | Easy | 11,273 | 682 |
redundant connection | class Solution(object):
def findRedundantConnection(self, edges):
self.parent = dict()
for e in edges:
f0 = self.find(e[0])
f1 = self.find(e[1])
if f0 == f1:
return e
self.parent[f0] = f1
def find(self, x):
if x not in self.parent:
return x
return self.find(self.parent[x]) | https://leetcode.com/problems/redundant-connection/discuss/2755933/Python-Union-Find-Easy | 1 | In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
n == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ai < bi <= edges.length
ai != bi
There are no repeated edges.
The given graph is connected. | Python - Union Find - Easy | 8 | redundant-connection | 0.62 | lokeshsenthilkumar | Medium | 11,323 | 684 |
repeated string match | class Solution:
def repeatedStringMatch(self, A: str, B: str) -> int:
if set(B).issubset(set(A)) == False: return -1
for i in range(1,int(len(B)/len(A))+3):
if B in A*i: return i
return -1
- Python3
- Junaid Mansuri | https://leetcode.com/problems/repeated-string-match/discuss/330741/Simple-Python3-Solution-(beats-~100)-(my-first-post-on-LeetCode-!!!) | 15 | Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc".
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.
Example 2:
Input: a = "a", b = "aa"
Output: 2
Constraints:
1 <= a.length, b.length <= 104
a and b consist of lowercase English letters. | Simple Python3 Solution (beats ~100%) (my first post on LeetCode !!!) | 1,600 | repeated-string-match | 0.34 | junaidmansuri | Medium | 11,336 | 686 |
longest univalue path | class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
def dfs(node):
"""Return longest univalue branch and longest univalue path (post-order traversal)."""
if not node: return 0, 0
(lx, llup), (rx, rlup) = dfs(node.left), dfs(node.right)
if not node.left or node.left.val != node.val: lx = 0
if not node.right or node.right.val != node.val: rx = 0
return 1 + max(lx, rx), max(llup, rlup, 1 + lx + rx)
return max(0, dfs(root)[-1]-1) | https://leetcode.com/problems/longest-univalue-path/discuss/902315/Python3-dfs-(post-order) | 4 | Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Example 2:
Input: root = [1,4,5,4,4,null,5]
Output: 2
Explanation: The shown image shows that the longest path of the same value (i.e. 4).
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
The depth of the tree will not exceed 1000. | [Python3] dfs (post order) | 215 | longest-univalue-path | 0.402 | ye15 | Medium | 11,345 | 687 |
knight probability in chessboard | class Solution:
def knightProbability(self, n: int, k: int, row0: int, col0: int) -> float:
# precalculate possible moves
adj_list = defaultdict(list)
d = ((-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2))
for row in range(n):
for col in range(n):
for dx, dy in d:
pos = (row + dx, col + dy)
if 0 <= pos[0] < n and 0 <= pos[1] < n:
adj_list[(row, col)].append(pos)
@cache
def get_leafs_num(pos, h):
if h == k:
return 1
res = 0
for next_pos in adj_list[pos]:
res += get_leafs_num(next_pos, h + 1)
return res
leafs_num = get_leafs_num((row0, col0), 0)
return leafs_num / 8**k | https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2193242/Python3-DFS-with-DP-beats-99-()()-Explained | 6 | On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly k moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.
Example 1:
Input: n = 3, k = 2, row = 0, column = 0
Output: 0.06250
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
Example 2:
Input: n = 1, k = 0, row = 0, column = 0
Output: 1.00000
Constraints:
1 <= n <= 25
0 <= k <= 100
0 <= row, column <= n - 1 | ✔️ [Python3] DFS with DP, beats 99% ٩(๑・ิᴗ・ิ)۶٩(・ิᴗ・ิ๑)۶, Explained | 164 | knight-probability-in-chessboard | 0.521 | artod | Medium | 11,351 | 688 |
maximum sum of 3 non overlapping subarrays | class Solution:
def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
@cache
def fn(i, n):
"""Return max sum of 3 non-overlapping subarrays."""
if n == 0: return []
if i+k >= len(prefix): return []
return max([i] + fn(i+k, n-1), fn(i+1, n), key=lambda x: sum(prefix[xx+k] - prefix[xx] for xx in x))
return fn(0, 3) | https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/1342651/Python3-dp | 1 | Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example 1:
Input: nums = [1,2,1,2,6,7,5,1], k = 2
Output: [0,3,5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Example 2:
Input: nums = [1,2,1,2,1,2,1,2,1], k = 2
Output: [0,2,4]
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] < 216
1 <= k <= floor(nums.length / 3) | [Python3] dp | 73 | maximum-sum-of-3-non-overlapping-subarrays | 0.489 | ye15 | Hard | 11,367 | 689 |
employee importance | class Solution:
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
id_to_emp = {employee.id: employee for employee in employees}
importance = 0
stack = [id_to_emp[id]]
while stack:
cur_emp = stack.pop()
importance += cur_emp.importance
stack.extend([id_to_emp[new_emp] for new_emp in cur_emp.subordinates])
return importance | https://leetcode.com/problems/employee-importance/discuss/332600/Iterative-Python-beats-99.73 | 5 | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees employees where:
employees[i].id is the ID of the ith employee.
employees[i].importance is the importance value of the ith employee.
employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.
Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.
Example 1:
Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1
Output: 11
Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.
They both have an importance value of 3.
Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.
Example 2:
Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5
Output: -3
Explanation: Employee 5 has an importance value of -3 and has no direct subordinates.
Thus, the total importance value of employee 5 is -3.
Constraints:
1 <= employees.length <= 2000
1 <= employees[i].id <= 2000
All employees[i].id are unique.
-100 <= employees[i].importance <= 100
One employee has at most one direct leader and may have several subordinates.
The IDs in employees[i].subordinates are valid IDs. | Iterative Python, beats 99.73% | 962 | employee-importance | 0.652 | hgrsd | Medium | 11,373 | 690 |
stickers to spell word | class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
freqs = [Counter(x) for x in stickers]
@cache
def fn(x):
"""Return min sticks to give x."""
if not x: return 0
ans = inf
freq = Counter(x)
for cnt in freqs:
if x[0] in cnt:
xx = "".join(k*v for k, v in (freq - cnt).items())
ans = min(ans, 1 + fn(xx))
return ans
ans = fn(target)
return ans if ans < inf else -1 | https://leetcode.com/problems/stickers-to-spell-word/discuss/1366983/Python3-dp | 4 | We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i] and target consist of lowercase English letters. | [Python3] dp | 234 | stickers-to-spell-word | 0.463 | ye15 | Hard | 11,388 | 691 |
top k frequent words | class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
#Have a dict of word and its freq
counts = collections.Counter(words)
#get a array wchich will have a tuple of word and count
heap = [(-count, word) for word, count in counts.items()]
#as default heap structure in python min heap and we want max heap
# to get top frequent word, we will do a make the counter negative
#so that the topmost element will come up (i.e -8 < -2 so in min heap -8 will come up wich is actually 8)
heapq.heapify(heap) #creating heap in place
#by deualt it will sort by fre then word
return [heapq.heappop(heap)[1] for _ in range(k)] | https://leetcode.com/problems/top-k-frequent-words/discuss/1657648/Simple-or-4-lines-or-using-heap-or-With-explanation | 25 | Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Constraints:
1 <= words.length <= 500
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
k is in the range [1, The number of unique words[i]]
Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space? | Simple | 4 lines | using heap | With explanation | 2,000 | top-k-frequent-words | 0.569 | shraddhapp | Medium | 11,394 | 692 |
binary number with alternating bits | class Solution:
def hasAlternatingBits(self, n: int) -> bool:
s = bin(n).replace('0b','')
for i in range(len(s)-1):
if s[i] == s[i+1]:
return False
return True | https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1095502/Python3-simple-solution | 2 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1 | Python3 simple solution | 54 | binary-number-with-alternating-bits | 0.613 | EklavyaJoshi | Easy | 11,432 | 693 |
max area of island | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
maxArea = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1: # run dfs only when we find a land
maxArea = max(maxArea, self.dfs(grid, i, j))
return maxArea
def dfs(self, grid, i, j):
# conditions for out of bound and when we encounter water
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:
return 0
maxArea = 1
grid[i][j] = '#' # this will act as visited set
maxArea += self.dfs(grid, i+1, j)
maxArea += self.dfs(grid, i-1, j)
maxArea += self.dfs(grid, i, j+1)
maxArea += self.dfs(grid, i, j-1)
return maxArea | https://leetcode.com/problems/max-area-of-island/discuss/1459194/python-Simple-and-intuitive-DFS-approach-!!! | 15 | You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Example 1:
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] is either 0 or 1. | [python] Simple and intuitive DFS approach !!! | 1,400 | max-area-of-island | 0.717 | nandanabhishek | Medium | 11,454 | 695 |
count binary substrings | class Solution:
def countBinarySubstrings(self, s: str) -> int:
stack = [[], []]
latest = int(s[0])
stack[latest].append(latest)
result = 0
for i in range(1,len(s)):
v = int(s[i])
if v != latest:
stack[v].clear()
latest = v
stack[v].append(v)
if len(stack[1-v]) > 0:
stack[1-v].pop()
result += 1
return result | https://leetcode.com/problems/count-binary-substrings/discuss/384054/Only-using-stack-with-one-iteration-logic-solution-in-Python-O(N) | 7 | Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'. | Only using stack with one iteration, logic solution in Python O(N) | 994 | count-binary-substrings | 0.656 | zouqiwu09 | Easy | 11,505 | 696 |
degree of an array | class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
C = {}
for i, n in enumerate(nums):
if n in C: C[n].append(i)
else: C[n] = [i]
M = max([len(i) for i in C.values()])
return min([i[-1]-i[0] for i in C.values() if len(i) == M]) + 1
- Junaid Mansuri | https://leetcode.com/problems/degree-of-an-array/discuss/349801/Solution-in-Python-3-(beats-~98) | 43 | Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: nums = [1,2,2,3,1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: nums = [1,2,2,3,1,4,2]
Output: 6
Explanation:
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
Constraints:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999. | Solution in Python 3 (beats ~98%) | 3,000 | degree-of-an-array | 0.559 | junaidmansuri | Easy | 11,520 | 697 |
partition to k equal sum subsets | class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
if k==1:
return True
total = sum(nums)
n = len(nums)
if total%k!=0:
return False
nums.sort(reverse=True)
average = total//k
if nums[0]>average:
return False
visited = [False]*n
def dfs(cur, begin, k):
if k==0:
return True
if cur>average:
return False
elif cur==average:
return dfs(0, 0, k-1)
for i in range(begin, n):
if not visited[i]:
visited[i] = True
if dfs(cur + nums[i], i+1, k):
return True
visited[i] = False
return False
return dfs(0, 0, k) | https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1627241/python-simple-with-detailed-explanation-or-96.13 | 5 | Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Example 2:
Input: nums = [1,2,3,4], k = 3
Output: false
Constraints:
1 <= k <= nums.length <= 16
1 <= nums[i] <= 104
The frequency of each element is in the range [1, 4]. | python simple with detailed explanation | 96.13% | 563 | partition-to-k-equal-sum-subsets | 0.408 | 1579901970cg | Medium | 11,531 | 698 |
falling squares | class Solution:
def fallingSquares(self, positions):
height, pos, max_h,res = [0],[0],0,[]
for left, side in positions:
i = bisect.bisect_right(pos, left)
j = bisect.bisect_left(pos, left + side)
high = max(height[i - 1:j] or [0]) + side
pos[i:j] = [left, left + side]
height[i:j] = [high, height[j - 1]]
max_h = max(max_h, high)
res.append(max_h)
return res | https://leetcode.com/problems/falling-squares/discuss/2397036/faster-than-90.37-or-python-or-solution-or-explained | 1 | There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the height of the current tallest stack of squares.
Return an integer array ans where ans[i] represents the height described above after dropping the ith square.
Example 1:
Input: positions = [[1,2],[2,3],[6,1]]
Output: [2,5,5]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of [2, 5, 5].
Example 2:
Input: positions = [[100,100],[200,100]]
Output: [100,100]
Explanation:
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of [100, 100].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
Constraints:
1 <= positions.length <= 1000
1 <= lefti <= 108
1 <= sideLengthi <= 106 | faster than 90.37% | python | solution | explained | 57 | falling-squares | 0.444 | vimla_kushwaha | Hard | 11,556 | 699 |
search in a binary search tree | class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return
if root.val==val:
return root
if root.val<val:
return self.searchBST(root.right,val)
else:
return self.searchBST(root.left,val) | https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/943397/Python-Simple-Solution | 20 | You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
Constraints:
The number of nodes in the tree is in the range [1, 5000].
1 <= Node.val <= 107
root is a binary search tree.
1 <= val <= 107 | Python Simple Solution | 1,300 | search-in-a-binary-search-tree | 0.772 | lokeshsenthilkumar | Easy | 11,558 | 700 |
insert into a binary search tree | class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
cur, next = None, root
while next:
cur = next
next = cur.left if val < cur.val else cur.right
if val < cur.val:
cur.left = TreeNode(val)
else:
cur.right = TreeNode(val)
return root | https://leetcode.com/problems/insert-into-a-binary-search-tree/discuss/1683883/Python3-ITERATIVE-(-)-Explained | 26 | You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
Example 1:
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Another accepted tree is:
Example 2:
Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
Example 3:
Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5
Output: [4,2,7,1,3,5]
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-108 <= Node.val <= 108
All the values Node.val are unique.
-108 <= val <= 108
It's guaranteed that val does not exist in the original BST. | ✔️ [Python3] ITERATIVE (づ ̄ ³ ̄)づ ❤, Explained | 1,300 | insert-into-a-binary-search-tree | 0.746 | artod | Medium | 11,594 | 701 |
binary search | class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid = (left+right)//2
if nums[mid]==target:
return mid
elif nums[mid]>target:
right = mid-1
else:
left = mid+1
return -1 | https://leetcode.com/problems/binary-search/discuss/2700642/Python-Classic-Binary-Search-Problem-or-99-Faster-or-Fastest-Solution | 47 | Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order. | ✔️ Python Classic Binary Search Problem | 99% Faster | Fastest Solution | 6,000 | binary-search | 0.551 | pniraj657 | Easy | 11,628 | 704 |
design hashset | # Linked List Solution
class MyHashSet(object):
def __init__(self):
self.keyRange = 769
self.bucketArray = [LinkedList() for i in range(self.keyRange)]
def _hash(self, key):
return key % self.keyRange
def add(self, key):
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].append(key)
def remove(self, key):
bucketIndex = self._hash(key)
self.bucketArray[bucketIndex].deleteNodeKeyAll(key)
# while self.bucketArray[bucketIndex].search(key):
# self.bucketArray[bucketIndex].deleteNodeKeyOne(key)
def contains(self, key):
bucketIndex = self._hash(key)
return self.bucketArray[bucketIndex].search(key)
# ---------------------------------------------------------
## Define a linked list
class Node:
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# ---------------------------------------------------------
## Insert a new node
### Insert the new node at the front of the linked list
def push(self, new_val):
new_node = Node(new_val)
new_node.next = self.head
self.head = new_node
### Insert the new node at the end of the linked list
def append(self, new_val):
new_node = Node(new_val)
if self.head is None:
self.head = new_node
return
# Traverse till the end of the linked list
last = self.head
while last.next:
last = last.next
last.next = new_node
### Insert the new node after a given node
def insertAfter(self, new_val, prev_node):
if prev_node is None:
print("Please enter the node which is the previous node of the inserted node.")
return
new_node = Node(new_val)
new_node.next = prev_node.next
prev_node.next = new_node
# ---------------------------------------------------------
## Delete a node
### Delete a node by value
# Iterative Method
def deleteNodeKeyOne(self, key): # delete a single node
temp = self.head
if temp is None:
return
if temp.val == key:
self.head = temp.next
temp = None
return
while temp is not None:
if temp.val == key:
break
prev = temp
temp = temp.next
if temp is None:
return
prev.next = temp.next
temp = None
def deleteNodeKeyAll(self, key): # delete all the nodes with value key
temp = self.head
if temp is None:
return
while temp.val == key:
deletedNode = temp
self.head = temp.next
temp = self.head
deletedNode = None
if temp is None:
return
nxt = temp.next
while nxt is not None:
if nxt.val == key:
deletedNode = nxt
temp.next = nxt.next
deletedNode = None
temp = nxt
nxt = nxt.next
### Delete a node by position and return the value of the deleted node
def deleteNodePosition(self, position):
if self.head is None:
return
if position == 0:
temp = self.head
self.head = self.head.next
temp = None
return
idx = 0
current = self.head
prev = self.head
nxt = self.head
while current is not None:
if idx == position:
nxt = current.next
break
prev = current
current = current.next
idx += 1
prev.next = nxt
current = None
# ---------------------------------------------------------
# Print a linked list
def printList(self):
temp = self.head
while temp:
print (" %d" %(temp.val))
temp = temp.next
# ---------------------------------------------------------
## Search an element in a linked list
def search(self, x):
current = self.head
while current is not None:
if current.val == x:
return True
current = current.next
return False | https://leetcode.com/problems/design-hashset/discuss/1947672/Python3-Linked-List-Solution-(faster-than-83) | 0 | Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
Example 1:
Input
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output
[null, null, null, true, false, null, true, null, false]
Explanation
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)
Constraints:
0 <= key <= 106
At most 104 calls will be made to add, remove, and contains. | Python3 Linked List Solution (faster than 83%) | 105 | design-hashset | 0.659 | Mr_Watermelon | Easy | 11,682 | 705 |
to lower case | class Solution:
def toLowerCase(self, s: str) -> str:
# Instead of using .lower(), let's implement with ASCII
# ord() returns the ascii value of a passed character
# Uncomment the line below to see the ASCII value of some important characters
# print(ord('a'), ord('z'), ord('A'), ord('Z'))
# Notice 'a'=97, and 'A'=65
# This can be used to tell whether a character is upper/lower case, and can help us convert between them
# First, make the string a list so we can change each char individually
s = list(s)
# Then, loop through the characters, and if their ascii value is <= 90 and >= 65, they must be upper case
# Use the difference (97 - 65 = 32) to convert it from upper to lower, then use chr() to convert from ascii to char
# - ord('A') + 32 = 97 = ord('a')
for i in range(len(s)):
if ord(s[i]) <= 90 and ord(s[i]) >= 65:
s[i] = chr(ord(s[i])+32)
return ''.join(s) | https://leetcode.com/problems/to-lower-case/discuss/2411462/Python3-ToLowerCase-Explanation-using-ASCII | 2 | Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
Example 1:
Input: s = "Hello"
Output: "hello"
Example 2:
Input: s = "here"
Output: "here"
Example 3:
Input: s = "LOVELY"
Output: "lovely"
Constraints:
1 <= s.length <= 100
s consists of printable ASCII characters. | [Python3] ToLowerCase - Explanation - using ASCII | 84 | to-lower-case | 0.82 | connorthecrowe | Easy | 11,684 | 709 |
random pick with blacklist | class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.hashmap={}
for b in blacklist:
self.hashmap[b]=-1
self.length=n-len(blacklist)
flag=n-1
for b in blacklist:
if b<self.length:
while flag in self.hashmap:
flag-=1
self.hashmap[b]=flag
flag-=1
def pick(self) -> int:
seed=random.randrange(self.length)
return self.hashmap.get(seed,seed)
# Your Solution object will be instantiated and called as such:
# obj = Solution(n, blacklist)
# param_1 = obj.pick() | https://leetcode.com/problems/random-pick-with-blacklist/discuss/2389935/faster-than-99.73-or-Python3-or-solution | 1 | You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.
Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.
Implement the Solution class:
Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist.
int pick() Returns a random integer in the range [0, n - 1] and not in blacklist.
Example 1:
Input
["Solution", "pick", "pick", "pick", "pick", "pick", "pick", "pick"]
[[7, [2, 3, 5]], [], [], [], [], [], [], []]
Output
[null, 0, 4, 1, 6, 1, 0, 4]
Explanation
Solution solution = new Solution(7, [2, 3, 5]);
solution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,
// 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).
solution.pick(); // return 4
solution.pick(); // return 1
solution.pick(); // return 6
solution.pick(); // return 1
solution.pick(); // return 0
solution.pick(); // return 4
Constraints:
1 <= n <= 109
0 <= blacklist.length <= min(105, n - 1)
0 <= blacklist[i] < n
All the values of blacklist are unique.
At most 2 * 104 calls will be made to pick. | faster than 99.73% | Python3 | solution | 152 | random-pick-with-blacklist | 0.337 | vimla_kushwaha | Hard | 11,729 | 710 |
minimum ascii delete sum for two strings | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
def lcs(s,p):
m,n = len(s),len(p)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m):
for j in range(n):
if s[i]==p[j]:
dp[i+1][j+1] = dp[i][j]+ord(s[i])
else:
dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1])
return dp[-1][-1]
common = lcs(s1,s2)
total,res = 0,0
for c in s1:
total+=ord(c)
for c in s2:
total+=ord(c)
res = total - common*2
return res | https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/1516574/Greedy-oror-DP-oror-Same-as-LCS | 4 | Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d] + 101[e] + 101[e] to the sum.
Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Constraints:
1 <= s1.length, s2.length <= 1000
s1 and s2 consist of lowercase English letters. | 📌📌 Greedy || DP || Same as LCS 🐍 | 94 | minimum-ascii-delete-sum-for-two-strings | 0.623 | abhi9Rai | Medium | 11,736 | 712 |
subarray product less than k | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
# Quick response for invalid k on product of positive numbers
return 0
else:
left_sentry = 0
num_of_subarray = 0
product_of_subarry = 1
# update right bound of sliding window
for right_sentry in range( len(nums) ):
product_of_subarry *= nums[right_sentry]
# update left bound of sliding window
while product_of_subarry >= k:
product_of_subarry //= nums[left_sentry]
left_sentry += 1
# Note:
# window size = right_sentry - left_sentry + 1
# update number of subarrary with product < k
num_of_subarray += right_sentry - left_sentry + 1
return num_of_subarray | https://leetcode.com/problems/subarray-product-less-than-k/discuss/481917/Python-sol.-based-on-sliding-window.-run-time-90%2B-w-Explanation | 3 | Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.
Example 1:
Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Example 2:
Input: nums = [1,2,3], k = 0
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106 | Python sol. based on sliding window. run-time 90%+ [ w/ Explanation ] | 723 | subarray-product-less-than-k | 0.452 | brianchiang_tw | Medium | 11,743 | 713 |
best time to buy and sell stock with transaction fee | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = inf, 0
for x in prices:
buy = min(buy, x)
sell = max(sell, x - buy)
return sell | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | 4 | You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note:
You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
The transaction fee is only charged once for each stock purchase and sale.
Example 1:
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
Constraints:
1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104 | [Python3] dp | 78 | best-time-to-buy-and-sell-stock-with-transaction-fee | 0.644 | ye15 | Medium | 11,758 | 714 |
1 bit and 2 bit characters | class Solution:
def isOneBitCharacter(self, bits):
i, n, numBits = 0, len(bits), 0
while i < n:
bit = bits[i]
if bit == 1:
i += 2
numBits = 2
else:
i += 1
numBits = 1
return numBits == 1 | https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2012976/Python-Clean-and-Simple! | 2 | We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
Example 1:
Input: bits = [1,0,0]
Output: true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
Example 2:
Input: bits = [1,1,1,0]
Output: false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
Constraints:
1 <= bits.length <= 1000
bits[i] is either 0 or 1. | Python - Clean and Simple! | 146 | 1-bit-and-2-bit-characters | 0.46 | domthedeveloper | Easy | 11,781 | 717 |
maximum length of repeated subarray | class Solution:
# DP Approach - Similar to 1143. Longest Common Subsequence
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m = len(nums1), len(nums2)
# dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]
dp = [[0] * (m + 1) for _ in range(n + 1)]
ans = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
# if both character is same
if nums1[i - 1] == nums2[j - 1]:
# then we add 1 to the previous state, which is dp[i - 1][j - 1]
# in other word, we extend the repeated subarray by 1
# e.g. a = [1], b = [1], length of repeated array is 1
# a = [1,2], b = [1,2], length of repeated array is the previous result + 1 = 2
dp[i][j] = dp[i - 1][j - 1] + 1
# record the max ans here
ans = max(ans, dp[i][j])
# else:
# if you are looking for longest common sequence,
# then you put dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); here
# however, this problem is looking for subarray,
# since both character is not equal, which means we need to break it here
# hence, set dp[i][j] to 0
return ans | https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599501/LeetCode-The-Hard-Way-Explained-Line-By-Line | 32 | Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Explanation: The repeated subarray with maximum length is [0,0,0,0,0].
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100 | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 2,000 | maximum-length-of-repeated-subarray | 0.515 | wingkwong | Medium | 11,796 | 718 |
find k th smallest pair distance | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def getPairs(diff):
l = 0
count = 0
for r in range(len(nums)):
while nums[r] - nums[l] > diff:
l += 1
count += r - l
return count
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
mid = (l + r) // 2
res = getPairs(mid)
if res >= k:
r = mid
else:
l = mid + 1
return l | https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/2581420/Simple-python-binary-search | 1 | The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Input: nums = [1,1,1], k = 2
Output: 0
Example 3:
Input: nums = [1,6,1], k = 3
Output: 5
Constraints:
n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2 | Simple python binary search | 123 | find-k-th-smallest-pair-distance | 0.364 | shubhamnishad25 | Hard | 11,831 | 719 |
longest word in dictionary | class Solution:
def longestWord(self, words: List[str]) -> str:
words.sort() # for smallest lexicographical order
visited = {""} # hashset to keep a track of visited words
res = ''
for word in words:
if word[:-1] in visited: # check previous word ie. word[:len(word)-1] visited or not
visited.add(word) # add this word to the set
if len(word) > len(res): # current word have greater lenght and lexicographically smaller
res = word # update res
return res
# Time: O(n log(n)) # for sorting the words
# Space: O(n) # for making the set visited | https://leetcode.com/problems/longest-word-in-dictionary/discuss/2075147/Python-O(n-log(n))-Time-O(n)-Space-Faster-Than-95 | 4 | Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i] consists of lowercase English letters. | [Python] O(n log(n)) Time, O(n) Space Faster Than 95% | 217 | longest-word-in-dictionary | 0.518 | samirpaul1 | Medium | 11,834 | 720 |
accounts merge | class Solution:
def dfs(self, graph, node, visit):
visit.add(node)
for nei in graph[node]:
if nei not in visit:
self.dfs(graph, nei, visit)
self.res.append(node)
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
graph = collections.defaultdict(set)
for account in accounts:
for email in account[1:]:
graph[account[1]].add(email)
graph[email].add(account[1])
#print(graph.items())
visit = set()
ans = []
for account in accounts:
name = account[0]
for email in account[1:]:
if email not in visit:
self.res = []
self.dfs(graph, email, visit)
ans.append([name]+sorted(self.res))
return ans | https://leetcode.com/problems/accounts-merge/discuss/2014051/Python-easy-to-read-and-understand-or-DFS | 7 | Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Output: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]
Explanation:
The first and second John's are the same person as they have the common email "johnsmith@mail.com".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
Example 2:
Input: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]
Output: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]
Constraints:
1 <= accounts.length <= 1000
2 <= accounts[i].length <= 10
1 <= accounts[i][j].length <= 30
accounts[i][0] consists of English letters.
accounts[i][j] (for j > 0) is a valid email. | Python easy to read and understand | DFS | 507 | accounts-merge | 0.564 | sanial2001 | Medium | 11,844 | 721 |
remove comments | class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans, inComment = [], False
new_str = ""
for c in source:
if not inComment: new_str = ""
i, n = 0, len(c)
# inComment, we find */
while i < n:
if inComment:
if c[i:i + 2] == '*/' and i + 1 < n:
i += 2
inComment = False
continue
i += 1
# not in Comment, we find /* // and common character
else:
if c[i:i + 2] == '/*' and i + 1 < n:
i += 2
inComment = True
continue
if c[i:i + 2] == '//' and i + 1 < n:
break
new_str += c[i]
i += 1
if new_str and not inComment:
ans.append(new_str)
return ans | https://leetcode.com/problems/remove-comments/discuss/2446606/Easy-to-understand-using-Python | 3 | Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\n'.
In C++, there are two types of comments, line comments, and block comments.
The string "//" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
The string "/*" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/" does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
For example, if the string "//" occurs in a block comment, it is ignored.
Similarly, if the string "/*" occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
For example, source = "string s = "/* Not a comment. */";" will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return the source code in the same format.
Example 1:
Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
Explanation: The line by line code is visualized as below:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
Example 2:
Input: source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].
Constraints:
1 <= source.length <= 100
0 <= source[i].length <= 80
source[i] consists of printable ASCII characters.
Every open block comment is eventually closed.
There are no single-quote or double-quote in the input. | Easy to understand using Python | 567 | remove-comments | 0.38 | fguo10 | Medium | 11,857 | 722 |
find pivot index | class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]
right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
for i, num in enumerate(nums): # we can use normal for loop as well.
right -= num # as we are trying to find out pivot index so iteratively we`ll reduce the value of right to find the pivot index
if left == right: # comparing the values for finding out the pivot index.
return i # if there is any return the index whixh will be our required index.
left += num # we have to add the num iteratively.
return -1 | https://leetcode.com/problems/find-pivot-index/discuss/2321669/Python-99.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | 9 | Given an array of integers nums, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Example 3:
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/ | Python 99.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | 725 | find-pivot-index | 0.535 | rlakshay14 | Easy | 11,865 | 724 |
split linked list in parts | class Solution:
def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:
size = self.get_size(head)
min_len, one_more = divmod(size, k)
res = []
current = ListNode()
current.next = head
for i in range(k):
ans = current
for _ in range(min_len + int(i < one_more)):
current = current.next
res.append(ans.next)
ans.next = None
return res
def get_size(self, head: ListNode) -> int:
size = 0
while head is not None:
size += 1
head = head.next
return size | https://leetcode.com/problems/split-linked-list-in-parts/discuss/1322974/Clean-Python-and-Java | 4 | Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return an array of the k parts.
Example 1:
Input: head = [1,2,3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but its string representation as a ListNode is [].
Example 2:
Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3
Output: [[1,2,3,4],[5,6,7],[8,9,10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
Constraints:
The number of nodes in the list is in the range [0, 1000].
0 <= Node.val <= 1000
1 <= k <= 50 | Clean Python and Java | 456 | split-linked-list-in-parts | 0.572 | aquafie | Medium | 11,919 | 725 |
number of atoms | class Solution:
def countOfAtoms(self, formula: str) -> str:
# constant declarations
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower=upper.lower()
digits = "0123456789"
# variables
count=defaultdict(int)
element_name = None
element_name_parse_start=False
element_count =""
bracket_stacks = [[]]
buffer = []
# function to parse out the complete number if a digit is seen,
# the function takes the character, that was seen as a digit and
# the generator object to get the remaining (yet to be read) part of formula
def parseout_number(ch,gen):
nonlocal buffer
num=""
try:
while ch in digits:
num += ch
ch = next(gen)
# after number is parsed out and a non-number character is seen,
# add that non-number character to the buffer to be read next, dont miss parsing it
buffer.append(ch)
except StopIteration:
# while iterating to find the end digit of the number, we have reached the end of the formula,
# meaning the digit ch and subsequent characters were numbers and were the last thing in the formula
# the code, outside of try-catch handles all the possible scenerios of parsing the number out,
# so do nothing here. move along
pass
# if we saw a number, return it as integer, else return empty string
if num != "":
return int(num)
else:
return ""
#generator expression
formula_chars = (ch for ch in formula)
# iterate over all characters
for char in formula_chars:
# add the character emitted by generator into buffer for processing
buffer.append(char)
# process what ever is in the buffer queue
while buffer:
ch = buffer.pop(0)
# if the character is an upper case character
# set the a flag to indicate start of a new element name
# check if the previous elementname was added to the processing_stack (bracket_stacks)
# if not then add it, noting one atom for that element
# set the character to element_name variable
if ch in upper:
element_name_parse_start=True
if element_name is not None and element_count == "":
bracket_stacks[-1].append([element_name,1])
element_name = ch
# if character is lowercase, just concat it to the element_name
elif ch in lower:
element_name += ch
# if character is a numerical digit, then parse that number out completely as integer
# set the flag to indicate the reading the element name is done
# store the element name and it's corresponding count into the processing_stack
# reset the variables element_name and element_count, ready for next element
elif ch in digits:
element_name_parse_start=False
element_count = parseout_number(ch,formula_chars)
bracket_stacks[-1].append([element_name,element_count])
element_count = ""
element_name = None
# if open bracket is seen, check if reading the element_name flag is still True
# if it is then that element has one atom only
# add it to the processing stack
# set the flag to indicate that reading the 'element_name' is done and
# add another processing stack top the top of the 'bracket_stacks'
# this new processing stack will have the atom details within the bracket
# finally, reset all other variables to ensure
# clean slate for the new child 'processing-stack' before exiting the code-block
elif ch == "(":
if element_name_parse_start:
bracket_stacks[-1].append([element_name,1])
element_name_parse_start=False
element_count = ""
bracket_stacks.append([]) # new processing stack
element_name = None
# if a bracket is closed
# make sure we account for one atom of element, if a number was not seen before closing the bracket
# set the flag to indicate we are done reading element_name
# check what is the next character after the bracket close char.
# if it's a digit, then parse that number out
# that number is the multiplier for the current processing stack
# which means we will need to multiply every atom/element count by the multiplier
# at this point the current processing stack
# which was created as part of opening the bracket is processed
# so, merge what we found into the parent processing stack by
# extending the parent processing stack with the results of the child stack
elif ch == ")":
if element_name_parse_start:
bracket_stacks[-1].append([element_name,1])
element_name = None
element_name_parse_start=False
braket_multiplier = ""
try:
next_ch= next(formula_chars)
braket_multiplier = parseout_number(next_ch,formula_chars)
except StopIteration:
pass
if braket_multiplier == "":
braket_multiplier = 1
# pop the child processing - stack to be processed
process_this = bracket_stacks.pop()
#processing
for idx,_ in enumerate(process_this):
process_this[idx][1] = process_this[idx][1]*braket_multiplier
#merging processed child stack with the parent stack
bracket_stacks[-1].extend(process_this)
# if the new element name seen flag is set then process that
# atom by adding it's element-name and atom count to the current processing stack
if element_name_parse_start:
if element_name is not None:
if element_count != "":
bracket_stacks[-1].append([element_name,int(element_count)])
else:
bracket_stacks[-1].append([element_name,1])
# pop the top-level processing-stack, this should contain a 'flattened' version of the atoms and their counts
# note that the counts of elements are not aggregated yet,
# eg:If Oxygen was seen within a bracket and also seen outside that bracket,
# then we'll have two entries for Oxygen. We'll aggregate them next...
count_pairs = bracket_stacks.pop()
# aggregate all the 'flattened' data in 'count_pairs' variable, using a dictionary
for element_name,element_count in count_pairs:
count[element_name]+= element_count
# preparing the output string...
# create a list meant to hold the 'words' of the output string, based on the description
output=[]
# fetch the keylist
elements_list = list(count.keys())
#sort it
elements_list.sort()
# for each element in the sorted keylist, if the element has more
# than 1 atom, append the atom and it's count
# if element has only 1 atom only append the atom name,
# but don't append the atom's count (which is 1)
for element in elements_list:
if count[element] > 1:
output.append(element)
output.append(str(count[element]))
else:
output.append(element)
# output will now have an list of words representation of what we need. turn the list into a string and return it
return "".join(output) | https://leetcode.com/problems/number-of-atoms/discuss/1335787/efficient-O(N)-python3-solution-using-stack-of-stacks-with-explanation-of-code-and-approach | 2 | Given a string formula representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.
For example, "H2O" and "H2O2" are possible, but "H1O2" is impossible.
Two formulas are concatenated together to produce another formula.
For example, "H2O2He3Mg4" is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
For example, "(H2O2)" and "(H2O2)3" are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
Example 1:
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Constraints:
1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid. | efficient O(N) python3 solution, using stack of stacks with explanation of code and approach | 258 | number-of-atoms | 0.522 | anupamkumar | Hard | 11,932 | 726 |
self dividing numbers | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
result = []
for i in range(left, right+ 1):
if "0" in str(i): continue
val = i
while val > 0:
n = val % 10
if i % n != 0:
val = -1
val = val // 10
if val != -1: result.append(i)
return result | https://leetcode.com/problems/self-dividing-numbers/discuss/1233710/WEEB-DOES-PYTHON(BEATS-91.49) | 4 | A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
A self-dividing number is not allowed to contain the digit zero.
Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].
Example 1:
Input: left = 1, right = 22
Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]
Example 2:
Input: left = 47, right = 85
Output: [48,55,66,77]
Constraints:
1 <= left <= right <= 104 | WEEB DOES PYTHON(BEATS 91.49%) | 278 | self-dividing-numbers | 0.776 | Skywalker5423 | Easy | 11,934 | 728 |
my calendar i | # Binary Search Tree Solution -> If exact matching of intervals found then return False
# Else you can add this interval to that particular node's left or right
class Node:
def __init__(self, s, e):
self.s = s
self.e = e
self.left = None
self.right = None
class MyCalendar:
def __init__(self):
self.head = None
def insert(self, s, e, node):
if s >= node.e:
if node.right: return self.insert(s, e, node.right)
else:
nn = Node(s, e)
node.right = nn
return True
elif e <= node.s:
if node.left: return self.insert(s, e, node.left)
else:
nn = Node(s, e)
node.left = nn
return True
else: return False
def book(self, s: int, e: int) -> bool:
if self.head == None:
nn = Node(s, e)
self.head = nn
return True
return self.insert(s, e, self.head) | https://leetcode.com/problems/my-calendar-i/discuss/2731671/Fastest-Python-solution-greater-Create-a-Binary-Search-Tree | 0 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.
A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendar class:
MyCalendar() Initializes the calendar object.
boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.
Example 1:
Input
["MyCalendar", "book", "book", "book"]
[[], [10, 20], [15, 25], [20, 30]]
Output
[null, true, false, true]
Explanation
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
Constraints:
0 <= start < end <= 109
At most 1000 calls will be made to book. | Fastest Python solution -> Create a Binary Search Tree🥶 | 17 | my-calendar-i | 0.572 | shiv-codes | Medium | 11,969 | 729 |
count different palindromic subsequences | class Solution:
def countPalindromicSubsequences(self, s:str) -> int:
@cache
def fn(ch, i, j):
if i > j:
return 0
if i == j and s[i] == ch:
return 1
if s[i] == s[j] == ch:
return 2 + fn('a', i+1, j-1) + fn('b', i+1, j-1) + fn('c', i+1, j-1) + fn('d', i+1, j-1)
elif s[i] != ch:
return fn(ch, i+1, j)
elif s[j] != ch:
return fn(ch, i, j-1)
n = len(s)
return (fn('a', 0, n-1) + fn('b', 0, n-1) + fn('c', 0, n-1) + fn('d', 0, n-1)) % (10**9+7) | https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1612723/DP-Python | 2 | Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.
Example 1:
Input: s = "bccb"
Output: 6
Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
Example 2:
Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"
Output: 104860361
Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
Constraints:
1 <= s.length <= 1000
s[i] is either 'a', 'b', 'c', or 'd'. | DP Python | 469 | count-different-palindromic-subsequences | 0.445 | yshawn | Hard | 11,970 | 730 |
flood fill | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
h, w = len(image), len(image[0])
def dfs( r, c, src_color):
if r < 0 or c < 0 or r >= h or c >= w or image[r][c] == newColor or image[r][c] != src_color:
# Reject for invalid coordination, repeated traversal, or different color
return
# update color
image[r][c] = newColor
# DFS to 4-connected neighbors
dfs( r-1, c, src_color )
dfs( r+1, c, src_color )
dfs( r, c-1, src_color )
dfs( r, c+1, src_color )
# ---------------------------------------------------------------------------
dfs(sr, sc, src_color = image[sr][sc] )
return image | https://leetcode.com/problems/flood-fill/discuss/626424/PythonJSGoC%2B%2B-sol-by-DFS-w-Comment | 17 | An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
Return the modified image after performing the flood fill.
Example 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
Example 2:
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
Output: [[0,0,0],[0,0,0]]
Explanation: The starting pixel is already colored 0, so no changes are made to the image.
Constraints:
m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], color < 216
0 <= sr < m
0 <= sc < n | Python/JS/Go/C++ sol by DFS [w/ Comment] | 4,300 | flood-fill | 0.607 | brianchiang_tw | Easy | 11,975 | 733 |
asteroid collision | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for a in asteroids:
if a > 0:
stack.append(a)
else:
while stack and stack[-1] > 0 and stack[-1] + a < 0:
stack.pop()
if not stack or stack[-1] < 0:
stack.append(a)
elif stack[-1] + a == 0:
stack.pop()
return stack | https://leetcode.com/problems/asteroid-collision/discuss/646757/Python3-concise-solution-Asteroid-Collision | 5 | We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Constraints:
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0 | Python3 concise solution - Asteroid Collision | 426 | asteroid-collision | 0.444 | r0bertz | Medium | 12,030 | 735 |
parse lisp expression | class Solution:
def evaluate(self, expression: str) -> int:
stack = []
parenEnd = {}
# Get the end parenthesis location
for idx, ch in enumerate(expression):
if ch == '(':
stack.append(idx)
if ch == ')':
parenEnd[stack.pop()] = idx
# Parses the expression into a list, each new sublist is a set of parenthesis
# Example:
# Input: "(let x 2 (mult x (let x 3 y 4 (add x y))))"
# Output: ['let', 'x', '2', ['mult', 'x', ['let', 'x', '3', 'y', '4', ['add', 'x', 'y']]]]
def parse(lo, hi):
arr = []
word = []
i = lo
while i < hi:
if expression[i] == '(':
arr.append(parse(i + 1, parenEnd[i]))
i = parenEnd[i]
elif expression[i] == ' ' or expression[i] == ')' and word != []:
if ''.join(word) != '':
arr.append(''.join(word))
word = []
i += 1
elif expression[i] != ')':
word.append(expression[i])
i += 1
else:
i += 1
if word != []:
arr.append(''.join(word))
return arr
# Change string expression into the list expression
expressionList = parse(1, len(expression) - 1)
# Eval expression with starting scope (variables)
return self.genEval(expressionList, {})
def genEval(self, expression, scope):
if type(expression) != list:
# If expression is just a variable or int
try:
return int(expression)
except:
return scope[expression]
else:
if expression[0] == 'let':
# Remove "let" from expression list
expression = expression[1:]
# This loop updates the scope (variables)
while len(expression) > 2:
scope = self.letEval(expression, scope.copy())
expression = expression[2:]
# Return the last value
return self.genEval(expression[0], scope.copy())
if expression[0] == 'add':
return self.addEval(expression, scope.copy())
if expression[0] == 'mult':
return self.multEval(expression, scope.copy())
def letEval(self, expression, scope):
scope[expression[0]] = self.genEval(expression[1], scope)
return scope
def addEval(self, expression, scope):
return self.genEval(expression[1], scope) + self.genEval(expression[2], scope)
def multEval(self, expression, scope):
return self.genEval(expression[1], scope) * self.genEval(expression[2], scope) | https://leetcode.com/problems/parse-lisp-expression/discuss/2149196/Python3-Solution | 1 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
(An integer could be positive or negative.)
A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.
An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.
A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names.
Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
Example 1:
Input: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
Output: 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
Example 2:
Input: expression = "(let x 3 x 2 x)"
Output: 2
Explanation: Assignment in let statements is processed sequentially.
Example 3:
Input: expression = "(let x 1 y 2 x (add x y) (add x y))"
Output: 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
Constraints:
1 <= expression.length <= 2000
There are no leading or trailing spaces in expression.
All tokens are separated by a single space in expression.
The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.
The expression is guaranteed to be legal and evaluate to an integer. | Python3 Solution | 113 | parse-lisp-expression | 0.515 | krzys2194 | Hard | 12,056 | 736 |
monotone increasing digits | class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
nums = [int(x) for x in str(N)] # digits
stack = []
for i, x in enumerate(nums):
while stack and stack[-1] > x: x = stack.pop() - 1
stack.append(x)
if len(stack) <= i: break
return int("".join(map(str, stack)).ljust(len(nums), "9")) # right padding with "9" | https://leetcode.com/problems/monotone-increasing-digits/discuss/921119/Python3-O(N)-via-stack | 1 | An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.
Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.
Example 1:
Input: n = 10
Output: 9
Example 2:
Input: n = 1234
Output: 1234
Example 3:
Input: n = 332
Output: 299
Constraints:
0 <= n <= 109 | [Python3] O(N) via stack | 126 | monotone-increasing-digits | 0.471 | ye15 | Medium | 12,058 | 738 |
daily temperatures | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
result = [0] * len(temperatures) # having list with 0`s elements of same lenght as temperature array.
stack = [] # taking empty stack.
for index, temp in enumerate(temperatures): # Traversing through provided list.
while stack and temperatures[stack[-1]] < temp: # stack should not be empty and checking previous temp with current temp.
# the above while loop and taking stack for saving index is very common practice in monotonic stack questions. Suggestion: understand it properly.
prev_temp = stack.pop() # stack.pop() will provide index of prev temp, taking in separate var as we are using it more then on place.
result[prev_temp] = index - prev_temp #at the index of prev_temp and i - prev_temp by this we`ll get how many step we moved to have greater temp.
stack.append(index) # in case stack is empty we`ll push index in it.
return result # returing the list of number of days to wait. | https://leetcode.com/problems/daily-temperatures/discuss/2506436/Python-Stack-97.04-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack | 6 | Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100 | Python Stack 97.04% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack | 473 | daily-temperatures | 0.666 | rlakshay14 | Medium | 12,066 | 739 |
delete and earn | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
mp = {}
for x in nums: mp[x] = x + mp.get(x, 0)
@lru_cache(None)
def fn(i):
"""Return maximum points one can earn from nums[i:]."""
if i >= len(nums): return 0
if nums[i] + 1 not in mp: return mp[nums[i]] + fn(i+1)
return max(mp[nums[i]] + fn(i+2), fn(i+1))
nums = sorted(set(nums))
return fn(0) | https://leetcode.com/problems/delete-and-earn/discuss/916859/Python3-top-down-dp | 7 | You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Example 1:
Input: nums = [3,4,2]
Output: 6
Explanation: You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
- Delete 2 to earn 2 points. nums = [].
You earn a total of 6 points.
Example 2:
Input: nums = [2,2,3,3,3,4]
Output: 9
Explanation: You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
- Delete a 3 again to earn 3 points. nums = [3].
- Delete a 3 once more to earn 3 points. nums = [].
You earn a total of 9 points.
Constraints:
1 <= nums.length <= 2 * 104
1 <= nums[i] <= 104 | [Python3] top-down dp | 273 | delete-and-earn | 0.573 | ye15 | Medium | 12,113 | 740 |
cherry pickup | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
n = len(grid)
@lru_cache(None)
def fn(t, i, ii):
"""Return maximum cherries collected at kth step when two robots are at ith and iith row"""
j, jj = t - i, t - ii #columns
if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location
if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location
if t == 0: return grid[0][0] #starting from 0,0
return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii))
return max(0, fn(2*n-2, n-1, n-1)) | https://leetcode.com/problems/cherry-pickup/discuss/699169/Python3-dp | 2 | You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through,
1 means the cell contains a cherry that you can pick up and pass through, or
-1 means the cell contains a thorn that blocks your way.
Return the maximum number of cherries you can collect by following the rules below:
Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).
After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.
When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.
If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.
Example 1:
Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]
Output: 5
Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Example 2:
Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]
Output: 0
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
grid[i][j] is -1, 0, or 1.
grid[0][0] != -1
grid[n - 1][n - 1] != -1 | [Python3] dp | 241 | cherry-pickup | 0.363 | ye15 | Hard | 12,161 | 741 |
network delay time | class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj_list = defaultdict(list)
for x,y,w in times:
adj_list[x].append((w, y))
visited=set()
heap = [(0, k)]
while heap:
travel_time, node = heapq.heappop(heap)
visited.add(node)
if len(visited)==n:
return travel_time
for time, adjacent_node in adj_list[node]:
if adjacent_node not in visited:
heapq.heappush(heap, (travel_time+time, adjacent_node))
return -1 | https://leetcode.com/problems/network-delay-time/discuss/2036405/Python-Simple-Dijkstra-Beats-~90 | 39 | You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Example 2:
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Example 3:
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Constraints:
1 <= k <= n <= 100
1 <= times.length <= 6000
times[i].length == 3
1 <= ui, vi <= n
ui != vi
0 <= wi <= 100
All the pairs (ui, vi) are unique. (i.e., no multiple edges.) | Python Simple Dijkstra Beats ~90% | 2,200 | network-delay-time | 0.515 | constantine786 | Medium | 12,164 | 743 |
find smallest letter greater than target | class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
# if the number is out of bound
if target >= letters[-1] or target < letters[0]:
return letters[0]
low = 0
high = len(letters)-1
while low <= high:
mid = (high+low)//2
if target >= letters[mid]: # in binary search this would be only greater than
low = mid+1
if target < letters[mid]:
high = mid-1
return letters[low] | https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/1568523/Python-easy-solution-with-detail-explanation-(modified-binary-search) | 71 | You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.
Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.
Example 1:
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.
Example 2:
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.
Example 3:
Input: letters = ["x","x","y","y"], target = "z"
Output: "x"
Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].
Constraints:
2 <= letters.length <= 104
letters[i] is a lowercase English letter.
letters is sorted in non-decreasing order.
letters contains at least two different characters.
target is a lowercase English letter. | Python easy solution with detail explanation (modified binary search) | 3,300 | find-smallest-letter-greater-than-target | 0.448 | Abeni | Easy | 12,197 | 744 |
min cost climbing stairs | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
cur = 0
dp0 = cost[0]
if len(cost) >= 2:
dp1 = cost[1]
for i in range(2, len(cost)):
cur = cost[i] + min(dp0, dp1)
dp0 = dp1
dp1 = cur
return min(dp0, dp1) | https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2260902/94-FASTER-97-Space-Efficient-Python-solutions-Different-approaches | 34 | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
Constraints:
2 <= cost.length <= 1000
0 <= cost[i] <= 999 | 94% FASTER 97% Space Efficient Python solutions Different approaches | 2,300 | min-cost-climbing-stairs | 0.625 | anuvabtest | Easy | 12,252 | 746 |
largest number at least twice of others | class Solution:
def dominantIndex(self, nums: List[int]) -> int:
if len(nums) is 1:
return 0
dom = max(nums)
i = nums.index(dom)
nums.remove(dom)
if max(nums) * 2 <= dom:
return i
return -1 | https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2069691/no-loops | 3 | You are given an integer array nums where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.
Constraints:
2 <= nums.length <= 50
0 <= nums[i] <= 100
The largest element in nums is unique. | no loops | 90 | largest-number-at-least-twice-of-others | 0.465 | andrewnerdimo | Easy | 12,316 | 747 |
shortest completing word | class Solution:
def shortestCompletingWord(self, P: str, words: List[str]) -> str:
alphs=""
res=""
for p in P:
if p.isalpha():
alphs+=p.lower()
for word in words:
if all(alphs.count(alphs[i]) <= word.count(alphs[i]) for i in range(len(alphs))):
if res=="" or len(res)>len(word):
res=word
return res | https://leetcode.com/problems/shortest-completing-word/discuss/1277850/Python3-Simple-solution-without-Dictionary | 4 | Given a string licensePlate and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.
For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
Example 1:
Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.
Example 2:
Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]
Output: "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.
Constraints:
1 <= licensePlate.length <= 7
licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i] consists of lower case English letters. | Python3 Simple solution without Dictionary | 335 | shortest-completing-word | 0.592 | Rei4126 | Easy | 12,352 | 748 |
contain virus | class Solution:
def containVirus(self, mat: List[List[int]]) -> int:
m,n = len(mat),len(mat[0])
def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area
if 0<=i<m and 0<=j<n and (i,j) not in visited:
if mat[i][j]==2: # Already quarantined cell
return 0
if mat[i][j]==0:
nextInfected.add((i,j)) # add cell which will be infected next day
return 1 # require one wall to quarantined cell from one side
else:
visited.add((i,j))
return dfs(i-1,j,visited,nextInfected) + dfs(i+1,j,visited,nextInfected) + dfs(i,j-1,visited,nextInfected) + dfs(i,j+1,visited,nextInfected) # traverse all four direction
else:
return 0
ans = 0
while True: # this loop running "how many days we should installing the walls" times
# For every day check which area infect more cells
visited = set() # Using in dfs
All_nextinfect = set()
stop , walls = set(),0 # here stop store the indices of maximum no. of cells in which we stop spreading of virus this day
for i in range(m):
for j in range(n):
if mat[i][j]==1 and (i,j) not in visited:
nextInfected = set()
a = dfs(i,j,visited,nextInfected)
if len(stop)<len(nextInfected):
All_nextinfect = All_nextinfect | stop # leave previous saved area from virus
stop = nextInfected # pick new area which we want to save
walls = a # require walls
p,q = i,j # starting position(indices) of this area
else:
All_nextinfect = All_nextinfect | nextInfected
if not stop : # if our job is done i.e. No cell will be infect Later
break
ans += walls # add new walls installed this day
# change each cell value to 2 which will be covered by quarantined area
def fun(p,q):
if 0<=p<m and 0<=q<n and mat[p][q]==1:
mat[p][q]=2
fun(p+1,q)
fun(p-1,q)
fun(p,q-1)
fun(p,q+1)
fun(p,q) # start dfs from start point of quarantined area
for a,b in All_nextinfect: # set new infected cell value = 1 for iterating next day
mat[a][b] = 1
return ans # Final answer | https://leetcode.com/problems/contain-virus/discuss/2224726/Pyhon-Easy-Solution-oror-DFS-oror-Time-O(m*n*max(m-n))-oror-Faster | 4 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
Example 1:
Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]
Output: 10
Explanation: There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
Example 2:
Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]]
Output: 4
Explanation: Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
Example 3:
Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]
Output: 13
Explanation: The region on the left only builds two new walls.
Constraints:
m == isInfected.length
n == isInfected[i].length
1 <= m, n <= 50
isInfected[i][j] is either 0 or 1.
There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round. | Pyhon Easy Solution || DFS || Time O(m*n*max(m , n)) || Faster | 378 | contain-virus | 0.509 | Laxman_Singh_Saini | Hard | 12,362 | 749 |
open the lock | class Solution:
def openLock(self, deadends: List[str], end: str) -> int:
if end in deadends or "0000" in deadends:
return -1
if end == "0000":
return 0
start, end, deadends = 0, int(end), {int(deadend) for deadend in deadends}
def distance(cur: int, target: int) -> int:
diff = 0
for _ in range(4):
a, b = cur % 10, target % 10
d = abs(a - b)
diff += min(d, 10 - d)
cur, target = cur // 10, target // 10
return diff
def turn_knob(cur: int, idx: int) -> Tuple[int, int]:
index = 10 ** idx
digit = cur // index % 10
up = cur - 9 * index if digit == 9 else cur + index
down = cur - index if digit else cur + 9 * index
return up, down
def process(
this_q: List[int], this_v: Dict[int, int], other_v: Dict[int, int], target: int
) -> int:
_, cur = heappop(this_q)
step = this_v[cur]
for i in range(4):
up, down = turn_knob(cur, i)
if up in other_v:
return step + other_v[up] + 1
if down in other_v:
return step + other_v[down] + 1
if up not in deadends and up not in this_v:
this_v[up] = step + 1
this_q.append((distance(up, target), up))
if down not in deadends and down not in this_v:
this_v[down] = step + 1
this_q.append((distance(down, target), down))
heapify(this_q)
return None
s_q, s_v = [(distance(start, end), start)], {start: 0}
e_q, e_v = [(distance(end, start), end)], {end: 0}
while s_q and e_q:
s = process(s_q, s_v, e_v, end)
if s: return s
e = process(e_q, e_v, s_v, start)
if e: return e
return -1 | https://leetcode.com/problems/open-the-lock/discuss/1251501/Python-or-Bi-directional-A-star-BFS-or-99.7-or-52ms-or-14.3MB | 3 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
Example 1:
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".
Example 2:
Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
Example 3:
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
Output: -1
Explanation: We cannot reach the target without getting stuck.
Constraints:
1 <= deadends.length <= 500
deadends[i].length == 4
target.length == 4
target will not be in the list deadends.
target and deadends[i] consist of digits only. | Python | Bi-directional A star, BFS | 99.7% | 52ms | 14.3MB | 110 | open-the-lock | 0.555 | PuneethaPai | Medium | 12,365 | 752 |
cracking the safe | class Solution:
def crackSafe(self, n: int, k: int) -> str:
def dfs(path, visitedCombinations, targetNumVisited, combos):
# Base Case. We've visited all possible combinations
if len(visitedCombinations) == targetNumVisited:
combos.append(''.join([str(x) for x in path]))
return True
# This if/else is necessary to prevent Python from picking up the first element if n = 1
if n > 1:
lastDigits = ''.join([str(x) for x in path[-(n-1):]])
else:
lastDigits = ''
for i in range(k):
path.append(i)
newPwd = f'{lastDigits}{i}'
# We have not reached the minimum pwd length. Continue recursion
if len(newPwd) != n:
if dfs(path, visitedCombinations, targetNumVisited, combos):
return True
if len(newPwd) == n and newPwd not in visitedCombinations:
visitedCombinations[newPwd] = 1
if dfs(path, visitedCombinations, targetNumVisited, combos):
return True
del visitedCombinations[newPwd]
path.pop()
return False
# Empty visited Combinations hash set
visitedCombinations = {}
combos = []
dfs([], visitedCombinations, k**n, combos)
return combos[0] | https://leetcode.com/problems/cracking-the-safe/discuss/2825347/DFS-Solution-in-Python | 0 | There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.
For example, the correct password is "345" and you enter in "012345":
After typing 0, the most recent 3 digits is "0", which is incorrect.
After typing 1, the most recent 3 digits is "01", which is incorrect.
After typing 2, the most recent 3 digits is "012", which is incorrect.
After typing 3, the most recent 3 digits is "123", which is incorrect.
After typing 4, the most recent 3 digits is "234", which is incorrect.
After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks.
Return any string of minimum length that will unlock the safe at some point of entering it.
Example 1:
Input: n = 1, k = 2
Output: "10"
Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.
Example 2:
Input: n = 2, k = 2
Output: "01100"
Explanation: For each possible password:
- "00" is typed in starting from the 4th digit.
- "01" is typed in starting from the 1st digit.
- "10" is typed in starting from the 3rd digit.
- "11" is typed in starting from the 2nd digit.
Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.
Constraints:
1 <= n <= 4
1 <= k <= 10
1 <= kn <= 4096 | DFS Solution in Python | 1 | cracking-the-safe | 0.555 | user0138r | Hard | 12,382 | 753 |
reach a number | class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
step = 0
far = 0
while far < target or far%2 != target%2:
step += 1
far +=step
return step | https://leetcode.com/problems/reach-a-number/discuss/991390/Python-Dummy-math-solution-easy-to-understand | 1 | You are standing at position 0 on an infinite number line. There is a destination at position target.
You can make some number of moves numMoves so that:
On each move, you can either go left or right.
During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.
Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.
Example 1:
Input: target = 2
Output: 3
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
Example 2:
Input: target = 3
Output: 2
Explanation:
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
Constraints:
-109 <= target <= 109
target != 0 | [Python] Dummy math solution, easy to understand | 47 | reach-a-number | 0.426 | KevinZzz666 | Medium | 12,384 | 754 |
pyramid transition matrix | class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
mp = {}
for x, y, z in allowed: mp.setdefault((x, y), set()).add(z)
def fn(row):
"""Return list of rows built from given row."""
ans = [""]
for x, y in zip(row, row[1:]):
if (x, y) not in mp: return []
ans = [xx + zz for xx in ans for zz in mp[x, y]]
return ans
# dfs
stack = [bottom]
while stack:
row = stack.pop()
if len(row) == 1: return True
stack.extend(fn(row))
return False | https://leetcode.com/problems/pyramid-transition-matrix/discuss/921324/Python3-progressively-building-new-rows | 2 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left bottom and 'A' is on the right bottom.
You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.
Given bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.
Example 1:
Input: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]
Output: true
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.
There are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed.
Example 2:
Input: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"]
Output: false
Explanation: The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
Constraints:
2 <= bottom.length <= 6
0 <= allowed.length <= 216
allowed[i].length == 3
The letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.
All the values of allowed are unique. | [Python3] progressively building new rows | 215 | pyramid-transition-matrix | 0.531 | ye15 | Medium | 12,387 | 756 |
set intersection size at least two | class Solution:
def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x:x[1])
size = 0
prev_start = -1
prev_end = -1
for curr_start, curr_end in intervals:
if prev_start == -1 or prev_end < curr_start: #if intervals do not overlap
size += 2
prev_start = curr_end-1
prev_end = curr_end
elif prev_start < curr_start: #if intervals overlap
if prev_end != curr_end:
prev_start = prev_end
prev_end = curr_end
else:
prev_start = curr_end-1
prev_end = curr_end
size += 1
return size | https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/2700915/Python-Explained-or-O(nlogn) | 1 | You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.
A containing set is an array nums where each interval from intervals has at least two integers in nums.
For example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets.
Return the minimum possible size of a containing set.
Example 1:
Input: intervals = [[1,3],[3,7],[8,9]]
Output: 5
Explanation: let nums = [2, 3, 4, 8, 9].
It can be shown that there cannot be any containing array of size 4.
Example 2:
Input: intervals = [[1,3],[1,4],[2,5],[3,5]]
Output: 3
Explanation: let nums = [2, 3, 4].
It can be shown that there cannot be any containing array of size 2.
Example 3:
Input: intervals = [[1,2],[2,3],[2,4],[4,5]]
Output: 5
Explanation: let nums = [1, 2, 3, 4, 5].
It can be shown that there cannot be any containing array of size 4.
Constraints:
1 <= intervals.length <= 3000
intervals[i].length == 2
0 <= starti < endi <= 108 | Python [Explained] | O(nlogn) | 545 | set-intersection-size-at-least-two | 0.439 | diwakar_4 | Hard | 12,391 | 757 |
special binary string | class Solution:
def makeLargestSpecial(self, s: str) -> str:
l = 0
balance = 0
sublist = []
for r in range(len(s)):
balance += 1 if s[r]=='1' else -1
if balance==0:
sublist.append("1" + self.makeLargestSpecial(s[l+1:r])+ "0")
l = r+1
sublist.sort(reverse=True)
return ''.join(sublist) | https://leetcode.com/problems/special-binary-string/discuss/1498369/Easy-Approach-oror-Well-Explained-oror-Substring | 5 | Special binary strings are binary strings with the following two properties:
The number of 0's is equal to the number of 1's.
Every prefix of the binary string has at least as many 1's as 0's.
You are given a special binary string s.
A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
Example 1:
Input: s = "11011000"
Output: "11100100"
Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped.
This is the lexicographically largest string possible after some number of swaps.
Example 2:
Input: s = "10"
Output: "10"
Constraints:
1 <= s.length <= 50
s[i] is either '0' or '1'.
s is a special binary string. | 📌📌 Easy-Approach || Well-Explained || Substring 🐍 | 371 | special-binary-string | 0.604 | abhi9Rai | Hard | 12,394 | 761 |
prime number of set bits in binary representation | class Solution:
def isPrime(self,x):
flag=0
if x==1:
return False
for i in range(2,x):
if x%i==0:
flag=1
break
if flag==1:
return False
return True
def countPrimeSetBits(self, left: int, right: int) -> int:
arr_dict={}
lst=list(range(left,right+1))
for i in lst:
if i not in arr_dict:
arr_dict[i]=bin(i).replace("0b","")
arr=list(arr_dict.values())
count=0
for i in arr:
if self.isPrime(i.count('1')):
# print(i)
count+=1
return count | https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1685874/Simple-python-code | 1 | Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1's present when written in binary.
For example, 21 written in binary is 10101, which has 3 set bits.
Example 1:
Input: left = 6, right = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
8 -> 1000 (1 set bit, 1 is not prime)
9 -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
4 numbers have a prime number of set bits.
Example 2:
Input: left = 10, right = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
5 numbers have a prime number of set bits.
Constraints:
1 <= left <= right <= 106
0 <= right - left <= 104 | Simple python code | 105 | prime-number-of-set-bits-in-binary-representation | 0.678 | amannarayansingh10 | Easy | 12,396 | 762 |
partition labels | class Solution:
def partitionLabels(self, s: str) -> List[int]:
L = len(s)
last = {s[i]: i for i in range(L)} # last appearance of the letter
i, ans = 0, []
while i < L:
end, j = last[s[i]], i + 1
while j < end: # validation of the part [i, end]
if last[s[j]] > end:
end = last[s[j]] # extend the part
j += 1
ans.append(end - i + 1)
i = end + 1
return ans | https://leetcode.com/problems/partition-labels/discuss/1868757/Python3-GREEDY-VALIDATION-(-)-Explained | 63 | You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
Example 1:
Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters. | ✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained | 5,700 | partition-labels | 0.798 | artod | Medium | 12,410 | 763 |
largest plus sign | class Solution:
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
mat = [[1]*N for _ in range(N)]
for x, y in mines: mat[x][y] = 0 # create matrix with mine
up = [[0]*N for _ in range(N)] # count 1s above mat[i][j] if mat[i][j] is 1
for i in range(N):
for j in range(N):
if mat[i][j]:
up[i][j] = 1
if i > 0: up[i][j] += up[i-1][j]
down = [[0]*N for _ in range(N)] # count 1s below mat[i][j] if mat[i][j] is 1
for i in range(N-1, -1, -1):
for j in range(N):
if mat[i][j]:
down[i][j] = 1
if i < N-1: down[i][j] += down[i+1][j]
left = [[0]*N for _ in range(N)] # count 1s on the left side of mat[i][j] if mat[i][j] is 1
for i in range(N):
for j in range(N):
if mat[i][j]:
left[i][j] = 1
if j > 0: left[i][j] += left[i][j-1]
right = [[0]*N for _ in range(N)] # count 1s on the right side of mat[i][j] if mat[i][j] is 1
for i in range(N):
for j in range(N-1, -1, -1):
if mat[i][j]:
right[i][j] = 1
if j < N-1: right[i][j] += right[i][j+1]
# find the largest + sign by using cached directions information
return max(min([up[i][j], down[i][j], left[i][j], right[i][j]]) for i in range(N) for j in range(N)) | https://leetcode.com/problems/largest-plus-sign/discuss/833937/Python-3-or-DP-Bomb-Enemy-or-Explanations | 5 | You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.
An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.
Example 1:
Input: n = 5, mines = [[4,2]]
Output: 2
Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.
Example 2:
Input: n = 1, mines = [[0,0]]
Output: 0
Explanation: There is no plus sign, so return 0.
Constraints:
1 <= n <= 500
1 <= mines.length <= 5000
0 <= xi, yi < n
All the pairs (xi, yi) are unique. | Python 3 | DP - Bomb Enemy | Explanations | 396 | largest-plus-sign | 0.484 | idontknoooo | Medium | 12,461 | 764 |
couples holding hands | class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
loc = {x: i for i, x in enumerate(row)}
ans = 0
for i in range(0, len(row), 2):
p = row[i] - 1 if row[i]&1 else row[i]+1
if row[i+1] != p:
ans += 1
ii = loc[p]
loc[row[i+1]], loc[row[ii]] = loc[row[ii]], loc[row[i+1]] # swap mappings
row[i+1], row[ii] = row[ii], row[i+1] # swap values
return ans | https://leetcode.com/problems/couples-holding-hands/discuss/1258087/Python3-a-few-approaches | 3 | There are n couples sitting in 2n seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).
Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
Example 1:
Input: row = [0,2,1,3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:
Input: row = [3,2,0,1]
Output: 0
Explanation: All couples are already seated side by side.
Constraints:
2n == row.length
2 <= n <= 30
n is even.
0 <= row[i] < 2n
All the elements of row are unique. | [Python3] a few approaches | 84 | couples-holding-hands | 0.569 | ye15 | Hard | 12,469 | 765 |
toeplitz matrix | class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]])->bool:
r_len, c_len = len(matrix),len(matrix[0])
for r in range (1, r_len):
for c in range (1, c_len):
if matrix[r][c]!=matrix[r-1][c-1]:
return False
return True | https://leetcode.com/problems/toeplitz-matrix/discuss/2761795/Python-Simple-and-Easy-Way-to-Solve-or-97-Faster | 3 | Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The diagonal "[1, 2]" has different elements.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Follow up:
What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
What if the matrix is so large that you can only load up a partial row into the memory at once? | ✔️ Python Simple and Easy Way to Solve | 97% Faster 🔥 | 182 | toeplitz-matrix | 0.688 | pniraj657 | Easy | 12,473 | 766 |
reorganize string | class Solution:
def reorganizeString(self, S: str) -> str:
counter = collections.Counter(S)
i, res, n = 0, [None] * len(S), len(S)
for k in sorted(counter, key = counter.get, reverse = True):
if counter[k] > n // 2 + (n % 2): return ""
for j in range(counter[k]):
if i >= n: i = 1
res[i] = k; i += 2
return "".join(res) | https://leetcode.com/problems/reorganize-string/discuss/488325/Python-8-Liner-Memory-usage-less-than-100 | 9 | Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters. | Python - 8 Liner - Memory usage less than 100% | 1,700 | reorganize-string | 0.528 | mmbhatk | Medium | 12,530 | 767 |
max chunks to make sorted ii | class Solution:
def maxChunksToSorted(self, nums: List[int]) -> int:
st = []
for n in nums:
if len(st)==0 or st[-1]<=n:
st.append(n)
else:
ma = st[-1]
while st and st[-1]>n:
ma = max(ma,st.pop())
st.append(ma)
return len(st) | https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1498733/Easy-to-Understand-oror-98-faster-oror-Well-Explained | 14 | You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Constraints:
1 <= arr.length <= 2000
0 <= arr[i] <= 108 | 📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍 | 659 | max-chunks-to-make-sorted-ii | 0.528 | abhi9Rai | Hard | 12,556 | 768 |
max chunks to make sorted | class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stack = []
for num in arr:
lagest = num
while stack and num < stack[-1]:
lagest = max(lagest, stack.pop())
stack.append(lagest)
return len(stack) | https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1579999/Python3-Solution-with-using-stack | 1 | You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2:
Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
Constraints:
n == arr.length
1 <= n <= 10
0 <= arr[i] < n
All the elements of arr are unique. | [Python3] Solution with using stack | 95 | max-chunks-to-make-sorted | 0.582 | maosipov11 | Medium | 12,563 | 769 |
jewels and stones | class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(i in J for i in S)
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(S.count(i) for i in J)
from collections import Counter
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(Counter(S)[i] for i in J)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/jewels-and-stones/discuss/362196/Solution-in-Python-3-(beats-~94)-(one-line)-(three-solutions) | 28 | You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
Constraints:
1 <= jewels.length, stones.length <= 50
jewels and stones consist of only English letters.
All the characters of jewels are unique. | Solution in Python 3 (beats ~94%) (one line) (three solutions) | 4,500 | jewels-and-stones | 0.881 | junaidmansuri | Easy | 12,569 | 771 |
sliding puzzle | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
def isSolved(board):
if board[-1] != 0: return False
for i in range(5):
if board[i] != i + 1: return False
return True
swap = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4],
4: [1, 3, 5],
5: [2, 4],
}
q = [board[0] + board[1]]
steps = 0
seen = set()
while (len(q)):
new_q = []
for board in q:
if tuple(board) in seen: continue
seen.add(tuple(board))
if isSolved(board): return steps
zeroIdx = board.index(0)
for swapIdx in swap[zeroIdx]:
copy = board.copy()
copy[zeroIdx], copy[swapIdx] = copy[swapIdx], copy[zeroIdx]
new_q.append(copy)
steps += 1
q = new_q
return -1 | https://leetcode.com/problems/sliding-puzzle/discuss/2831256/Python-BFS%3A-77-time-70-space | 0 | On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Example 1:
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Example 2:
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Example 3:
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Constraints:
board.length == 2
board[i].length == 3
0 <= board[i][j] <= 5
Each value board[i][j] is unique. | Python BFS: 77% time, 70% space | 2 | sliding-puzzle | 0.639 | hqz3 | Hard | 12,629 | 773 |
global and local inversions | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
for i, a in enumerate(A):
if (abs(a - i) > 1):
return False
return True | https://leetcode.com/problems/global-and-local-inversions/discuss/1084172/(Optimal-Solution)-Thinking-Process-Explained-in-More-Detail-than-You'd-Ever-Want | 3 | You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i where:
0 <= i < n - 1
nums[i] > nums[i + 1]
Return true if the number of global inversions is equal to the number of local inversions.
Example 1:
Input: nums = [1,0,2]
Output: true
Explanation: There is 1 global inversion and 1 local inversion.
Example 2:
Input: nums = [1,2,0]
Output: false
Explanation: There are 2 global inversions and 1 local inversion.
Constraints:
n == nums.length
1 <= n <= 105
0 <= nums[i] < n
All the integers of nums are unique.
nums is a permutation of all the numbers in the range [0, n - 1]. | (Optimal Solution) Thinking Process Explained in More Detail than You'd Ever Want | 215 | global-and-local-inversions | 0.436 | valige7091 | Medium | 12,635 | 775 |
swap adjacent in lr string | class Solution:
def canTransform(self, S, E):
L, R, X = 0, 0, 0
for i, j in zip(S, E):
L += (j == 'L')
R += (i == 'R')
if i == 'R' and L: return False
if j == 'L' and R: return False
L -= (i == 'L')
R -= (j == 'R')
if L < 0 or R < 0: return False
X += (i == 'X') - (j == 'X')
return X == 0 | https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2712752/Python3-Solution-or-O(n)-or-Clean-and-Concise | 0 | In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.
Example 1:
Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: true
Explanation: We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX
Example 2:
Input: start = "X", end = "L"
Output: false
Constraints:
1 <= start.length <= 104
start.length == end.length
Both start and end will only consist of characters in 'L', 'R', and 'X'. | ✔ Python3 Solution | O(n) | Clean and Concise | 10 | swap-adjacent-in-lr-string | 0.371 | satyam2001 | Medium | 12,645 | 777 |
swim in rising water | class Solution:
# O(max(n^2, m)) time, h --> the highest elevation in the grid
# O(n^2) space,
# Approach: BFS, Priority queue
# I wld advise to do task scheduler question, it's pretty similar
# except that u apply bfs to traverse the grid 4 directionally
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
if n == 1:
return 0
def getNeighbours(coord: Tuple) -> List[Tuple]:
i, j = coord
n = len(grid)
neighbours = []
if i < n-1:
neighbours.append((i+1, j))
if i > 0:
neighbours.append((i-1, j))
if j < n-1:
neighbours.append((i, j+1))
if j > 0:
neighbours.append((i, j-1))
return neighbours
qu = deque()
waiting_qu = []
vstd = set()
waiting_qu.append([grid[0][0], (0, 0)])
vstd.add((0, 0))
time = 0
while waiting_qu:
time +=1
while waiting_qu and waiting_qu[0][0] <= time:
qu.append(heapq.heappop(waiting_qu)[1])
while qu:
cell = qu.popleft()
if cell == (n-1, n-1):
return time
nbrs = getNeighbours(cell)
for nb in nbrs:
if nb in vstd: continue
x, y = nb
elevation = grid[x][y]
vstd.add(nb)
if elevation > time:
heapq.heappush(waiting_qu, [elevation, nb])
else:
qu.append(nb)
return -1 | https://leetcode.com/problems/swim-in-rising-water/discuss/2464943/Easy-to-follow-python3-solutoon | 1 | You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).
Example 1:
Input: grid = [[0,2],[1,3]]
Output: 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
Example 2:
Input: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output: 16
Explanation: The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
Constraints:
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] < n2
Each value grid[i][j] is unique. | Easy to follow python3 solutoon | 34 | swim-in-rising-water | 0.597 | destifo | Hard | 12,652 | 778 |
k th symbol in grammar | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if N == 1:
return 0
half = 2**(N - 2)
if K > half:
return 1 if self.kthGrammar(N - 1, K - half) == 0 else 0
else:
return self.kthGrammar(N - 1, K) | https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/945679/Python-recursive-everything-you-need-to-know | 6 | We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Example 1:
Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0
Example 2:
Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
row 2: 01
Example 3:
Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
row 2: 01
Constraints:
1 <= n <= 30
1 <= k <= 2n - 1 | Python recursive, everything you need to know | 343 | k-th-symbol-in-grammar | 0.409 | lattices | Medium | 12,665 | 779 |
reaching points | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
if sx > tx or sy > ty: return False
if sx == tx: return (ty-sy)%sx == 0 # only change y
if sy == ty: return (tx-sx)%sy == 0
if tx > ty:
return self.reachingPoints(sx, sy, tx%ty, ty) # make sure tx%ty < ty
elif tx < ty:
return self.reachingPoints(sx, sy, tx, ty%tx)
else:
return False | https://leetcode.com/problems/reaching-points/discuss/808072/Python-recursive-solution-runtime-beats-98.91 | 14 | Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.
The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).
Example 1:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: true
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
Example 2:
Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: false
Example 3:
Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: true
Constraints:
1 <= sx, sy, tx, ty <= 109 | Python recursive solution runtime beats 98.91 % | 3,300 | reaching-points | 0.324 | yiz486 | Hard | 12,688 | 780 |
rabbits in forest | class Solution:
def numRabbits(self, answers: List[int]) -> int:
return sum((key+1) * math.ceil(freq / (key+1)) if key+1 < freq else key+1 for key, freq in collections.Counter(answers).items()) | https://leetcode.com/problems/rabbits-in-forest/discuss/838445/Python-3-or-Hash-Table-1-liner-or-Explanations | 1 | There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
Input: answers = [10,10,10]
Output: 11
Constraints:
1 <= answers.length <= 1000
0 <= answers[i] < 1000 | Python 3 | Hash Table 1 liner | Explanations | 178 | rabbits-in-forest | 0.552 | idontknoooo | Medium | 12,696 | 781 |
transform to chessboard | class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
n = len(board)
def fn(vals):
"""Return min moves to transform to chessboard."""
total = odd = 0
for i, x in enumerate(vals):
if vals[0] == x:
total += 1
if i&1: odd += 1
elif vals[0] ^ x != (1 << n) - 1: return inf
ans = inf
if len(vals) <= 2*total <= len(vals)+1: ans = min(ans, odd)
if len(vals)-1 <= 2*total <= len(vals): ans = min(ans, total - odd)
return ans
rows, cols = [0]*n, [0]*n
for i in range(n):
for j in range(n):
if board[i][j]:
rows[i] ^= 1 << j
cols[j] ^= 1 << i
ans = fn(rows) + fn(cols)
return ans if ans < inf else -1 | https://leetcode.com/problems/transform-to-chessboard/discuss/1305763/Python3-alternating-numbers | 8 | You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output: 2
Explanation: One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]]
Output: 0
Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]]
Output: -1
Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Constraints:
n == board.length
n == board[i].length
2 <= n <= 30
board[i][j] is either 0 or 1. | [Python3] alternating numbers | 379 | transform-to-chessboard | 0.518 | ye15 | Hard | 12,706 | 782 |
minimum distance between bst nodes | class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
# list with two element
# the first for the previous element
# the second for the min value
pre_mn = [-float("inf"), float("inf")]
def dfs(tree):
if not tree:
return
# Keep going to the left
dfs(tree.left)
# if we can't go further, update min and pre
pre_mn[1] = min(pre_mn[1], abs(tree.val) - pre_mn[0])
pre_mn[0] = tree.val
# keep traversing in-order
dfs(tree.right)
dfs(root)
# return min (the second element in the list)
return pre_mn[1] | https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1957176/Python-In-Order-Traversal-Explained-Well-Via-Comments | 1 | Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 100].
0 <= Node.val <= 105
Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/ | Python In-Order Traversal, Explained Well Via Comments | 89 | minimum-distance-between-bst-nodes | 0.569 | Hejita | Easy | 12,707 | 783 |
letter case permutation | class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
def backtrack(sub="", i=0):
if len(sub) == len(S):
res.append(sub)
else:
if S[i].isalpha():
backtrack(sub + S[i].swapcase(), i + 1)
backtrack(sub + S[i], i + 1)
res = []
backtrack()
return res | https://leetcode.com/problems/letter-case-permutation/discuss/379928/Python-clear-solution | 164 | Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example 1:
Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: s = "3z4"
Output: ["3z4","3Z4"]
Constraints:
1 <= s.length <= 12
s consists of lowercase English letters, uppercase English letters, and digits. | Python clear solution | 7,000 | letter-case-permutation | 0.735 | DenysCoder | Medium | 12,721 | 784 |
is graph bipartite | class Solution:
def isBipartite(self, graph: list[list[int]]) -> bool:
vis = [False for n in range(0, len(graph))]
while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated
ind = vis.index(False) # Find the first entry in the visited list that is false
vis[ind] = True
grp = {ind:True} # initialize first node as part of group 1
q = [ind] # Add current index to queue
while q: # Go to each node in the graph
u = q.pop(0)
for v in graph[u]: # Go to each vertice connected to the current node
if vis[v] == True: # If visited check that it is in the opposite group of the current node
if grp[u] == grp[v]:
return False # If a single edge does not lead to a group change return false
else: # If not visited put v in opposite group of u, set to visited, and append to q
vis[v] = True
grp[v] = not grp[u]
q.append(v)
return True | https://leetcode.com/problems/is-graph-bipartite/discuss/1990803/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022 | 3 | There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Example 1:
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
Output: false
Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
Input: graph = [[1,3],[0,2],[1,3],[0,2]]
Output: true
Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
Constraints:
graph.length == n
1 <= n <= 100
0 <= graph[u].length < n
0 <= graph[u][i] <= n - 1
graph[u] does not contain u.
All the values of graph[u] are unique.
If graph[u] contains v, then graph[v] contains u. | [Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022 | 356 | is-graph-bipartite | 0.527 | cucerdariancatalin | Medium | 12,773 | 785 |
k th smallest prime fraction | class Solution:
def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
if len(arr) > 2:
res = [] # list for storing the list: [prime fraction of arr[i]/arr[j], arr[i], arr[j]]
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# creating and adding the sublist to res
tmp = [arr[i] / arr[j], arr[i], arr[j]]
res.append(tmp)
# sorting res on the basis of value of arr[i]
res.sort(key=lambda x: x[0])
# creating and returning the required list
return [res[k - 1][1], res[k - 1][2]]
else:
return arr | https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2121258/Explained-Easiest-Python-Solution | 2 | You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.
For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].
Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].
Example 1:
Input: arr = [1,2,3,5], k = 3
Output: [2,5]
Explanation: The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
The third fraction is 2/5.
Example 2:
Input: arr = [1,7], k = 1
Output: [1,7]
Constraints:
2 <= arr.length <= 1000
1 <= arr[i] <= 3 * 104
arr[0] == 1
arr[i] is a prime number for i > 0.
All the numbers of arr are unique and sorted in strictly increasing order.
1 <= k <= arr.length * (arr.length - 1) / 2
Follow up: Can you solve the problem with better than O(n2) complexity? | [Explained] Easiest Python Solution | 180 | k-th-smallest-prime-fraction | 0.509 | the_sky_high | Medium | 12,814 | 786 |
cheapest flights within k stops | class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
#Make graph
adj_list = {i:[] for i in range(n)}
for frm, to, price in flights:
adj_list[frm].append((to, price))
best_visited = [2**31]*n # Initialized to maximum
prior_queue = [ (0, -1, src) ] # weight, steps, node
while prior_queue:
cost, steps, node = heapq.heappop(prior_queue)
if best_visited[node] <= steps: # Have seen the node already, and the current steps are more than last time
continue
if steps > k: # More than k stops, invalid
continue
if node==dst: # reach the destination # as priority_queue is a minHeap so this cost is the most minimum cost.
return cost
best_visited[node] = steps # Update steps
for neighb, weight in adj_list[node]:
heapq.heappush(prior_queue, (cost + weight, steps + 1, neighb))
return -1
# Time: O(n * len(flights) * log(n))
# Space: O(n) | https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2066105/Python-Easy-Solution-using-Dijkstra's-Algorithm | 6 | There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
Constraints:
1 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= fromi, toi < n
fromi != toi
1 <= pricei <= 104
There will not be any multiple flights between two cities.
0 <= src, dst, k < n
src != dst | Python Easy Solution using Dijkstra's Algorithm | 445 | cheapest-flights-within-k-stops | 0.359 | samirpaul1 | Medium | 12,820 | 787 |
rotated digits | class Solution:
def rotatedDigits(self, N: int) -> int:
count = 0
for x in range(1, N+1):
x = str(x)
if '3' in x or '4' in x or '7' in x:
continue
if '2' in x or '5' in x or '6' in x or '9' in x:
count+=1
return count | https://leetcode.com/problems/rotated-digits/discuss/1205605/Python3-simple-solution-using-two-approaches | 4 | An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
0, 1, and 8 rotate to themselves,
2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),
6 and 9 rotate to each other, and
the rest of the numbers do not rotate to any other number and become invalid.
Given an integer n, return the number of good integers in the range [1, n].
Example 1:
Input: n = 10
Output: 4
Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
Example 2:
Input: n = 1
Output: 0
Example 3:
Input: n = 2
Output: 1
Constraints:
1 <= n <= 104 | Python3 simple solution using two approaches | 207 | rotated-digits | 0.568 | EklavyaJoshi | Medium | 12,834 | 788 |
escape the ghosts | class Solution:
def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:
t_x, t_y = target
m_x, m_y = abs(t_x), abs(t_y)
for x, y in ghosts:
manhattan = abs(t_x - x) + abs(t_y - y)
if manhattan <= m_x + m_y:
return False
return True | https://leetcode.com/problems/escape-the-ghosts/discuss/1477363/Python-3-or-Manhattan-Distance-Math-or-Explanation | 1 | You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.
Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.
You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.
Return true if it is possible to escape regardless of how the ghosts move, otherwise return false.
Example 1:
Input: ghosts = [[1,0],[0,3]], target = [0,1]
Output: true
Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.
Example 2:
Input: ghosts = [[1,0]], target = [2,0]
Output: false
Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
Example 3:
Input: ghosts = [[2,0]], target = [1,0]
Output: false
Explanation: The ghost can reach the target at the same time as you.
Constraints:
1 <= ghosts.length <= 100
ghosts[i].length == 2
-104 <= xi, yi <= 104
There can be multiple ghosts in the same location.
target.length == 2
-104 <= xtarget, ytarget <= 104 | Python 3 | Manhattan Distance, Math | Explanation | 117 | escape-the-ghosts | 0.607 | idontknoooo | Medium | 12,845 | 789 |
domino and tromino tiling | class Solution(object):
def numTilings(self, n):
dp = [1, 2, 5] + [0] * n
for i in range(3, n):
dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007
return dp[n - 1] | https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620809/PythonJAVACC%2B%2B-DP-oror-Image-Visualized-Explanation-oror-100-Faster-oror-O(N) | 84 | You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 1000 | ✅ [Python/JAVA/C/C++] DP || Image Visualized Explanation || 100% Faster || O(N) | 2,800 | domino-and-tromino-tiling | 0.484 | linfq | Medium | 12,849 | 790 |
custom sort string | class Solution:
def customSortString(self, order: str, s: str) -> str:
rank = [26]*26
for i in range(len(order)):
rank[ord(order[i]) - ord('a')] = i
return "".join(sorted(list(s), key= lambda x: rank[ord(x) - ord('a')])) | https://leetcode.com/problems/custom-sort-string/discuss/2237060/Simple-yet-interview-friendly-or-Faster-than-99.97-or-Custom-Sorting-in-Python | 2 | You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd"
Output: "cbad"
Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
Input: order = "bcafg", s = "abcd"
Output: "bcad"
Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.
Constraints:
1 <= order.length <= 26
1 <= s.length <= 200
order and s consist of lowercase English letters.
All the characters of order are unique. | ✅ Simple yet interview friendly | Faster than 99.97% | Custom Sorting in Python | 62 | custom-sort-string | 0.693 | reinkarnation | Medium | 12,858 | 791 |
number of matching subsequences | class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
def is_sub(word):
index=-1
for ch in word:
index=s.find(ch,index+1)
if index==-1:
return False
return True
c=0
for word in words:
if is_sub(word):
c+=1
return c | https://leetcode.com/problems/number-of-matching-subsequences/discuss/1289476/Easy-Approach-oror-Well-explained-oror-95-faster | 27 | Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "abcde", words = ["a","bb","acd","ace"]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Example 2:
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
Output: 2
Constraints:
1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
s and words[i] consist of only lowercase English letters. | 📌 Easy-Approach || Well-explained || 95% faster 🐍 | 1,200 | number-of-matching-subsequences | 0.519 | abhi9Rai | Medium | 12,887 | 792 |
preimage size of factorial zeroes function | class Solution:
def preimageSizeFZF(self, k: int) -> int:
lo, hi = 0, 1 << 32
while lo <= hi:
mid = lo + hi >> 1
x, y = mid, 0
while x:
x //= 5
y += x
if y < k: lo = mid + 1
elif y > k: hi = mid - 1
else: return 5
return 0 | https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1306028/Python3-binary-search | 1 | Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.
For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
Example 1:
Input: k = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
Example 2:
Input: k = 5
Output: 0
Explanation: There is no x such that x! ends in k = 5 zeroes.
Example 3:
Input: k = 3
Output: 5
Constraints:
0 <= k <= 109 | [Python3] binary search | 69 | preimage-size-of-factorial-zeroes-function | 0.428 | ye15 | Hard | 12,919 | 793 |
valid tic tac toe state | class Solution:
def validTicTacToe(self, board: List[str]) -> bool:
# The two criteria for a valid board are:
# 1) num of Xs - num of Os is 0 or 1
# 2) X is not a winner if the # of moves is even, and
# O is not a winner if the # of moves is odd.
d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array
s = [d[ch] for ch in ''.join(board)] # Ex: ["XOX"," X "," "] --> [1,-1,1,0,1,0,0,0,0]
sm = sum(s)
if sm>>1: return False # <-- criterion 1
n = -3 if sm == 1 else 3 # <-- criterion 2.
if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8],
s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are
s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags
return True # <-- both criteria are true | https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/2269469/Python3-oror-int-array-7-lines-w-explanation-oror-TM%3A-98-49 | 4 | Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares ' '.
The first player always places 'X' characters, while the second player always places 'O' characters.
'X' and 'O' characters are always placed into empty squares, never filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O "," "," "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX"," X "," "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XOX","O O","XOX"]
Output: true
Constraints:
board.length == 3
board[i].length == 3
board[i][j] is either 'X', 'O', or ' '. | Python3 || int array, 7 lines, w/ explanation || T/M: 98%/ 49% | 221 | valid-tic-tac-toe-state | 0.351 | warrenruud | Medium | 12,922 | 794 |
number of subarrays with bounded maximum | class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
start,end = -1, -1
res = 0
for i in range(len(nums)):
if nums[i] > right:
start = end = i
continue
if nums[i] >= left:
end = i
res += end - start
return res | https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/2304108/Python-or-Two-pointer-technique-or-Easy-solution | 2 | Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,1,4,3], left = 2, right = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].
Example 2:
Input: nums = [2,9,2,5,6], left = 2, right = 8
Output: 7
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109 | Python | Two pointer technique | Easy solution | 79 | number-of-subarrays-with-bounded-maximum | 0.527 | __Asrar | Medium | 12,935 | 795 |
rotate string | class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return len(s) == len(goal) and s in goal+goal | https://leetcode.com/problems/rotate-string/discuss/2369025/or-python3-or-ONE-LINE-or-FASTER-THAN-99-or | 18 | Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Example 1:
Input: s = "abcde", goal = "cdeab"
Output: true
Example 2:
Input: s = "abcde", goal = "abced"
Output: false
Constraints:
1 <= s.length, goal.length <= 100
s and goal consist of lowercase English letters. | ✅ | python3 | ONE LINE | FASTER THAN 99% | 🔥💪 | 628 | rotate-string | 0.542 | sahelriaz | Easy | 12,939 | 796 |
all paths from source to target | class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
q = [[0]]
result = []
target = len(graph) - 1
while q:
temp = q.pop(0)
if temp[-1] == target:
result.append(temp)
else:
for neighbor in graph[temp[-1]]:
q.append(temp + [neighbor])
return result | https://leetcode.com/problems/all-paths-from-source-to-target/discuss/752799/Python-simple-BFS-solution-explained | 6 | Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Example 2:
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Constraints:
n == graph.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[i][j] != i (i.e., there will be no self-loops).
All the elements of graph[i] are unique.
The input graph is guaranteed to be a DAG. | Python simple BFS solution explained | 787 | all-paths-from-source-to-target | 0.815 | spec_he123 | Medium | 12,966 | 797 |
smallest rotation with highest score | class Solution:
def bestRotation(self, nums: List[int]) -> int:
diff = [0]*(len(nums) + 1)
for i, x in enumerate(nums):
diff[i+1] += 1
if x <= i: diff[0] += 1
diff[(i-x)%len(nums) + 1] -= 1
ans = prefix = 0
mx = -inf
for i, x in enumerate(diff):
prefix += x
if prefix > mx: mx, ans = prefix, i
return ans | https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/1307760/Python3-difference-array | 0 | You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point].
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Example 1:
Input: nums = [2,3,1,4,0]
Output: 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4]
Output: 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] < nums.length | [Python3] difference array | 137 | smallest-rotation-with-highest-score | 0.498 | ye15 | Hard | 13,011 | 798 |
champagne tower | class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)]
dp[0][0] = poured
for i in range(query_row):
for j in range(len(dp[i])):
temp = (dp[i][j] - 1) / 2.0
if temp>0:
dp[i+1][j] += temp
dp[i+1][j+1] += temp
return dp[query_row][query_glass] if dp[query_row][query_glass] <= 1 else 1 | https://leetcode.com/problems/champagne-tower/discuss/1818232/Python-Easy-Solution-or-95-Faster-or-Dynamic-Programming | 24 | We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)
Example 1:
Input: poured = 1, query_row = 1, query_glass = 1
Output: 0.00000
Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
Example 2:
Input: poured = 2, query_row = 1, query_glass = 1
Output: 0.50000
Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
Example 3:
Input: poured = 100000009, query_row = 33, query_glass = 17
Output: 1.00000
Constraints:
0 <= poured <= 109
0 <= query_glass <= query_row < 100 | ✔️ Python Easy Solution | 95% Faster | Dynamic Programming | 1,300 | champagne-tower | 0.513 | pniraj657 | Medium | 13,013 | 799 |
minimum swaps to make sequences increasing | class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
ans = sm = lg = mx = 0
for x, y in zip(A, B):
if mx < min(x, y): # prev max < current min
ans += min(sm, lg) # update answer & reset
sm = lg = 0
mx = max(x, y)
if x < y: sm += 1 # count "x < y"
elif x > y: lg += 1 # count "x > y"
return ans + min(sm, lg) | https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/discuss/932390/Python3-two-counters | 8 | You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].
For example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].
Return the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.
An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].
Example 1:
Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]
Output: 1
Explanation:
Swap nums1[3] and nums2[3]. Then the sequences are:
nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
which are both strictly increasing.
Example 2:
Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]
Output: 1
Constraints:
2 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 2 * 105 | [Python3] two counters | 237 | minimum-swaps-to-make-sequences-increasing | 0.393 | ye15 | Hard | 13,030 | 801 |
find eventual safe states | class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n=len(graph)
status=[0]*(n)
res=[]
def dfs(i):# this function will check is there any loop, cycle and i is a part of that loop,cycle
if status[i]=="visited": #if this node is already visited, loop detected return true
return True
if status[i]=="safe": #if this node is previously visited and marked safe no need to repeat it ,return False no loop possible from it
return False
status[i]="visited" # so we have visited this node
for j in graph[i]:
if dfs(j):# if loop detected return True
return True
status[i]="safe" # if we reached till here means no loop detected from node i so this node is safe
return False # no loop possible return false
for i in range(n):
if not dfs(i): #if no loop detected this node is safe
res.append(i)
return res | https://leetcode.com/problems/find-eventual-safe-states/discuss/1317749/Python-DFS-Easy | 9 | There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
Example 1:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2:
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
Constraints:
n == graph.length
1 <= n <= 104
0 <= graph[i].length <= n
0 <= graph[i][j] <= n - 1
graph[i] is sorted in a strictly increasing order.
The graph may contain self-loops.
The number of edges in the graph will be in the range [1, 4 * 104]. | Python-DFS-Easy | 575 | find-eventual-safe-states | 0.553 | manmohan1105 | Medium | 13,032 | 802 |
unique morse code words | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
MORSE = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.',
'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.',
'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-',
'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..',
}
def uniqueMorseRepresentations(self, words: List[str]) -> int:
return len(set(map(self.encode, words)))
@classmethod
def encode(cls, word: str) -> str:
return ''.join(map(cls.MORSE.get, word)) | https://leetcode.com/problems/unique-morse-code-words/discuss/2438206/Python-Elegant-and-Short-or-Two-lines-or-No-loops | 5 | International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.
For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word.
Return the number of different transformations among all words we have.
Example 1:
Input: words = ["gin","zen","gig","msg"]
Output: 2
Explanation: The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."
There are 2 different transformations: "--...-." and "--...--.".
Example 2:
Input: words = ["a"]
Output: 1
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 12
words[i] consists of lowercase English letters. | Python Elegant & Short | Two lines | No loops | 395 | unique-morse-code-words | 0.827 | Kyrylo-Ktl | Easy | 13,048 | 804 |
split array with same average | class Solution(object):
def splitArraySameAverage(self, A):
if len(A)==1: return False
global_avg = sum(A)/float(len(A))
for lenB in range(1, len(A)/2+1):
if int(lenB*global_avg) == lenB*global_avg:
if self.exist(lenB*global_avg, lenB, A):
return True
return False
def exist(self, tosum, item_count, arr):
if item_count==0:
return False if tosum else True
if item_count > len(arr) or not arr:
return False
if any([self.exist(tosum-arr[0], item_count-1, arr[1:]),
self.exist(tosum, item_count, arr[1:])]):
return True
return False | https://leetcode.com/problems/split-array-with-same-average/discuss/120654/Simple-python-with-explanation | 26 | You are given an integer array nums.
You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).
Return true if it is possible to achieve that and false otherwise.
Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.
Example 1:
Input: nums = [1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
Example 2:
Input: nums = [3,1]
Output: false
Constraints:
1 <= nums.length <= 30
0 <= nums[i] <= 104 | Simple python with explanation | 4,200 | split-array-with-same-average | 0.259 | licaiuu | Hard | 13,097 | 805 |
number of lines to write string | class Solution:
def numberOfLines(self, widths: List[int], s: str) -> List[int]:
count = ans = wi = 0
s = list(s)
while s:
val = ord(s[0]) - 97
if(widths[val] + wi > 100):
wi = 0
count += 1
wi += widths[val]
s.pop(0)
return([count + 1 , wi]) | https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1170893/Python3-97-Faster-Solution | 2 | You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.
You are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.
Return an array result of length 2 where:
result[0] is the total number of lines.
result[1] is the width of the last line in pixels.
Example 1:
Input: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"
Output: [3,60]
Explanation: You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
Example 2:
Input: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"
Output: [2,4]
Explanation: You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
Constraints:
widths.length == 26
2 <= widths[i] <= 10
1 <= s.length <= 1000
s contains only lowercase English letters. | [Python3] 97% Faster Solution | 80 | number-of-lines-to-write-string | 0.662 | VoidCupboard | Easy | 13,100 | 806 |
max increase to keep city skyline | class Solution:
def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int:
M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c) for c in zip(*G)]
return sum(min(R[i],C[j]) - G[i][j] for i,j in itertools.product(range(M),range(N)))
- Junaid Mansuri
- Chicago, IL | https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/445773/Python-3-(two-lines)-(beats-~100) | 5 | There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
Example 1:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation: The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Example 2:
Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Explanation: Increasing the height of any building will result in the skyline changing.
Constraints:
n == grid.length
n == grid[r].length
2 <= n <= 50
0 <= grid[r][c] <= 100 | Python 3 (two lines) (beats ~100%) | 1,200 | max-increase-to-keep-city-skyline | 0.86 | junaidmansuri | Medium | 13,111 | 807 |
soup servings | class Solution:
def soupServings(self, n: int) -> float:
@cache # cache the result for input (a, b)
def dfs(a, b):
if a <= 0 and b > 0: return 1 # set criteria probability
elif a <= 0 and b <= 0: return 0.5
elif a > 0 and b <= 0: return 0
return (dfs(a-4, b) + dfs(a-3, b-1) + dfs(a-2, b-2) + dfs(a-1, b-3)) * 0.25 # dfs
if n > 4275: return 1 # observe the distribution you will find `a` tends to be easier to get used up than `b`
n /= 25 # reduce the input scale
return dfs(n, n) # both soup have `n` ml | https://leetcode.com/problems/soup-servings/discuss/1651208/Python-3-or-Bottom-up-and-Top-down-DP-or-Explanation | 5 | There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B,
Serve 75 ml of soup A and 25 ml of soup B,
Serve 50 ml of soup A and 50 ml of soup B, and
Serve 25 ml of soup A and 75 ml of soup B.
When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
Note that we do not have an operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: n = 50
Output: 0.62500
Explanation: If we choose the first two operations, A will become empty first.
For the third operation, A and B will become empty at the same time.
For the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Example 2:
Input: n = 100
Output: 0.71875
Constraints:
0 <= n <= 109 | Python 3 | Bottom-up & Top-down DP | Explanation | 660 | soup-servings | 0.433 | idontknoooo | Medium | 13,134 | 808 |
expressive words | class Solution:
def expressiveWords(self, s: str, words: List[str]) -> int:
def summarize(word):
res = []
n = len(word)
i, j = 0, 0
while i<=j and j <= n-1:
while j <= n-1 and word[j] == word[i]:
j += 1
res.append(word[i])
res.append(j-i)
i = j
return res
t = 0
start = summarize(s)
n = len(start)//2
def compare(w):
r = summarize(w)
if len(r) != len(start):
return False
for i in range(0, 2*n, 2):
if start[i] != r[i]:
return False
elif start[i] == r[i]:
if start[i+1] < r[i+1]:
return False
elif start[i+1] == r[i+1]:
pass
elif start[i+1] < 3:
return False
return True
for w in words:
if compare(w):
t += 1
return t | https://leetcode.com/problems/expressive-words/discuss/1507874/Problem-description-is-horrible...-but-here's-simple-python-solution | 3 | Sometimes people repeat letters to represent extra feeling. For example:
"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.
For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s.
Return the number of query strings that are stretchy.
Example 1:
Input: s = "heeellooo", words = ["hello", "hi", "helo"]
Output: 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.
Example 2:
Input: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"]
Output: 3
Constraints:
1 <= s.length, words.length <= 100
1 <= words[i].length <= 100
s and words[i] consist of lowercase letters. | Problem description is horrible... but here's simple python solution | 483 | expressive-words | 0.463 | byuns9334 | Medium | 13,139 | 809 |
chalkboard xor game | class Solution:
def xorGame(self, nums):
#create a variable 0
x = 0
#iterate over the elements in the nums
for i in nums:
#do xor of all the elements
x ^= i
#Alice wins in two situations :
#1.if the xor is already 0 (x == 0 )
#2.if the length of nums is even because if alice got chance with even length and xor != 0 he will select a number so that he will leave the odd number of same integer
#if nums == [a,a,a,b] then alice erase b so bob must erase from [a,a,a] so he will lose if he erase any number
return x == 0 or len(nums)%2 == 0
#in other situations bob will win | https://leetcode.com/problems/chalkboard-xor-game/discuss/2729320/Simple-python-code-with-explanation | 0 | You are given an array of integers nums represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.
Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.
Return true if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: nums = [1,1,2]
Output: false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Example 2:
Input: nums = [0,1]
Output: true
Example 3:
Input: nums = [1,2,3]
Output: true
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 216 | Simple python code with explanation | 11 | chalkboard-xor-game | 0.554 | thomanani | Hard | 13,150 | 810 |
subdomain visit count | class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
d = defaultdict(int)
for s in cpdomains:
cnt, s = s.split()
cnt = int(cnt)
d[s] += cnt
pos = s.find('.') + 1
while pos > 0:
d[s[pos:]] += cnt
pos = s.find('.', pos) + 1
for x, i in d.items():
yield f'{i} {x}' | https://leetcode.com/problems/subdomain-visit-count/discuss/914736/Python3-100-faster-100-less-memory-(32ms-14.1mb) | 10 | A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.
For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.
Given an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
Example 1:
Input: cpdomains = ["9001 discuss.leetcode.com"]
Output: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]
Explanation: We only have one website domain: "discuss.leetcode.com".
As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
Input: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.
For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
Constraints:
1 <= cpdomain.length <= 100
1 <= cpdomain[i].length <= 100
cpdomain[i] follows either the "repi d1i.d2i.d3i" format or the "repi d1i.d2i" format.
repi is an integer in the range [1, 104].
d1i, d2i, and d3i consist of lowercase English letters. | Python3 100% faster, 100% less memory (32ms, 14.1mb) | 1,300 | subdomain-visit-count | 0.752 | haasosaurus | Medium | 13,152 | 811 |
largest triangle area | class Solution:
def largestTriangleArea(self, points: List[List[int]]) -> float:
area = 0
n = len(points)
for i in range(n):
x1,y1 = points[i]
for j in range(i+1,n):
x2,y2 = points[j]
for k in range(j+1,n):
x3,y3 = points[k]
curr = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))
if curr>area:
area = curr
return area | https://leetcode.com/problems/largest-triangle-area/discuss/1585033/Python-oror-Faster-than-93-oror-Simple-maths-oror-with-explanation | 19 | Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2.00000
Explanation: The five points are shown in the above figure. The red triangle is the largest.
Example 2:
Input: points = [[1,0],[0,0],[0,1]]
Output: 0.50000
Constraints:
3 <= points.length <= 50
-50 <= xi, yi <= 50
All the given points are unique. | Python || Faster than 93% || Simple maths || with explanation | 1,300 | largest-triangle-area | 0.6 | ana_2kacer | Easy | 13,172 | 812 |