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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
longest palindromic subsequence | class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
return self.get_longest_subseq(0, len(s)-1, s)
def get_longest_subseq(self, start, end, s):
"""
method used to find the longest palindrome subsequence in a string
start: start index of the string
end: end index of the string
s: string
return: length of the longest palindrome subsequence
"""
if start == end:
return 1
if start > end:
return 0
if s[start] == s[end]:
return 2 + self.get_longest_subseq(start + 1, end - 1, s)
return max(self.get_longest_subseq(start + 1, end, s), self.get_longest_subseq(start, end - 1, s)) | https://leetcode.com/problems/longest-palindromic-subsequence/discuss/1968323/Python-3-Approaches-(Recursion-%2B-Memoization-%2B-DP) | 6 | Given a string s, find the longest palindromic subsequence's length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
1 <= s.length <= 1000
s consists only of lowercase English letters. | Python - 3 Approaches (Recursion + Memoization + DP) | 225 | longest-palindromic-subsequence | 0.607 | superGloria | Medium | 9,070 | 516 |
super washing machines | class Solution:
def findMinMoves(self, machines: List[int]) -> int:
total = sum(machines)
if total % len(machines): return -1 # impossible
avg = total // len(machines)
ans = prefix = 0
for i, x in enumerate(machines):
ans = max(ans, abs(prefix), x - avg)
prefix += x - avg
return ans | https://leetcode.com/problems/super-washing-machines/discuss/1494245/Python3-greedy | 1 | You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.
Example 1:
Input: machines = [1,0,5]
Output: 3
Explanation:
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
Example 2:
Input: machines = [0,3,0]
Output: 2
Explanation:
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
Example 3:
Input: machines = [0,2,0]
Output: -1
Explanation:
It's impossible to make all three washing machines have the same number of dresses.
Constraints:
n == machines.length
1 <= n <= 104
0 <= machines[i] <= 105 | [Python3] greedy | 138 | super-washing-machines | 0.401 | ye15 | Hard | 9,099 | 517 |
coin change ii | class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [[1]+[0]*amount for _ in range(len(coins)+1)]
for i in range(1, len(coins)+1):
for j in range(1, amount+1):
if coins[i-1] <= j:
dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]]
else:
dp[i][j] = dp[i-1][j]
return dp[len(coins)][amount] # or dp[-1][-1] | https://leetcode.com/problems/coin-change-ii/discuss/675186/Python3-DP-Solution-O(mn)-Time-and-Space | 9 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
Example 1:
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
Constraints:
1 <= coins.length <= 300
1 <= coins[i] <= 5000
All the values of coins are unique.
0 <= amount <= 5000 | Python3 DP Solution - O(mn) Time and Space | 1,200 | coin-change-ii | 0.599 | schedutron | Medium | 9,100 | 518 |
random flip matrix | class Solution:
def __init__(self, m: int, n: int):
self.nums = m * n - 1
self.cols = n
self.flipped = set()
def flip(self) -> List[int]:
rc = random.randint(0, self.nums)
while rc in self.flipped:
rc = random.randint(0, self.nums)
self.flipped.add(rc)
return [rc // self.cols, rc % self.cols]
def reset(self) -> None:
self.flipped = set() | https://leetcode.com/problems/random-flip-matrix/discuss/2108517/Python3Three-solutions-with-detailed-explanation. | 0 | There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.
Implement the Solution class:
Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.
int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.
void reset() Resets all the values of the matrix to be 0.
Example 1:
Input
["Solution", "flip", "flip", "flip", "reset", "flip"]
[[3, 1], [], [], [], [], []]
Output
[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]
Explanation
Solution solution = new Solution(3, 1);
solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]
solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.
Constraints:
1 <= m, n <= 104
There will be at least one free cell for each call to flip.
At most 1000 calls will be made to flip and reset. | [Python3]Three solutions with detailed explanation. | 55 | random-flip-matrix | 0.399 | AlainWong | Medium | 9,144 | 519 |
detect capital | class Solution:
def detectCapitalUse(self, word: str) -> bool:
return word in [word.upper(), word.lower(), word.title()]
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/detect-capital/discuss/336441/Solution-in-Python-3-(one-line) | 6 | We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of capitals in it is right.
Example 1:
Input: word = "USA"
Output: true
Example 2:
Input: word = "FlaG"
Output: false
Constraints:
1 <= word.length <= 100
word consists of lowercase and uppercase English letters. | Solution in Python 3 (one line) | 541 | detect-capital | 0.555 | junaidmansuri | Easy | 9,147 | 520 |
longest uncommon subsequence i | class Solution:
def findLUSlength(self, a: str, b: str) -> int:
if a==b:return -1
else:return max(len(a),len(b)) | https://leetcode.com/problems/longest-uncommon-subsequence-i/discuss/1277607/python-two-lines-or-easy | 4 | Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If no such uncommon subsequence exists, return -1.
An uncommon subsequence between two strings is a string that is a
subsequence
of exactly one of them.
Example 1:
Input: a = "aba", b = "cdc"
Output: 3
Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
Note that "cdc" is also a longest uncommon subsequence.
Example 2:
Input: a = "aaa", b = "bbb"
Output: 3
Explanation: The longest uncommon subsequences are "aaa" and "bbb".
Example 3:
Input: a = "aaa", b = "aaa"
Output: -1
Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1.
Constraints:
1 <= a.length, b.length <= 100
a and b consist of lower-case English letters. | python two lines | easy | 314 | longest-uncommon-subsequence-i | 0.603 | chikushen99 | Easy | 9,194 | 521 |
longest uncommon subsequence ii | class Solution:
def findLUSlength(self, S: List[str]) -> int:
C = collections.Counter(S)
S = sorted(C.keys(), key = len, reverse = True)
for i,s in enumerate(S):
if C[s] != 1: continue
b = True
for j in range(i):
I, c = -1, True
for i in s:
I = S[j].find(i,I+1)
if I == -1:
c = False
break
if c:
b = False
break
if b: return len(s)
return -1
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/longest-uncommon-subsequence-ii/discuss/380412/Solution-in-Python-3-(beats-~100) | 2 | Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.
For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
Example 1:
Input: strs = ["aba","cdc","eae"]
Output: 3
Example 2:
Input: strs = ["aaa","aaa","aa"]
Output: -1
Constraints:
2 <= strs.length <= 50
1 <= strs[i].length <= 10
strs[i] consists of lowercase English letters. | Solution in Python 3 (beats ~100%) | 648 | longest-uncommon-subsequence-ii | 0.404 | junaidmansuri | Medium | 9,209 | 522 |
continuous subarray sum | class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
# Brute Force: O(𝑛^2) - TLE
count = 0
for i in range(len(nums)):
sum = 0
for j in range(i, len(nums)):
sum += nums[j]
if sum % k == 0:
return True
return False
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
# Optimal Approach - Time and Space: O(n), O(n)
res = {0: -1}
prefSum = 0
for i in range(len(nums)):
prefSum += nums[i]
rem = prefSum % k
if rem in res:
if i-res[rem] > 1:
return True
else:
res[rem] = i
return False | https://leetcode.com/problems/continuous-subarray-sum/discuss/1582670/Python-Easy-Solution-or-Brute-Force-and-Optimal-Approach | 5 | Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.
A good subarray is a subarray where:
its length is at least two, and
the sum of the elements of the subarray is a multiple of k.
Note that:
A subarray is a contiguous part of the array.
An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.
Example 1:
Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
Example 2:
Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
Example 3:
Input: nums = [23,2,6,4,7], k = 13
Output: false
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= sum(nums[i]) <= 231 - 1
1 <= k <= 231 - 1 | Python Easy Solution | Brute Force and Optimal Approach | 603 | continuous-subarray-sum | 0.285 | leet_satyam | Medium | 9,213 | 523 |
longest word in dictionary through deleting | class Solution:
def findLongestWord(self, s: str, d: List[str]) -> str:
def is_subseq(main: str, sub: str) -> bool:
i, j, m, n = 0, 0, len(main), len(sub)
while i < m and j < n and n - j >= m - i:
if main[i] == sub[j]:
i += 1
j += 1
return i == m
res = ''
helper = sorted(d, key = lambda x: len(x), reverse = True)
for word in helper:
if len(word) < len(res): return res
if ( not res or word < res ) and is_subseq(word, s):
res = word
return res | https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/discuss/1077760/Python.-very-clear-and-simplistic-solution. | 6 | Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"
Example 2:
Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"
Constraints:
1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s and dictionary[i] consist of lowercase English letters. | Python. very clear and simplistic solution. | 879 | longest-word-in-dictionary-through-deleting | 0.512 | m-d-f | Medium | 9,254 | 524 |
contiguous array | class Solution:
def findMaxLength(self, nums: List[int]) -> int:
partial_sum = 0
# table is a dictionary
# key : partial sum value
# value : the left-most index who has the partial sum value
table = { 0: -1}
max_length = 0
for idx, number in enumerate( nums ):
# partial_sum add 1 for 1
# partial_sum minus 1 for 0
if number:
partial_sum += 1
else:
partial_sum -= 1
if partial_sum in table:
# we have a subarray with equal number of 0 and 1
# update max length
max_length = max( max_length, ( idx - table[partial_sum] ) )
else:
# update the left-most index for specified partial sum value
table[ partial_sum ] = idx
return max_length | https://leetcode.com/problems/contiguous-array/discuss/577489/Python-O(n)-by-partial-sum-and-dictionary.-90%2B-w-Visualization | 12 | Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example 1:
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Example 2:
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1. | Python O(n) by partial sum and dictionary. 90%+ [w/ Visualization] | 1,700 | contiguous-array | 0.468 | brianchiang_tw | Medium | 9,274 | 525 |
beautiful arrangement | class Solution:
def countArrangement(self, n: int) -> int:
self.count = 0
self.backtrack(n, 1, [])
return self.count
def backtrack(self, N, idx, temp):
if len(temp) == N:
self.count += 1
return
for i in range(1, N+1):
if i not in temp and (i % idx == 0 or idx % i == 0):
temp.append(i)
self.backtrack(N, idx+1, temp)
temp.pop() | https://leetcode.com/problems/beautiful-arrangement/discuss/1094146/Python-Backtracking-the-more-intuitive-way | 8 | Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return the number of the beautiful arrangements that you can construct.
Example 1:
Input: n = 2
Output: 2
Explanation:
The first beautiful arrangement is [1,2]:
- perm[1] = 1 is divisible by i = 1
- perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
- perm[1] = 2 is divisible by i = 1
- i = 2 is divisible by perm[2] = 1
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 15 | Python Backtracking, the more intuitive way | 872 | beautiful-arrangement | 0.646 | IamCookie | Medium | 9,297 | 526 |
random pick with weight | class Solution:
def __init__(self, w: List[int]):
self.li = []
ma = sum(w)
for i, weight in enumerate(w):
ratio = ceil(weight / ma * 100)
self.li += ([i] * ratio)
def pickIndex(self) -> int:
return random.choice(self.li) | https://leetcode.com/problems/random-pick-with-weight/discuss/1535699/Better-than-96.5 | 8 | You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.
You need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).
For example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).
Example 1:
Input
["Solution","pickIndex"]
[[[1]],[]]
Output
[null,0]
Explanation
Solution solution = new Solution([1]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
Example 2:
Input
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output
[null,1,1,1,1,0]
Explanation
Solution solution = new Solution([1, 3]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
[null,1,1,1,1,0]
[null,1,1,1,1,1]
[null,1,1,1,0,0]
[null,1,1,1,0,1]
[null,1,0,1,0,0]
......
and so on.
Constraints:
1 <= w.length <= 104
1 <= w[i] <= 105
pickIndex will be called at most 104 times. | Better than 96.5% | 815 | random-pick-with-weight | 0.461 | josephp27 | Medium | 9,315 | 528 |
minesweeper | class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
m, n = len(board), len(board[0])
def dfs(x, y):
if board[x][y] == 'M': board[x][y] = 'X'
elif board[x][y] == 'E':
cnt, nei = 0, []
for i, j in map(lambda v: (v[0]+x, v[1]+y), [(-1, 0), (1, 0), (-1, -1), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 1)]):
if 0 <= i < m and 0 <= j < n:
nei.append((i, j))
if board[i][j] == 'M': cnt += 1
if not cnt:
board[x][y] = 'B'
for i, j in nei: dfs(i, j)
else: board[x][y] = str(cnt)
dfs(*click)
return board | https://leetcode.com/problems/minesweeper/discuss/875335/Python-3-or-Ad-hoc-DFS-or-Explanation | 5 | Let's play the minesweeper game (Wikipedia, online game)!
You are given an m x n char matrix board representing the game board where:
'M' represents an unrevealed mine,
'E' represents an unrevealed empty square,
'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
digit ('1' to '8') represents how many mines are adjacent to this revealed square, and
'X' represents a revealed mine.
You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').
Return the board after revealing this position according to the following rules:
If a mine 'M' is revealed, then the game is over. You should change it to 'X'.
If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.
If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
Return the board when no more squares will be revealed.
Example 1:
Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0]
Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
Example 2:
Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2]
Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 50
board[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'.
click.length == 2
0 <= clickr < m
0 <= clickc < n
board[clickr][clickc] is either 'M' or 'E'. | Python 3 | Ad-hoc DFS | Explanation | 743 | minesweeper | 0.655 | idontknoooo | Medium | 9,331 | 529 |
minimum absolute difference in bst | class Solution:
def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
d = float('inf')
s = []
if root == None:
return
d = self.traverse(root,d,s)
return d
def traverse(self,root,d,s):
if root.left != None:
d = self.traverse(root.left,d,s)
s.append(root.val)
if len(s)>1:
diff = s[-1]-s[-2]
if diff < d:
d = diff
if root.right != None:
d = self.traverse(root.right,d,s)
return d | https://leetcode.com/problems/minimum-absolute-difference-in-bst/discuss/1414654/Faster-than-99.61-of-Python3-with-logical-explanation | 4 | Given the root of a Binary Search Tree (BST), return the minimum absolute 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, 104].
0 <= Node.val <= 105
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/ | Faster than 99.61% of Python3 with logical explanation | 786 | minimum-absolute-difference-in-bst | 0.568 | iron_man_365 | Easy | 9,349 | 530 |
k diff pairs in an array | class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
cnt=0
c=Counter(nums)
if k==0:
for key,v in c.items():
if v>1:
cnt+=1
else:
for key,v in c.items():
if key+k in c:
cnt+=1
return cnt | https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/1757434/Python-O(n)-Solution-or-98-Faster-or-Easy-Solution-or-K-diff-Pairs-in-an-Array | 34 | Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
0 <= i, j < nums.length
i != j
|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute value of val.
Example 1:
Input: nums = [3,1,4,1,5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input: nums = [1,2,3,4,5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Constraints:
1 <= nums.length <= 104
-107 <= nums[i] <= 107
0 <= k <= 107 | ✔️ Python O(n) Solution | 98% Faster | Easy Solution | K-diff Pairs in an Array | 2,200 | k-diff-pairs-in-an-array | 0.408 | pniraj657 | Medium | 9,362 | 532 |
complex number multiplication | class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
a1,b1 = num1.split('+')
a1 = int(a1)
b1 = int(b1[:-1])
a2,b2 = num2.split('+')
a2 = int(a2)
b2 = int(b2[:-1])
return str(a1*a2 + b1*b2*(-1)) + '+' + str(a1*b2 + a2*b1) + 'i' | https://leetcode.com/problems/complex-number-multiplication/discuss/1187864/Python3-simple-solution | 7 | A complex number can be represented as a string on the form "real+imaginaryi" where:
real is the real part and is an integer in the range [-100, 100].
imaginary is the imaginary part and is an integer in the range [-100, 100].
i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Constraints:
num1 and num2 are valid complex numbers. | Python3 simple solution | 113 | complex-number-multiplication | 0.714 | EklavyaJoshi | Medium | 9,384 | 537 |
convert bst to greater tree | class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
sum = 0
def sol(root: TreeNode) -> TreeNode:
nonlocal sum
if root:
sol(root.right)
root.val += sum
sum = root.val
sol(root.left)
return root
return sol(root) | https://leetcode.com/problems/convert-bst-to-greater-tree/discuss/1057429/Python.-faster-than-100.00.-Explained-clear-and-Easy-understanding-solution.-O(n).-Recursive | 13 | Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input: root = [0,null,1]
Output: [1,null,1]
Constraints:
The number of nodes in the tree is in the range [0, 104].
-104 <= Node.val <= 104
All the values in the tree are unique.
root is guaranteed to be a valid binary search tree.
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ | Python. faster than 100.00%. Explained, clear & Easy-understanding solution. O(n). Recursive | 912 | convert-bst-to-greater-tree | 0.674 | m-d-f | Medium | 9,404 | 538 |
minimum time difference | class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
M = 1440
times = [False] * M
for time in timePoints:
minute = self.minute(time)
if times[minute]:
return 0
times[minute] = True
minutes = [i for i in range(M) if times[i]]
return min((minutes[i] - minutes[i-1]) % M for i in range(len(minutes)))
def minute(self, time: str) -> int:
h, m = map(int, time.split(':'))
return 60*h + m | https://leetcode.com/problems/minimum-time-difference/discuss/1829297/python-3-bucket-sort-O(n)-time-O(1)-space | 9 | Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.
Example 1:
Input: timePoints = ["23:59","00:00"]
Output: 1
Example 2:
Input: timePoints = ["00:00","23:59","00:00"]
Output: 0
Constraints:
2 <= timePoints.length <= 2 * 104
timePoints[i] is in the format "HH:MM". | [python 3] bucket sort, O(n) time, O(1) space | 595 | minimum-time-difference | 0.563 | dereky4 | Medium | 9,431 | 539 |
single element in a sorted array | class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
counts = defaultdict(int)
for num in nums:
counts[num] += 1
for num, count in counts.items():
if count == 1:
return num
return -1 # this will never be reached
# return Counter(nums).most_common()[-1][0] # one-liner, but TC O(nlogn) | https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/1587293/Python-3-Simple-Approaches-with-Explanation | 54 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 105 | [Python] 3 Simple Approaches with Explanation | 2,800 | single-element-in-a-sorted-array | 0.585 | zayne-siew | Medium | 9,449 | 540 |
reverse string ii | class Solution:
def reverseStr(self, s: str, k: int) -> str:
if len(s)<(k):return s[::-1]
if len(s)<(2*k):return (s[:k][::-1]+s[k:])
return s[:k][::-1]+s[k:2*k]+self.reverseStr(s[2*k:],k) | https://leetcode.com/problems/reverse-string-ii/discuss/343424/Python-3-solution-using-recursion-(efficient)-3-liner-with-explanation | 22 | Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2
Output: "bacd"
Constraints:
1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104 | Python 3 solution using recursion (efficient) 3-liner with explanation | 1,700 | reverse-string-ii | 0.505 | ketan35 | Easy | 9,496 | 541 |
01 matrix | class Solution:
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
row, col = len(mat), len(mat[0])
queue = deque([])
for x in range(row):
for y in range(col):
if mat[x][y] == 0:
queue.append((x, y, 1))
return self.bfs(row, col, queue, mat)
def bfs(self, row, col, queue, grid):
visited = set()
while queue:
x, y, steps = queue.popleft()
for nx, ny in [[x+1,y], [x-1,y], [x,y+1], [x,y-1]]:
if 0<=nx<row and 0<=ny<col and (nx,ny) not in visited:
if grid[nx][ny] == 1:
visited.add((nx,ny))
grid[nx][ny] = steps
queue.append((nx, ny, steps+1))
return grid | https://leetcode.com/problems/01-matrix/discuss/1556018/WEEB-DOES-PYTHON-BFS | 7 | Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
There is at least one 0 in mat. | WEEB DOES PYTHON BFS | 414 | 01-matrix | 0.442 | Skywalker5423 | Medium | 9,542 | 542 |
diameter of binary tree | class Solution:
def __init__(self):
self.diameter = 0 # stores the maximum diameter calculated
def depth(self, node: Optional[TreeNode]) -> int:
"""
This function needs to do the following:
1. Calculate the maximum depth of the left and right sides of the given node
2. Determine the diameter at the given node and check if its the maximum
"""
# Calculate maximum depth
left = self.depth(node.left) if node.left else 0
right = self.depth(node.right) if node.right else 0
# Calculate diameter
if left + right > self.diameter:
self.diameter = left + right
# Make sure the parent node(s) get the correct depth from this node
return 1 + (left if left > right else right)
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
# if not root:
# return 0
self.depth(root) # root is guaranteed to be a TreeNode object
return self.diameter | https://leetcode.com/problems/diameter-of-binary-tree/discuss/1515564/Python-Easy-to-understand-solution-w-Explanation | 56 | Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2:
Input: root = [1,2]
Output: 1
Constraints:
The number of nodes in the tree is in the range [1, 104].
-100 <= Node.val <= 100 | Python Easy-to-understand solution w Explanation | 3,100 | diameter-of-binary-tree | 0.561 | zayne-siew | Easy | 9,572 | 543 |
remove boxes | class Solution:
def removeBoxes(self, boxes: List[int]) -> int:
@cache
def fn(lo, hi, k):
"""Return max score of removing boxes from lo to hi with k to the left."""
if lo == hi: return 0
while lo+1 < hi and boxes[lo] == boxes[lo+1]: lo, k = lo+1, k+1
ans = (k+1)*(k+1) + fn(lo+1, hi, 0)
for mid in range(lo+2, hi):
if boxes[lo] == boxes[mid]:
ans = max(ans, fn(lo+1, mid, 0) + fn(mid, hi, k+1))
return ans
return fn(0, len(boxes), 0) | https://leetcode.com/problems/remove-boxes/discuss/1379392/Python3-dp | 2 | You are given several boxes with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.
Return the maximum points you can get.
Example 1:
Input: boxes = [1,3,2,2,2,3,4,3,1]
Output: 23
Explanation:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
----> [1, 3, 3, 3, 1] (1*1=1 points)
----> [1, 1] (3*3=9 points)
----> [] (2*2=4 points)
Example 2:
Input: boxes = [1,1,1]
Output: 9
Example 3:
Input: boxes = [1]
Output: 1
Constraints:
1 <= boxes.length <= 100
1 <= boxes[i] <= 100 | [Python3] dp | 293 | remove-boxes | 0.479 | ye15 | Hard | 9,595 | 546 |
number of provinces | class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
n = len(M) #1
visited = [False]*n #2
count = 0 #3
if not M: #4
return 0 #5
def dfs(u): #6
for v in range(n): #7
if M[u][v] == 1 and visited[v] == False: #8
visited[v] = True #9
dfs(v) #10
for idx in range(n): #11
if visited[idx] == False: #12
count += 1 #13
visited[idx] == True #14
dfs(idx) #15
return count #16 | https://leetcode.com/problems/number-of-provinces/discuss/727759/Python3-solution-with-detailed-explanation | 17 | There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.
Return the total number of provinces.
Example 1:
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Example 2:
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] is 1 or 0.
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i] | Python3 solution with detailed explanation | 1,600 | number-of-provinces | 0.634 | peyman_np | Medium | 9,597 | 547 |
student attendance record i | class Solution:
def checkRecord(self, s: str) -> bool:
return (s.count('A') < 2) and ('LLL' not in s)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/student-attendance-record-i/discuss/356636/Solution-in-Python-3-(one-line) | 16 | You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
The student is eligible for an attendance award if they meet both of the following criteria:
The student was absent ('A') for strictly fewer than 2 days total.
The student was never late ('L') for 3 or more consecutive days.
Return true if the student is eligible for an attendance award, or false otherwise.
Example 1:
Input: s = "PPALLP"
Output: true
Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.
Example 2:
Input: s = "PPALLL"
Output: false
Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
Constraints:
1 <= s.length <= 1000
s[i] is either 'A', 'L', or 'P'. | Solution in Python 3 (one line) | 940 | student-attendance-record-i | 0.481 | junaidmansuri | Easy | 9,644 | 551 |
student attendance record ii | class Solution:
def checkRecord(self, n: int) -> int:
C, m = [1,1,0,1,0,0], 10**9 + 7
for i in range(n-1):
a, b = sum(C[:3]) % m, sum(C[3:]) % m
C = [a, C[0], C[1], a + b, C[3], C[4]]
return (sum(C) % m) | https://leetcode.com/problems/student-attendance-record-ii/discuss/356750/Solution-in-Python-3-(five-lines)-(with-explanation) | 12 | An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A': Absent.
'L': Late.
'P': Present.
Any student is eligible for an attendance award if they meet both of the following criteria:
The student was absent ('A') for strictly fewer than 2 days total.
The student was never late ('L') for 3 or more consecutive days.
Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.
Example 1:
Input: n = 2
Output: 8
Explanation: There are 8 records with length 2 that are eligible for an award:
"PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"
Only "AA" is not eligible because there are 2 absences (there need to be fewer than 2).
Example 2:
Input: n = 1
Output: 3
Example 3:
Input: n = 10101
Output: 183236316
Constraints:
1 <= n <= 105 | Solution in Python 3 (five lines) (with explanation) | 1,900 | student-attendance-record-ii | 0.412 | junaidmansuri | Hard | 9,674 | 552 |
optimal division | class Solution:
def optimalDivision(self, nums: List[int]) -> str:
if len(nums) <= 2: return "/".join(map(str, nums))
return f'{nums[0]}/({"/".join(map(str, nums[1:]))})' | https://leetcode.com/problems/optimal-division/discuss/1265206/Python3-string-concatenation | 3 | You are given an integer array nums. The adjacent integers in nums will perform the float division.
For example, for nums = [2,3,4], we will evaluate the expression "2/3/4".
However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.
Return the corresponding expression that has the maximum value in string format.
Note: your expression should not contain redundant parenthesis.
Example 1:
Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority.
So you should return "1000/(100/10/2)".
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
Example 2:
Input: nums = [2,3,4]
Output: "2/(3/4)"
Explanation: (2/(3/4)) = 8/3 = 2.667
It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667
Constraints:
1 <= nums.length <= 10
2 <= nums[i] <= 1000
There is only one optimal division for the given input. | [Python3] string concatenation | 86 | optimal-division | 0.597 | ye15 | Medium | 9,687 | 553 |
brick wall | class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
count = defaultdict(int)
tot = len(wall)
if tot == 1 and len(wall[0]) > 1:
return 0
elif tot == 1 and len(wall[0]) == 1:
return 1
for w in wall:
s = 0
for i in range(len(w)):
s += w[i]
count[s] += 1
count[s] -= 1
return tot - max(count.values()) | https://leetcode.com/problems/brick-wall/discuss/1736767/python-easy-hashmap-solution | 1 | There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.
Example 1:
Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
Output: 2
Example 2:
Input: wall = [[1],[1],[1]]
Output: 3
Constraints:
n == wall.length
1 <= n <= 104
1 <= wall[i].length <= 104
1 <= sum(wall[i].length) <= 2 * 104
sum(wall[i]) is the same for each row i.
1 <= wall[i][j] <= 231 - 1 | python easy hashmap solution | 62 | brick-wall | 0.532 | byuns9334 | Medium | 9,696 | 554 |
next greater element iii | class Solution:
def nextGreaterElement(self, n: int) -> int:
m=list(str(n)) ## n = 257761
l = len(m) ## l = 6
d = {}
res = str(n)
## reading character backwards: 1->6->7->7->5 break
for i,c in enumerate(m[::-1]):
if not d:
d[c]=1 ## d = {'1':1}
else:
if all(c >= x for x in d):
d[c]=d.get(c,0)+1 ## d = {'1':1,'6':1,'7':2}
else:
d[c]=d.get(c,0)+1 ## d = {'1':1,'5':1,'6':1,'7':2}
res = ''.join(m[:l-1-i]) ## res = '2'
stock = sorted(list(d.keys())) ## stock = ['1','5','6','7']
cplus = stock[stock.index(c)+1] ## cplus = '6' just > '5'
res += cplus ## res = '26'
d[cplus] -= 1 ## d = {'1':1,'5':1,'6':0,'7':2}
res += ''.join([x * d[x] for x in stock])
## res = '26' + '1577'
break
return int(res) if n < int(res) < (2**31-1) else -1 | https://leetcode.com/problems/next-greater-element-iii/discuss/983461/Simple-Python-Solution-easy-to-understand-reading-backwards-from-the-end | 7 | Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.
Example 1:
Input: n = 12
Output: 21
Example 2:
Input: n = 21
Output: -1
Constraints:
1 <= n <= 231 - 1 | Simple Python Solution, easy to understand, reading backwards from the end | 935 | next-greater-element-iii | 0.341 | KevinZzz666 | Medium | 9,708 | 556 |
reverse words in a string iii | class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
for i in range(len(s)): s[i] = s[i][::-1]
return " ".join(s)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/reverse-words-in-a-string-iii/discuss/332138/Simple-Python-3-Solution-(beats-~98)-(three-lines) | 8 | Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "Mr Ding"
Output: "rM gniD"
Constraints:
1 <= s.length <= 5 * 104
s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s.
All the words in s are separated by a single space. | Simple Python 3 Solution (beats ~98%) (three lines) | 2,000 | reverse-words-in-a-string-iii | 0.816 | junaidmansuri | Easy | 9,725 | 557 |
logical or of two binary grids represented as quad trees | class Solution:
def intersect(self, quadTree1: 'Node', quadTree2: 'Node') -> 'Node':
if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition
if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition
tl = self.intersect(quadTree1.topLeft, quadTree2.topLeft)
tr = self.intersect(quadTree1.topRight, quadTree2.topRight)
bl = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)
br = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight)
if tl.isLeaf and tr.isLeaf and bl.isLeaf and br.isLeaf and tl.val == tr.val == bl.val == br.val:
return Node(tl.val, True, None, None, None, None)
return Node(None, False, tl, tr, bl, br) | https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/discuss/884082/Python3-9-line-recursive-(64ms-93.33) | 2 | A Binary Matrix is a matrix in which all the elements are either 0 or 1.
Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix.
Return a Quad-Tree representing the n * n binary matrix which is the result of logical bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2.
Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
isLeaf: True if the node is leaf node on the tree or False if the node has the four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
If the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.
If the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.
Recurse for each of the children with the proper sub-grid.
If you want to know more about the Quad-Tree, you can refer to the wiki.
Quad-Tree format:
The input/output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].
If the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.
Example 1:
Input: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]
, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
Output: [[0,0],[1,1],[1,1],[1,1],[1,0]]
Explanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
Example 2:
Input: quadTree1 = [[1,0]], quadTree2 = [[1,0]]
Output: [[1,0]]
Explanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.
The resulting matrix is of size 1*1 with also zero.
Constraints:
quadTree1 and quadTree2 are both valid Quad-Trees each representing a n * n grid.
n == 2x where 0 <= x <= 9. | [Python3] 9-line recursive (64ms 93.33%) | 151 | logical-or-of-two-binary-grids-represented-as-quad-trees | 0.483 | ye15 | Medium | 9,780 | 558 |
maximum depth of n ary tree | class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:
# empty node or empty tree
return 0
else:
# DFS to choose the longest path
if root.children:
# current node has subtrees
return max( self.maxDepth(child) for child in root.children ) + 1
else:
# current node is leaf node
return 1 | https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/629671/Python-O(n)-by-DFS-90%2B-w-Comment | 4 | Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5
Constraints:
The total number of nodes is in the range [0, 104].
The depth of the n-ary tree is less than or equal to 1000. | Python O(n) by DFS 90%+ [w/ Comment] | 438 | maximum-depth-of-n-ary-tree | 0.716 | brianchiang_tw | Easy | 9,782 | 559 |
subarray sum equals k | class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
ans=0
prefsum=0
d={0:1}
for num in nums:
prefsum = prefsum + num
if prefsum-k in d:
ans = ans + d[prefsum-k]
if prefsum not in d:
d[prefsum] = 1
else:
d[prefsum] = d[prefsum]+1
return ans | https://leetcode.com/problems/subarray-sum-equals-k/discuss/1759711/Python-Simple-Python-Solution-Using-PrefixSum-and-Dictionary | 192 | Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
Constraints:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107 | [ Python ] ✅✅ Simple Python Solution Using PrefixSum and Dictionary 🔥✌ | 26,200 | subarray-sum-equals-k | 0.44 | ASHOK_KUMAR_MEGHVANSHI | Medium | 9,800 | 560 |
array partition | class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
sum_ = 0
for i in range(0,len(nums),2):
sum_ += nums[i]
return sum_
# Time : 356 ms
# Memory : 16.7 M | https://leetcode.com/problems/array-partition/discuss/390198/Algorithm-and-solution-in-python3 | 47 | Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
Example 1:
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
Example 2:
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
Constraints:
1 <= n <= 104
nums.length == 2 * n
-104 <= nums[i] <= 104 | Algorithm and solution in python3 | 3,200 | array-partition | 0.767 | ramanaditya | Easy | 9,846 | 561 |
binary tree tilt | class Solution:
def findTilt(self, root: Optional[TreeNode]) -> int:
def rec(node):
nonlocal res
if not node:
return 0
left_sum = rec(node.left)
right_sum = rec(node.right)
res += abs(left_sum - right_sum)
return left_sum + node.val + right_sum
res = 0
rec(root)
return res | https://leetcode.com/problems/binary-tree-tilt/discuss/1617385/Recursive-solution-Python | 3 | Given the root of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.
Example 1:
Input: root = [1,2,3]
Output: 1
Explanation:
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
Example 2:
Input: root = [4,2,9,3,5,null,7]
Output: 15
Explanation:
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
Example 3:
Input: root = [21,7,14,1,1,2,2,3,3]
Output: 9
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000 | Recursive solution Python | 192 | binary-tree-tilt | 0.595 | kryuki | Easy | 9,877 | 563 |
find the closest palindrome | class Solution:
def find_next_palindrome(self, n, additive):
l = len(n)
if l == 0:
return 0
first_half = str(int(n[:l // 2 + l % 2]) + additive)
return int(first_half + first_half[(-1 - l%2)::-1])
def nearestPalindromic(self, n: str) -> str:
m = int(n)
candidates = [self.find_next_palindrome(n, additive) for additive in range(-1, 2)] # Cases 1, 2, and 3
candidates.append(self.find_next_palindrome("9"*(len(n)-1), 0)) # Case 4
candidates.append(self.find_next_palindrome("1" + "0"*len(n), 0)) # Case 5
ans = None
for t in candidates:
if t == m:
continue
if ans is None or abs(ans - m) > abs(t - m) or (abs(ans - m) == abs(t - m) and t < m):
ans = t
return str(ans) | https://leetcode.com/problems/find-the-closest-palindrome/discuss/2581120/Only-5-Cases-to-Consider%3A-Concise-implementation-in-Python-with-Full-Explanation | 3 | Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
Example 1:
Input: n = "123"
Output: "121"
Example 2:
Input: n = "1"
Output: "0"
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
Constraints:
1 <= n.length <= 18
n consists of only digits.
n does not have leading zeros.
n is representing an integer in the range [1, 1018 - 1]. | Only 5 Cases to Consider: Concise implementation in Python with Full Explanation | 269 | find-the-closest-palindrome | 0.22 | metaphysicalist | Hard | 9,890 | 564 |
array nesting | class Solution:
def arrayNesting(self, nums: List[int]) -> int:
res, l = 0, len(nums)
globalSet = set()
for k in range(l):
if k not in globalSet:
currLength, currSet, val = 0, set(), k
while True:
if nums[val] in currSet: break
currSet.add(nums[val])
globalSet.add(nums[val])
currLength, val = currLength + 1, nums[val]
res = max(res, currLength)
return res | https://leetcode.com/problems/array-nesting/discuss/1438213/CLEAN-and-SHORT-PYTHON-O(N)-TIME-O(N)-SPACE | 6 | You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
The first element in s[k] starts with the selection of the element nums[k] of index = k.
The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
We stop adding right before a duplicate element occurs in s[k].
Return the longest length of a set s[k].
Example 1:
Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation:
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
Example 2:
Input: nums = [0,1,2]
Output: 1
Constraints:
1 <= nums.length <= 105
0 <= nums[i] < nums.length
All the values of nums are unique. | CLEAN & SHORT PYTHON, O(N) TIME, O(N) SPACE | 442 | array-nesting | 0.565 | kushagrabainsla | Medium | 9,894 | 565 |
reshape the matrix | class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
flatten = []
new_mat = []
for row in mat:
for num in row:
flatten.append(num)
if r * c != len(flatten): # when given parameters is NOT possible and legal
return mat
else:
for row_index in range(r):
new_mat.append(flatten[row_index * c : row_index * c + c])
return new_mat | https://leetcode.com/problems/reshape-the-matrix/discuss/2046840/Python-Intuitive-%2B-Direct-for-Beginners-with-Illustrations | 45 | In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Example 2:
Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300 | [Python] Intuitive + Direct for Beginners with Illustrations | 1,100 | reshape-the-matrix | 0.627 | ziaiz-zythoniz | Easy | 9,912 | 566 |
permutation in string | class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
window = len(s1)
s1_c = Counter(s1)
for i in range(len(s2)-window+1):
s2_c = Counter(s2[i:i+window])
if s2_c == s1_c:
return True
return False | https://leetcode.com/problems/permutation-in-string/discuss/1476884/Python-Sliding-Window-and-Dictionary.-Easy-to-understand | 29 | Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
1 <= s1.length, s2.length <= 104
s1 and s2 consist of lowercase English letters. | Python Sliding Window and Dictionary. Easy to understand | 3,000 | permutation-in-string | 0.437 | ParthitPatel | Medium | 9,964 | 567 |
subtree of another tree | class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if not s:
return False
if self.isSameTree(s, t):
return True
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q | https://leetcode.com/problems/subtree-of-another-tree/discuss/265239/Python-Easy-to-Understand | 83 | Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
Constraints:
The number of nodes in the root tree is in the range [1, 2000].
The number of nodes in the subRoot tree is in the range [1, 1000].
-104 <= root.val <= 104
-104 <= subRoot.val <= 104 | Python Easy to Understand | 13,100 | subtree-of-another-tree | 0.46 | ccparamecium | Easy | 10,009 | 572 |
distribute candies | class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
return min(len(candyType) //2, len(set(candyType))) | https://leetcode.com/problems/distribute-candies/discuss/1088016/Python.-One-liner-Easy-understanding-solution. | 2 | Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.
Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.
Example 1:
Input: candyType = [1,1,2,2,3,3]
Output: 3
Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.
Example 2:
Input: candyType = [1,1,2,3]
Output: 2
Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.
Example 3:
Input: candyType = [6,6,6,6]
Output: 1
Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.
Constraints:
n == candyType.length
2 <= n <= 104
n is even.
-105 <= candyType[i] <= 105 | Python. One-liner Easy-understanding solution. | 224 | distribute-candies | 0.661 | m-d-f | Easy | 10,043 | 575 |
out of boundary paths | class Solution: # The plan is to accrete the number of paths from the starting cell, which
# is the sum of (a) the number of adjacent positions that are off the grid
# and (b) the number of paths from the adjacent cells in the grid within
# maxMove steps. We determine (b) recursively.
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
@lru_cache(None) # <-- Many cells are revisited so we cache the previous calls
def dp (x,y,steps = maxMove):
if x not in range(m) or y not in range(n): # <-- Moved off the grid so increment the tally
return 1
if not steps: # <-- Ran out of the maxMove steps
return 0
ans, dx, dy = 0, 1, 0
for _ in range(4):
ans+= dp(x+dx, y+dy, steps-1) # <-- visit the adjacent cells
dx, dy = dy,-dx # <-- iterates thru the directions:
# south => east => north => west
return ans
return dp (startRow, startColumn)%1000000007
# Thanks to XixiangLiu for fixing a number of my errors in the original post. | https://leetcode.com/problems/out-of-boundary-paths/discuss/2288190/Python3-oror-recursion-one-grid-w-explanation-oror-TM%3A-8949 | 5 | There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.
Given the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
Output: 6
Example 2:
Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
Output: 12
Constraints:
1 <= m, n <= 50
0 <= maxMove <= 50
0 <= startRow < m
0 <= startColumn < n | Python3 || recursion , one grid w/ explanation || T/M: 89%/49% | 371 | out-of-boundary-paths | 0.443 | warrenruud | Medium | 10,073 | 576 |
shortest unsorted continuous subarray | class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
l, u = len(nums) - 1,0
for i in range(len(nums)):
if nums[i]!=sorted_nums[i]:
l=min(l, i)
u=max(u, i)
return 0 if l>=u else u-l+1 | https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/2002965/Python-Simple-Two-Approaches | 11 | Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.
Return the shortest such subarray and output its length.
Example 1:
Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Example 2:
Input: nums = [1,2,3,4]
Output: 0
Example 3:
Input: nums = [1]
Output: 0
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
Follow up: Can you solve it in O(n) time complexity? | Python Simple Two Approaches | 828 | shortest-unsorted-continuous-subarray | 0.363 | constantine786 | Medium | 10,093 | 581 |
delete operation for two strings | class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m,n=len(word1),len(word2)
@cache
def lcs(i, j): # find longest common subsequence
if i==m or j==n:
return 0
return 1 + lcs(i+1, j+1) if word1[i]==word2[j] else max(lcs(i+1, j), lcs(i,j+1))
# subtract the lcs length from both the strings
# the difference is the number of characters that has to deleted
return m + n - 2*lcs(0,0) | https://leetcode.com/problems/delete-operation-for-two-strings/discuss/2148966/Python-DP-2-approaches-using-LCS | 49 | Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
In one step, you can delete exactly one character in either string.
Example 1:
Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Example 2:
Input: word1 = "leetcode", word2 = "etco"
Output: 4
Constraints:
1 <= word1.length, word2.length <= 500
word1 and word2 consist of only lowercase English letters. | Python DP 2 approaches using LCS ✅ | 3,000 | delete-operation-for-two-strings | 0.594 | constantine786 | Medium | 10,142 | 583 |
erect the fence | class Solution:
def outerTrees(self, points: List[List[int]]) -> List[List[int]]:
"""
Use Monotone Chain algorithm.
"""
def is_clockwise(
p0: List[int], p1: List[int], p2: List[int]) -> bool:
"""
Determine the orientation the slope p0p2 is on the clockwise
orientation of the slope p0p1.
"""
return (p1[1] - p0[1]) * (p2[0] - p0[0]) > \
(p2[1] - p0[1]) * (p1[0] - p0[0])
sortedPoints = sorted(points)
# Scan from left to right to generate the lower part of the hull.
hull = []
for p in sortedPoints:
while len(hull) > 1 and is_clockwise(hull[-2], hull[-1], p):
hull.pop()
hull.append(p)
if len(hull) == len(points): # All the points are on the perimeter now.
return hull
# Scan from right to left to generate the higher part of the hull.
# Remove the last point first as it will be scanned again.
hull.pop()
for p in reversed(sortedPoints):
while len(hull) > 1 and is_clockwise(hull[-2], hull[-1], p):
hull.pop()
hull.append(p)
# Pop the first point as it is already added to hull when processing
# the lower part.
hull.pop()
return hull | https://leetcode.com/problems/erect-the-fence/discuss/864619/Python-Solution-with-Monotone-Chain-Algorithm | 4 | You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.
Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed.
Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.
Example 1:
Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]
Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.
Example 2:
Input: trees = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]
Explanation: The fence forms a line that passes through all the trees.
Constraints:
1 <= trees.length <= 3000
trees[i].length == 2
0 <= xi, yi <= 100
All the given positions are unique. | Python Solution with Monotone Chain Algorithm | 542 | erect-the-fence | 0.523 | eroneko | Hard | 10,180 | 587 |
n ary tree preorder traversal | class Solution(object):
def preorder(self, root):
# To store the output result...
output = []
self.traverse(root, output)
return output
def traverse(self, root, output):
# Base case: If root is none...
if root is None: return
# Append the value of the root node to the output...
output.append(root.val)
# Recursively traverse each node in the children array...
for child in root.children:
self.traverse(child, output) | https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/2496970/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Python3-oror-Iterative-and-Recursive(DFS) | 28 | Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The height of the n-ary tree is less than or equal to 1000.
Follow up: Recursive solution is trivial, could you do it iteratively? | Very Easy || 100% || Fully Explained || Java, C++, Python, Python3 || Iterative & Recursive(DFS) | 1,600 | n-ary-tree-preorder-traversal | 0.762 | PratikSen07 | Easy | 10,201 | 589 |
n ary tree postorder traversal | class Solution:
def postorder(self, root: 'Node') -> List[int]:
def dfs(node):
"""Populate ans via post-order traversal."""
if not node: return
for child in node.children: dfs(child)
ans.append(node.val)
ans = []
dfs(root)
return ans | https://leetcode.com/problems/n-ary-tree-postorder-traversal/discuss/355782/Python3-recursive-and-iterative-implementation | 2 | Given the root of an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
Example 1:
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]
Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The height of the n-ary tree is less than or equal to 1000.
Follow up: Recursive solution is trivial, could you do it iteratively? | [Python3] recursive & iterative implementation | 129 | n-ary-tree-postorder-traversal | 0.772 | ye15 | Easy | 10,232 | 590 |
tag validator | class Solution:
def isValid(self, code: str) -> bool:
if code[0] != '<' or code[-1] != '>': return False
i, n = 0, len(code)
stk = []
while i < n:
if code[i] == '<':
if i != 0 and code[i: i + 9] == '<![CDATA[':
if not stk: return False
j = i + 9
while j + 3 <= n and code[j: j + 3] != ']]>': j += 1
if code[j: j + 3] == ']]>': i = j + 3
else: return False
else:
start = i
isend = False
i += 1
if i >= n: return False
if code[i] == r'/':
isend = True
i += 1
if i >= n: return False
tag = ''
while i < n and code[i] != '>':
if not code[i].isupper(): return False
tag += code[i]
i += 1
if i >= n or len(tag) == 0 or len(tag) > 9: return False
if isend:
if not stk or stk[-1] != tag: return False
stk.pop(-1)
else:
if start != 0 and not stk: return False
stk.append(tag)
i += 1
else:
if not stk: return False
while i < n and code[i] != '<': i += 1
return not stk | https://leetcode.com/problems/tag-validator/discuss/449403/Two-Python-Solution%3A(1)-linear-paring-with-stack(2)BNF-parsing-with-pyparsing | 1 | Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.
A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).
The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.
Example 1:
Input: code = "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
Output: true
Explanation:
The code is wrapped in a closed tag : <DIV> and </DIV>.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.
So TAG_CONTENT is valid, and then the code is valid. Thus return true.
Example 2:
Input: code = "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
Output: true
Explanation:
We first separate the code into : start_tag|tag_content|end_tag.
start_tag -> "<DIV>"
end_tag -> "</DIV>"
tag_content could also be separated into : text1|cdata|text2.
text1 -> ">> ![cdata[]] "
cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"
text2 -> "]]>>]"
The reason why start_tag is NOT "<DIV>>>" is because of the rule 6.
The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.
Example 3:
Input: code = "<A> <B> </A> </B>"
Output: false
Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.
Constraints:
1 <= code.length <= 500
code consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '. | Two Python Solution:(1) linear paring with stack;(2)BNF parsing with pyparsing | 402 | tag-validator | 0.371 | cava | Hard | 10,250 | 591 |
fraction addition and subtraction | class Solution:
def fractionAddition(self, exp: str) -> str:
if not exp:
return "0/1"
if exp[0] != '-':
exp = '+' + exp
# Parse the expression to get the numerator and denominator of each fraction
num = []
den = []
pos = True
i = 0
while i < len(exp):
# Check sign
pos = True if exp[i] == '+' else False
# Get numerator
i += 1
n = 0
while exp[i].isdigit():
n = n*10 + int(exp[i])
i += 1
num.append(n if pos else -n)
# Get denominator
i += 1
d = 0
while i < len(exp) and exp[i].isdigit():
d = d*10 + int(exp[i])
i += 1
den.append(d)
# Multiply the numerator of all fractions so that they have the same denominator
denominator = functools.reduce(lambda x, y: x*y, den)
for i,(n,d) in enumerate(zip(num, den)):
num[i] = n * denominator // d
# Sum up all of the numerator values
numerator = sum(num)
# Divide numerator and denominator by the greatest common divisor (gcd)
g = math.gcd(numerator, denominator)
numerator = numerator // g
denominator = denominator // g
return f"{numerator}/{denominator}" | https://leetcode.com/problems/fraction-addition-and-subtraction/discuss/1128722/Python-Simple-Parsing-with-example | 6 | Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.
Example 1:
Input: expression = "-1/2+1/2"
Output: "0/1"
Example 2:
Input: expression = "-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input: expression = "1/3-1/2"
Output: "-1/6"
Constraints:
The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
The number of given fractions will be in the range [1, 10].
The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int. | [Python] Simple Parsing - with example | 918 | fraction-addition-and-subtraction | 0.521 | rowe1227 | Medium | 10,252 | 592 |
valid square | class Solution:
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
def dist(point1,point2):
return (point1[0]-point2[0])**2+(point1[1]-point2[1])**2
D=[
dist(p1,p2),
dist(p1,p3),
dist(p1,p4),
dist(p2,p3),
dist(p2,p4),
dist(p3,p4)
]
D.sort()
return 0<D[0]==D[1]==D[2]==D[3] and D[4]==D[5] | https://leetcode.com/problems/valid-square/discuss/931866/python-easy-to-understand-3-lines-code-beats-95 | 17 | Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.
The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Example 1:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
Example 2:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false
Example 3:
Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]
Output: true
Constraints:
p1.length == p2.length == p3.length == p4.length == 2
-104 <= xi, yi <= 104 | python easy to understand 3 lines code beats 95% | 966 | valid-square | 0.44 | Mahesh_N_V | Medium | 10,260 | 593 |
longest harmonious subsequence | class Solution:
def findLHS(self, nums: List[int]) -> int:
tmp = Counter(nums)
keys = tmp.keys()
max = 0
for num in keys:
if num - 1 in keys:
if tmp[num - 1] + tmp[num] > max:
max = tmp[num - 1] + tmp[num]
return max | https://leetcode.com/problems/longest-harmonious-subsequence/discuss/1049126/Python.-O(n)-Cool-easy-and-clear-solution. | 6 | We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Example 2:
Input: nums = [1,2,3,4]
Output: 2
Example 3:
Input: nums = [1,1,1,1]
Output: 0
Constraints:
1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109 | Python. O(n), Cool, easy & clear solution. | 494 | longest-harmonious-subsequence | 0.532 | m-d-f | Easy | 10,275 | 594 |
range addition ii | class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
min_row = m
min_col = n
for i in range(len(ops)):
min_row=min(min_row, ops[i][0])
min_col=min(min_col, ops[i][1])
return min_row*min_col | https://leetcode.com/problems/range-addition-ii/discuss/1434604/C-or-C%2B%2B-or-Python-or-Java-or-C-or-JavaScript-or-Go-Same-Simple-Solution | 23 | You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
Example 2:
Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]
Output: 4
Example 3:
Input: m = 3, n = 3, ops = []
Output: 9
Constraints:
1 <= m, n <= 4 * 104
0 <= ops.length <= 104
ops[i].length == 2
1 <= ai <= m
1 <= bi <= n | [ C | C++ | Python | Java | C# | JavaScript | Go ] Same Simple Solution | 2,000 | range-addition-ii | 0.551 | HadaEn | Easy | 10,293 | 598 |
minimum index sum of two lists | class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
d = {}
d2 = {}
min_ = 5000
ret = []
for i in range(len(list1)):
d[list1[i]] = i+1
for i in range(len(list2)):
a = d.get(list2[i], 0)
if a:
b = a+i-1
if b <= min_:
min_ = b
d2[list2[i]] = b
for k,v in d2.items():
if v <= min_:
ret.append(k)
return ret | https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/1382036/Easy-Python-Solution-(Memory-Usage-less-than-97) | 3 | Given two arrays of strings list1 and list2, find the common strings with the least index sum.
A common string is a string that appeared in both list1 and list2.
A common string with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings.
Return all the common strings with the least index sum. Return the answer in any order.
Example 1:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]
Explanation: The only common string is "Shogun".
Example 2:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
Output: ["Shogun"]
Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1.
Example 3:
Input: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"]
Output: ["sad","happy"]
Explanation: There are three common strings:
"happy" with index sum = (0 + 1) = 1.
"sad" with index sum = (1 + 0) = 1.
"good" with index sum = (2 + 2) = 4.
The strings with the least index sum are "sad" and "happy".
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i] and list2[i] consist of spaces ' ' and English letters.
All the strings of list1 are unique.
All the strings of list2 are unique.
There is at least a common string between list1 and list2. | Easy Python Solution (Memory Usage less than 97%) | 454 | minimum-index-sum-of-two-lists | 0.529 | the_sky_high | Easy | 10,308 | 599 |
non negative integers without consecutive ones | class Solution:
def findIntegers(self, n: int) -> int:
# f stores the fibonacci numbers
f = [1, 2]
for i in range(2, 30):
f.append(f[-1]+f[-2])
# last_seen tells us if there was a one right before.
# If that is the case, we are done then and there!
# ans is the answer
ans, last_seen = 0, 0
for i in reversed(range(30)):
if (1 << i) & n: # is the ith bit set?
ans += f[i]
if last_seen:
ans -= 1
break
last_seen = 1
else:
last_seen = 0
return ans+1 | https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/discuss/1361794/Python3-Official-Solution-Explained-Simply-with-Diagrams | 100 | Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.
Example 1:
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
Example 2:
Input: n = 1
Output: 2
Example 3:
Input: n = 2
Output: 3
Constraints:
1 <= n <= 109 | [Python3] Official Solution Explained Simply with Diagrams | 2,500 | non-negative-integers-without-consecutive-ones | 0.39 | chaudhary1337 | Hard | 10,337 | 600 |
can place flowers | class Solution:
def canPlaceFlowers(self, f: List[int], n: int) -> bool:
L, i, c, f = len(f)-2, -2, 0, f + [0]
while i < L:
i += 2
if f[i] == 1: continue
if f[i+1] == 0: c += 1
else: i += 1
return n <= c
class Solution:
def canPlaceFlowers(self, f: List[int], n: int) -> bool:
L, f, i, c = len(f), [0] + f + [0], 1, 0
while i <= L:
if f[i-1:i+2] == [0,0,0]: c, i = c + 1, i + 1
i += 1
return n <= c
class Solution:
def canPlaceFlowers(self, f: List[int], n: int) -> bool:
L, f, s, c = len(f), f + [0,1], 0, 1
for i in range(L+2):
if f[i] == 1: s, c = s + max(0,c-1)//2, 0
else: c += 1
return n <= s
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/can-place-flowers/discuss/380474/Three-Solutions-in-Python-3-(beats-~100) | 7 | You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Constraints:
1 <= flowerbed.length <= 2 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length | Three Solutions in Python 3 (beats ~100%) | 1,800 | can-place-flowers | 0.329 | junaidmansuri | Easy | 10,341 | 605 |
construct string from binary tree | class Solution:
def tree2str(self, t: TreeNode) -> str:
sb = [] # init string builder
# helper function to create result
def helper(node: TreeNode) -> None:
if not node:
return
sb.append(str(node.val))
if not node.left and not node.right:
# leaf node, stop processing
return
sb.append('(') # always wrap left node with parenthesis when right node exist
helper(node.left) # process left node recursively
sb.append(')')
if node.right: # adding parenthesis for the right node only if it is not empty
sb.append('(')
helper(node.right)
sb.append(')')
helper(t)
return ''.join(sb) | https://leetcode.com/problems/construct-string-from-binary-tree/discuss/1112030/Python-recursive-solution-with-string-builder | 15 | Given the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:
Node Representation: Each node in the tree should be represented by its integer value.
Parentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:
If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node's value.
If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.
Omitting Empty Parentheses: Any empty parentheses pairs (i.e., ()) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.
In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately.
Example 1:
Input: root = [1,2,3,4]
Output: "1(2(4))(3)"
Explanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)".
Example 2:
Input: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.
Constraints:
The number of nodes in the tree is in the range [1, 104].
-1000 <= Node.val <= 1000 | Python recursive solution with string builder | 1,200 | construct-string-from-binary-tree | 0.636 | ignat-s | Easy | 10,378 | 606 |
find duplicate file in system | class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
m = defaultdict(list)
for p in paths:
# 1. split the string by ' '
path = p.split()
# the first string is the directory path
# the rest of them are just file names with content
directoryPath, rest = path[0], path[1:]
# for each file names with content
for f in rest:
# we retrieve the file name and the file content
fileName, fileContent = f.split('(')[0], f.split('(')[1][:-1]
# then group {directoryPath}/{fileName} by file content
m[fileContent].append("{}/{}".format(directoryPath, fileName))
# return the file list only when the size is greater than 1, meaning they are duplicate files
return [m[k] for k in m.keys() if len(m[k]) > 1] | https://leetcode.com/problems/find-duplicate-file-in-system/discuss/2595019/LeetCode-The-Hard-Way-Explained-Line-By-Line | 28 | Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
"directory_path/file_name.txt"
Example 1:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Example 2:
Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
Constraints:
1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 105
paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
You may assume no files or directories share the same name in the same directory.
You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
Follow up:
Imagine you are given a real file system, how will you search files? DFS or BFS?
If the file content is very large (GB level), how will you modify your solution?
If you can only read the file by 1kb each time, how will you modify your solution?
What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
How to make sure the duplicated files you find are not false positive? | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 1,200 | find-duplicate-file-in-system | 0.678 | wingkwong | Medium | 10,417 | 609 |
valid triangle number | class Solution:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
ans = 0
for i in range(len(nums)):
lo, hi = 0, i-1
while lo < hi:
if nums[lo] + nums[hi] > nums[i]:
ans += hi - lo
hi -= 1
else: lo += 1
return ans | https://leetcode.com/problems/valid-triangle-number/discuss/884373/Python3-O(N2)-time-solution | 3 | Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Example 2:
Input: nums = [4,2,3,4]
Output: 4
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000 | [Python3] O(N^2) time solution | 222 | valid-triangle-number | 0.504 | ye15 | Medium | 10,449 | 611 |
merge two binary trees | class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1: return root2
if not root2: return root1
queue = deque([(root1, root2)])
while queue:
current_root1, current_root2 = queue.pop()
if current_root1.left and current_root2.left: queue.append((current_root1.left, current_root2.left))
elif not current_root1.left: current_root1.left = current_root2.left
if current_root1.right and current_root2.right: queue.append((current_root1.right, current_root2.right))
elif not current_root1.right: current_root1.right = current_root2.right
current_root1.val += current_root2.val
return root1 | https://leetcode.com/problems/merge-two-binary-trees/discuss/1342175/Elegant-Python-Iterative-and-Recursive-solutions | 9 | You are given two binary trees root1 and root2.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
Example 1:
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]
Example 2:
Input: root1 = [1], root2 = [1,2]
Output: [2,2]
Constraints:
The number of nodes in both trees is in the range [0, 2000].
-104 <= Node.val <= 104 | Elegant Python Iterative & Recursive solutions | 453 | merge-two-binary-trees | 0.786 | soma28 | Easy | 10,460 | 617 |
task scheduler | class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
cnt = [0] * 26
for i in tasks: cnt[ord(i) - ord('A')] += 1
mx, mxcnt = max(cnt), 0
for i in cnt:
if i == mx: mxcnt += 1
return max((mx - 1) * (n + 1) + mxcnt, len(tasks)) | https://leetcode.com/problems/task-scheduler/discuss/2667200/Python-O(n)-time-count-it-directly | 10 | You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.
Return the minimum number of intervals required to complete all tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.
After completing task A, you must wait two cycles before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th cycle, you can do A again as 2 intervals have passed.
Example 2:
Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6
Explanation: A possible sequence is: A -> B -> C -> D -> A -> B.
With a cooling interval of 1, you can repeat a task after just one other task.
Example 3:
Input: tasks = ["A","A","A", "B","B","B"], n = 3
Output: 10
Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.
There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.
Constraints:
1 <= tasks.length <= 104
tasks[i] is an uppercase English letter.
0 <= n <= 100 | Python O(n) time, count it directly | 1,100 | task-scheduler | 0.558 | alex391a | Medium | 10,490 | 621 |
add one row to tree | class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int, side = "left") -> TreeNode:
if d == 1:
res = TreeNode(v)
setattr(res, side, root)
return res
if root:
root.left = self.addOneRow(root.left, v, d - 1)
root.right = self.addOneRow(root.right, v, d - 1, 'right')
return root | https://leetcode.com/problems/add-one-row-to-tree/discuss/1101104/Python.-Recursive.-Easy-understanding-solution | 13 | Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
cur's original left subtree should be the left subtree of the new left subtree root.
cur's original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.
Example 1:
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]
Example 2:
Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 104].
The depth of the tree is in the range [1, 104].
-100 <= Node.val <= 100
-105 <= val <= 105
1 <= depth <= the depth of tree + 1 | Python. Recursive. Easy understanding solution | 772 | add-one-row-to-tree | 0.595 | m-d-f | Medium | 10,507 | 623 |
maximum product of three numbers | class Solution:
def maximumProduct(self, nums: List[int]) -> int:
max1 = max2 = max3 = float("-inf")
min1 = min2 = float("inf")
for num in nums:
if num > max1:
max1, max2, max3 = num, max1, max2
elif num > max2:
max2, max3 = num, max2
elif num > max3:
max3 = num
if num < min1:
min1, min2 = num, min1
elif num < min2:
min2 = num
return max(max2*max3, min1*min2) * max1 | https://leetcode.com/problems/maximum-product-of-three-numbers/discuss/356715/Python3-O(N)-and-O(NlogN)-solutions | 7 | Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
3 <= nums.length <= 104
-1000 <= nums[i] <= 1000 | [Python3] O(N) and O(NlogN) solutions | 677 | maximum-product-of-three-numbers | 0.463 | ye15 | Easy | 10,533 | 628 |
k inverse pairs array | class Solution:
# A very good description of the dp solution is at
# https://leetcode.com/problems/k-inverse-pairs-array/solution/
# The code below uses two 1D arrays--dp and tmp--instead if a
# 2D array. tmp replaces dp after each i-iteration.
def kInversePairs(self, n: int, k: int) -> int:
dp, mod = [1]+[0] * k, 1000000007
for i in range(n):
tmp, sm = [], 0
for j in range(k + 1):
sm+= dp[j]
if j-i >= 1: sm-= dp[j-i-1]
sm%= mod
tmp.append(sm)
dp = tmp
#print(dp) # <-- uncomment this line to get a sense of dp from the print output
# try n = 6, k = 4; your answer should be 49.
return dp[k] | https://leetcode.com/problems/k-inverse-pairs-array/discuss/2293304/Python3-oror-dp1D-array-10-lines-w-explanation-oror-TM%3A-9586 | 8 | For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].
Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.
Example 1:
Input: n = 3, k = 0
Output: 1
Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
Example 2:
Input: n = 3, k = 1
Output: 2
Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
Constraints:
1 <= n <= 1000
0 <= k <= 1000 | Python3 || dp,1D array, 10 lines, w/ explanation || T/M: 95%/86% | 657 | k-inverse-pairs-array | 0.429 | warrenruud | Hard | 10,562 | 629 |
course schedule iii | class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
courses.sort(key=lambda c: c[1])
A, curr = [], 0
for dur, ld in courses:
heapq.heappush(A,-dur)
curr += dur
if curr > ld: curr += heapq.heappop(A)
return len(A) | https://leetcode.com/problems/course-schedule-iii/discuss/2185553/Python3-oror-Heapq-oror-Faster-Solution-with-explanation | 28 | There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.
You will start on the 1st day and you cannot take two or more courses simultaneously.
Return the maximum number of courses that you can take.
Example 1:
Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
Output: 3
Explanation:
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
Example 2:
Input: courses = [[1,2]]
Output: 1
Example 3:
Input: courses = [[3,2],[4,3]]
Output: 0
Constraints:
1 <= courses.length <= 104
1 <= durationi, lastDayi <= 104 | Python3 || Heapq || Faster Solution with explanation | 1,000 | course-schedule-iii | 0.402 | bvian | Hard | 10,570 | 630 |
smallest range covering elements from k lists | class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
k=len(nums)
maxx=-float('inf')
ans=[0,float('inf')]
heap=[]
for i in range(k):
heap.append((nums[i][0],i,0))
if nums[i][0]>maxx:maxx=nums[i][0]
heapq.heapify(heap)
while True:
val,row,col= heapq.heappop(heap)
tmp=maxx-val
if tmp<ans[1]-ans[0]:ans=[val,maxx]
elif tmp==ans[1]-ans[0] and val<ans[0]:ans=[val,maxx]
if col+1==len(nums[row]):break
if nums[row][col+1]>maxx:maxx=nums[row][col+1]
heapq.heappush(heap,(nums[row][col+1],row,col+1))
return ans | https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/discuss/1495460/PYTHON-SOLUTION-FASTER-THAN-88.58-OF-PYTHON-SUBMISSIONS | 1 | You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.
Example 1:
Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].
Example 2:
Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]
Constraints:
nums.length == k
1 <= k <= 3500
1 <= nums[i].length <= 50
-105 <= nums[i][j] <= 105
nums[i] is sorted in non-decreasing order. | PYTHON SOLUTION FASTER THAN 88.58% OF PYTHON SUBMISSIONS | 113 | smallest-range-covering-elements-from-k-lists | 0.606 | reaper_27 | Hard | 10,585 | 632 |
sum of square numbers | class Solution:
def judgeSquareSum(self, c: int) -> bool:
low = 0
high = int(sqrt(c))
if high**2 == c:
return True
while low<=high:
x = low **2 + high **2
if x == c:
return True
if x > c:
high-=1
else:
low+=1
return False | https://leetcode.com/problems/sum-of-square-numbers/discuss/2203194/Python3-solution-using-two-pointers | 6 | Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: c = 5
Output: true
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: c = 3
Output: false
Constraints:
0 <= c <= 231 - 1 | 📌 Python3 solution using two pointers | 89 | sum-of-square-numbers | 0.346 | Dark_wolf_jss | Medium | 10,592 | 633 |
exclusive time of functions | class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
helper = lambda log: (int(log[0]), log[1], int(log[2])) # to covert id and time to integer
logs = [helper(log.split(':')) for log in logs] # convert [string] to [(,,)]
ans, s = [0] * n, [] # initialize answer and stack
for (i, status, timestamp) in logs: # for each record
if status == 'start': # if it's start
if s: ans[s[-1][0]] += timestamp - s[-1][1] # if s is not empty, update time spent on previous id (s[-1][0])
s.append([i, timestamp]) # then add to top of stack
else: # if it's end
ans[i] += timestamp - s.pop()[1] + 1 # update time spend on `i`
if s: s[-1][1] = timestamp+1 # if s is not empty, udpate start time of previous id;
return ans | https://leetcode.com/problems/exclusive-time-of-functions/discuss/863039/Python-3-or-Clean-Simple-Stack-or-Explanation | 15 | On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.
Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.
Example 1:
Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3,4]
Explanation:
Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.
Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.
Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.
So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.
Example 2:
Input: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]
Output: [8]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls itself again.
Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.
Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.
So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.
Example 3:
Input: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]
Output: [7,1]
Explanation:
Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.
Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.
Function 0 (initial call) resumes execution then immediately calls function 1.
Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.
Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time.
So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.
Constraints:
1 <= n <= 100
1 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
No two start events will happen at the same timestamp.
No two end events will happen at the same timestamp.
Each function has an "end" log for each "start" log. | Python 3 | Clean, Simple Stack | Explanation | 1,100 | exclusive-time-of-functions | 0.611 | idontknoooo | Medium | 10,614 | 636 |
average of levels in binary tree | class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:
# Quick response for empty tree
return []
traversal_q = [root]
average = []
while traversal_q:
# compute current level average
cur_avg = sum( (node.val for node in traversal_q if node) ) / len(traversal_q)
# add to result
average.append( cur_avg )
# update next level queue
next_level_q = [ child for node in traversal_q for child in (node.left, node.right) if child ]
# update traversal queue as next level's
traversal_q = next_level_q
return average | https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/492462/PythonGo-O(n)-by-level-order-traversal.-w-Explanation | 10 | Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].
Example 2:
Input: root = [3,9,20,15,7]
Output: [3.00000,14.50000,11.00000]
Constraints:
The number of nodes in the tree is in the range [1, 104].
-231 <= Node.val <= 231 - 1 | Python/Go O(n) by level-order-traversal. [ w/ Explanation ] | 1,300 | average-of-levels-in-binary-tree | 0.717 | brianchiang_tw | Easy | 10,629 | 637 |
shopping offers | class Solution:
def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:
n = len(price)
@lru_cache(maxsize=None)
def dfs(needs):
ans = sum([i*j for i, j in zip(price, needs)])
cur = sys.maxsize
for s in special:
new_needs, ok = [], True
for i in range(n):
need, give = needs[i], s[i]
if need < give: # if over purchase, ignore this combination
ok = False
break
new_needs.append(need-give)
if ok: cur = min(cur, dfs(tuple(new_needs)) + s[-1])
return min(ans, cur)
return dfs(tuple(needs)) | https://leetcode.com/problems/shopping-offers/discuss/783072/Python-3-DFS-%2B-Memoization-(lru_cache) | 2 | In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.
You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
Example 1:
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
Example 2:
Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
Explanation: The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
Constraints:
n == price.length == needs.length
1 <= n <= 6
0 <= price[i], needs[i] <= 10
1 <= special.length <= 100
special[i].length == n + 1
0 <= special[i][j] <= 50 | Python 3 DFS + Memoization (lru_cache) | 292 | shopping-offers | 0.541 | idontknoooo | Medium | 10,657 | 638 |
decode ways ii | class Solution:
def numDecodings(self, s: str) -> int:
non_zero = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
first_incl, second_incl = 1, 0
first_excl, second_excl = 0, 0
if s[0] in non_zero:
second_incl = 1
if s[0] == '*':
second_incl = 9
for i in range(1, len(s)):
new_incl, new_excl = 0, 0
if s[i] == '*':
new_incl = 9 * (second_incl + second_excl)
if s[i-1] == '1':
# number is of type (1, *)
new_excl = 9 * (first_incl + first_excl)
elif s[i-1] == '2':
# number is of type (2, *)
new_excl = 6 * (first_incl + first_excl)
elif s[i-1] == '*':
# number is of type (*, *)
new_excl = 15 * (first_incl + first_excl)
else:
if s[i] in non_zero:
new_incl = second_incl + second_excl
if s[i-1] == '*':
# number is of type (*,digit)
if int(s[i]) <= 6:
new_excl = 2 * (first_excl + first_incl)
else:
new_excl = first_incl + first_excl
else:
# number is of type (digit,digit)
val = int(s[i-1:i+1])
if 10 <= val <= 26:
new_excl = first_incl + first_excl
else:
new_excl = 0
first_incl, first_excl = second_incl, second_excl
second_incl, second_excl = new_incl, new_excl
return (second_incl + second_excl) % (10**9 + 7) | https://leetcode.com/problems/decode-ways-ii/discuss/2509952/Best-Python3-implementation-(Top-93.7)-oror-Clean-code | 0 | A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: s = "*"
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "*".
Example 2:
Input: s = "1*"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Example 3:
Input: s = "2*"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
Constraints:
1 <= s.length <= 105
s[i] is a digit or '*'. | ✔️ Best Python3 implementation (Top 93.7%) || Clean code | 25 | decode-ways-ii | 0.304 | UpperNoot | Hard | 10,662 | 639 |
solve the equation | class Solution:
def solveEquation(self, equation: str) -> str:
def helper(l,r): # left inclusive and right exclusive
constant = unknown = 0
sign,val = 1,''
while l < r:
if equation[l].isnumeric():
val += equation[l]
elif equation[l] == 'x':
unknown += sign*int(val or '1') # in case the coefficient is 1
val = ''
else: # meet a +/-
if val:
constant += sign*int(val)
sign = 1 if equation[l]=='+' else -1
val = ''
l += 1
if val: # if the last digit is a number
constant += sign*i
return constant,unknown
mid = equation.find('=')
constant1,unknown1 = helper(0,mid)
constant2,unknown2 = helper(mid+1,len(equation))
const,var = constant2-constant1,unknown1-unknown2
# print(a,b)
if var == 0:
if const == 0: return "Infinite solutions"
else: return "No solution"
else: return 'x={}'.format(const//var) | https://leetcode.com/problems/solve-the-equation/discuss/837106/Python-or-No-Regex-or-Simple-Logic-or-Probably-better-for-interviews-or-Commented | 6 | Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.
Example 1:
Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: equation = "x=x"
Output: "Infinite solutions"
Example 3:
Input: equation = "2x=x"
Output: "x=0"
Constraints:
3 <= equation.length <= 1000
equation has exactly one '='.
equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'. | Python | No Regex | Simple Logic | Probably better for interviews | Commented | 299 | solve-the-equation | 0.434 | since2020 | Medium | 10,664 | 640 |
maximum average subarray i | class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
M = d = 0
for i in range(len(nums)-k):
d += nums[i+k] - nums[i]
if d > M: M = d
return (sum(nums[:k])+M)/k
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/maximum-average-subarray-i/discuss/336428/Solution-in-Python-3-(beats-100) | 11 | You are given an integer array nums consisting of n elements, and an integer k.
Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.
Example 1:
Input: nums = [1,12,-5,-6,50,3], k = 4
Output: 12.75000
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
Example 2:
Input: nums = [5], k = 1
Output: 5.00000
Constraints:
n == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104 | Solution in Python 3 (beats 100%) | 2,100 | maximum-average-subarray-i | 0.438 | junaidmansuri | Easy | 10,672 | 643 |
set mismatch | class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
c=Counter(nums)
l=[0,0]
for i in range(1,len(nums)+1):
if c[i]==2:
l[0]=i
if c[i]==0:
l[1]=i
return l | https://leetcode.com/problems/set-mismatch/discuss/2733971/Easy-Python-Solution | 14 | You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2,3]
Example 2:
Input: nums = [1,1]
Output: [1,2]
Constraints:
2 <= nums.length <= 104
1 <= nums[i] <= 104 | Easy Python Solution | 966 | set-mismatch | 0.43 | Vistrit | Easy | 10,705 | 645 |
maximum length of pair chain | class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
pairs.sort()
rt = 1
l = pairs[0]
for r in range(1,len(pairs)):
if l[1] < pairs[r][0]:
rt += 1
l = pairs[r]
elif pairs[r][1]<l[1]:
l = pairs[r]
return rt | https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1564508/Fast-O(NlogN)-and-simple-Python-3-solution | 2 | You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
You do not need to use up all the given intervals. You can select pairs in any order.
Example 1:
Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4].
Example 2:
Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].
Constraints:
n == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti <= 1000 | Fast O(NlogN) and simple Python 3 solution | 156 | maximum-length-of-pair-chain | 0.564 | cyrille-k | Medium | 10,764 | 646 |
palindromic substrings | class Solution:
def countSubstrings(self, s: str) -> int:
L, r = len(s), 0
for i in range(L):
for a,b in [(i,i),(i,i+1)]:
while a >= 0 and b < L and s[a] == s[b]: a -= 1; b += 1
r += (b-a)//2
return r
- Junaid Mansuri
(LeetCode ID)@hotmail.com | https://leetcode.com/problems/palindromic-substrings/discuss/392119/Solution-in-Python-3-(beats-~94)-(six-lines)-(With-Detaiiled-Explanation) | 67 | Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Constraints:
1 <= s.length <= 1000
s consists of lowercase English letters. | Solution in Python 3 (beats ~94%) (six lines) (With Detaiiled Explanation) | 8,100 | palindromic-substrings | 0.664 | junaidmansuri | Medium | 10,781 | 647 |
replace words | class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
d = {w:len(w) for w in dictionary}
mini, maxi = min(d.values()), max(d.values())
wd = sentence.split()
rt = []
for s in wd:
c = s
for k in range(mini,min(maxi,len(s))+1):
ss = s[:k]
if ss in d:
c = ss
break
rt.append(c)
return " ".join(rt) | https://leetcode.com/problems/replace-words/discuss/1576514/Fast-solution-beats-97-submissions | 3 | In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "help" is followed by the successor word "ful", we can form a new word "helpful".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Constraints:
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i] consists of only lower-case letters.
1 <= sentence.length <= 106
sentence consists of only lower-case letters and spaces.
The number of words in sentence is in the range [1, 1000]
The length of each word in sentence is in the range [1, 1000]
Every two consecutive words in sentence will be separated by exactly one space.
sentence does not have leading or trailing spaces. | Fast solution beats 97% submissions | 118 | replace-words | 0.627 | cyrille-k | Medium | 10,832 | 648 |
dota2 senate | class Solution:
def predictPartyVictory(self, senate: str) -> str:
n = len(senate)
s, banned = set(), [False] * n
ban_d = ban_r = 0
while len(s) != 1:
s = set()
for i, p in enumerate(senate):
if banned[i]: continue
if p == 'R':
if ban_r > 0: # current R being banned
ban_r -= 1
banned[i] = True
else: # if current R is valid, it will ban D
ban_d += 1
s.add('R')
else:
if ban_d > 0: # current D being banned
ban_d -= 1
banned[i] = True
else: # if current D is valid, it will ban R
ban_r += 1
s.add('D')
return 'Radiant' if s.pop() == 'R' else 'Dire' | https://leetcode.com/problems/dota2-senate/discuss/845912/Python-3-or-Greedy-Simulation-or-Explanantion | 8 | In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant" or "Dire".
Example 1:
Input: senate = "RD"
Output: "Radiant"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: senate = "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in round 1.
And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Constraints:
n == senate.length
1 <= n <= 104
senate[i] is either 'R' or 'D'. | Python 3 | Greedy, Simulation | Explanantion | 690 | dota2-senate | 0.404 | idontknoooo | Medium | 10,852 | 649 |
2 keys keyboard | class Solution:
def minSteps(self, n: int) -> int:
dp = [float('inf')] * (n+1)
## Intialize a dp array to store the solutions of sub problems i.e. number of steps needed
dp[1] = 0
## Intially first element of dp array with 0 as 'A' is already present and we haven't consumed any steps yet.
## As the value of n is from [1,3000] and initally 'A' is already present so we don't need to bother about the dp[0]
divisors = []
## This is to store the divisors of N
for i in range(1, n//2 + 1):
if n % i == 0:
divisors.append(i)
## We have stored all the divisors. For n = 10, divisors = [1,2,5]
for j in divisors:
dp[j] += 1
##To copy the current number of A's, we add one step
for i in range(j+1, n+1):
if i % j == 0:
## We can only form the string length which is divisible by j
dp[i] = min(dp[i], dp[i-j] + 1)
## Compare with previous number of steps and update with the minimum
return dp[-1]
#Return last value of dp i.e. N | https://leetcode.com/problems/2-keys-keyboard/discuss/727856/Python3-Dynamic-Programming-Beginners | 12 | There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.
Example 1:
Input: n = 3
Output: 3
Explanation: Initially, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
Example 2:
Input: n = 1
Output: 0
Constraints:
1 <= n <= 1000 | Python3 Dynamic Programming - Beginners | 1,000 | 2-keys-keyboard | 0.532 | ayushjain94 | Medium | 10,857 | 650 |
find duplicate subtrees | class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
seen = collections.defaultdict(int)
res = []
def helper(node):
if not node:
return
sub = tuple([helper(node.left), node.val, helper(node.right)])
if sub in seen and seen[sub] == 1:
res.append(node)
seen[sub] += 1
return sub
helper(root)
return res | https://leetcode.com/problems/find-duplicate-subtrees/discuss/1178526/Easy-%2B-Clean-%2B-Straightforward-Python-Recursive | 15 | Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:
Input: root = [2,1,1]
Output: [[1]]
Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
Constraints:
The number of the nodes in the tree will be in the range [1, 5000]
-200 <= Node.val <= 200 | Easy + Clean + Straightforward Python Recursive | 1,100 | find-duplicate-subtrees | 0.565 | Pythagoras_the_3rd | Medium | 10,880 | 652 |
two sum iv input is a bst | class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
queue = [root]
unique_set = set()
while len(queue) > 0:
current = queue.pop()
if k - current.val in unique_set: return True
unique_set.add(current.val)
if current.left: queue.append(current.left)
if current.right: queue.append(current.right)
return False | https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1011974/BFS-two-pointers-and-recursive | 2 | Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 104].
-104 <= Node.val <= 104
root is guaranteed to be a valid binary search tree.
-105 <= k <= 105 | BFS, two pointers and recursive | 213 | two-sum-iv-input-is-a-bst | 0.61 | borodayev | Easy | 10,886 | 653 |
maximum binary tree | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
# base case
if not nums:
return None
max_val = max(nums)
max_idx = nums.index(max_val)
root = TreeNode(max_val)
root.left = self.constructMaximumBinaryTree(nums[:max_idx])
root.right = self.constructMaximumBinaryTree(nums[max_idx+1:])
return root | https://leetcode.com/problems/maximum-binary-tree/discuss/944324/simple-python3-solution-with-recursion | 2 | You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:
Create a root node whose value is the maximum value in nums.
Recursively build the left subtree on the subarray prefix to the left of the maximum value.
Recursively build the right subtree on the subarray suffix to the right of the maximum value.
Return the maximum binary tree built from nums.
Example 1:
Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
Explanation: The recursive calls are as follow:
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
- The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
- Empty array, so no child.
- The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
Example 2:
Input: nums = [3,2,1]
Output: [3,null,2,null,1]
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
All integers in nums are unique. | simple python3 solution with recursion | 100 | maximum-binary-tree | 0.845 | Gushen88 | Medium | 10,922 | 654 |
print binary tree | class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
height = 0
def dfs(node, h): # Find height
nonlocal height
height = max(height, h)
if node.left:
dfs(node.left, h+1)
if node.right:
dfs(node.right, h+1)
dfs(root, 0)
n = 2 ** (height + 1) - 1 # Get `n`
offset = (n - 1) // 2 # Column for root node
ans = [[''] * n for _ in range(height + 1)]
q = [(root, 0, offset)]
for i in range(height+1): # BFS
tmp_q = []
while q:
cur, r, c = q.pop()
ans[r][c] = str(cur.val)
if cur.left:
tmp_q.append((cur.left, r+1, c-2 ** (height - r - 1)))
if cur.right:
tmp_q.append((cur.right, r+1, c+2 ** (height - r - 1)))
q = tmp_q
return ans | https://leetcode.com/problems/print-binary-tree/discuss/1384379/Python-3-or-DFS-%2B-BFS-(Level-order-traversal)-or-Explanation | 2 | Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns n should be equal to 2height+1 - 1.
Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
For each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
Continue this process until all the nodes in the tree have been placed.
Any empty cells should contain the empty string "".
Return the constructed matrix res.
Example 1:
Input: root = [1,2]
Output:
[["","1",""],
["2","",""]]
Example 2:
Input: root = [1,2,3,null,4]
Output:
[["","","","1","","",""],
["","2","","","","3",""],
["","","4","","","",""]]
Constraints:
The number of nodes in the tree is in the range [1, 210].
-99 <= Node.val <= 99
The depth of the tree will be in the range [1, 10]. | Python 3 | DFS + BFS (Level-order-traversal) | Explanation | 256 | print-binary-tree | 0.614 | idontknoooo | Medium | 10,937 | 655 |
robot return to origin | class Solution:
def judgeCircle(self, moves: str) -> bool:
return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/robot-return-to-origin/discuss/342078/Solution-in-Python-3-(~beats-99)-(-one-line-) | 11 | There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).
Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.
Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
Example 1:
Input: moves = "UD"
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
Example 2:
Input: moves = "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
Constraints:
1 <= moves.length <= 2 * 104
moves only contains the characters 'U', 'D', 'L' and 'R'. | Solution in Python 3 (~beats 99%) ( one line ) | 1,600 | robot-return-to-origin | 0.753 | junaidmansuri | Easy | 10,943 | 657 |
find k closest elements | class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# first binary search where the value 'x' should be in the sorted array
n = len(arr)
low, high = 0, n - 1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == x:
start, end = mid - 1, mid + 1
k -= 1
break
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
if low > high:
start = high
end = low
# after we found where 'x' should be in the sorted array we expand to the left and to the right to find the next values until k (using two pointers start, end)
while k > 0:
if start == -1:
end += 1
elif end == n:
start -= 1
else:
if abs(arr[start] - x) <= abs(arr[end] - x):
start -= 1
else:
end += 1
k -= 1
return arr[start + 1:end] | https://leetcode.com/problems/find-k-closest-elements/discuss/1310805/Python-Solution | 13 | Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr is sorted in ascending order.
-104 <= arr[i], x <= 104 | Python Solution | 1,000 | find-k-closest-elements | 0.468 | mariandanaila01 | Medium | 10,973 | 658 |
split array into consecutive subsequences | class Solution:
def isPossible(self, nums: List[int]) -> bool:
len1 = len2 = absorber = 0
prev_num = nums[0] - 1
for streak_len, streak_num in Solution.get_streaks(nums):
if streak_num == prev_num + 1:
spillage = streak_len - len1 - len2
if spillage < 0:
return False
absorber = min(absorber, spillage)
len1, len2, absorber = spillage - absorber, len1, absorber + len2
else:
if len1 or len2:
return False
absorber = 0
prev_num = streak_num
return len1 == len2 == 0
@staticmethod
def get_streaks(nums: List[int]):
streak_num = nums[0]
streak_len = 0
for num in nums:
if num == streak_num:
streak_len += 1
else:
yield streak_len, streak_num
streak_num = num
streak_len = 1
yield streak_len, streak_num | https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2446738/Python-524ms-98.3-Faster-Multiple-solutions-94-memory-efficient | 44 | You are given an integer array nums that is sorted in non-decreasing order.
Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:
Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
All subsequences have a length of 3 or more.
Return true if you can split nums according to the above conditions, or false otherwise.
A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).
Example 1:
Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5
Example 2:
Input: nums = [1,2,3,3,4,4,5,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5
Example 3:
Input: nums = [1,2,3,4,4,5]
Output: false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
nums is sorted in non-decreasing order. | Python 524ms 98.3% Faster Multiple solutions 94% memory efficient | 2,900 | split-array-into-consecutive-subsequences | 0.506 | anuvabtest | Medium | 11,024 | 659 |
image smoother | class Solution:
def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:
row, col = len(M), len(M[0])
res = [[0]*col for i in range(row)]
dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]
for i in range(row):
for j in range(col):
temp = [M[i+m][j+n] for m,n in dirs if 0<=i+m<row and 0<=j+n<col]
res[i][j] = sum(temp)//len(temp)
return res | https://leetcode.com/problems/image-smoother/discuss/454951/Python3-simple-solution | 12 | An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.
Example 1:
Input: img = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Example 2:
Input: img = [[100,200,100],[200,50,200],[100,200,100]]
Output: [[137,141,137],[141,138,141],[137,141,137]]
Explanation:
For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137
For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141
For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138
Constraints:
m == img.length
n == img[i].length
1 <= m, n <= 200
0 <= img[i][j] <= 255 | Python3 simple solution | 807 | image-smoother | 0.551 | jb07 | Easy | 11,038 | 661 |
maximum width of binary tree | class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
Q = collections.deque()
Q.append((root,0))
ans = 0
while Q:
length = len(Q)
_, start = Q[0]
for i in range(length):
node, index = Q.popleft()
if node.left:
Q.append((node.left, 2*index))
if node.right:
Q.append((node.right, 2*index+1))
ans = max(ans, index-start+1)
return ans | https://leetcode.com/problems/maximum-width-of-binary-tree/discuss/688259/Python-solution-O(N)-BFS-traversal | 4 | Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is guaranteed that the answer will in the range of a 32-bit signed integer.
Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
Example 2:
Input: root = [1,3,2,5,null,null,9,6,null,7]
Output: 7
Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
Example 3:
Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width exists in the second level with length 2 (3,2).
Constraints:
The number of nodes in the tree is in the range [1, 3000].
-100 <= Node.val <= 100 | Python solution - O(N) BFS traversal | 489 | maximum-width-of-binary-tree | 0.407 | realslimshady | Medium | 11,045 | 662 |
strange printer | class Solution:
def strangePrinter(self, s: str) -> int:
s = "".join(ch for i, ch in enumerate(s) if i == 0 or s[i-1] != ch)
@cache
def fn(lo, hi):
"""Return min ops to print s[lo:hi]."""
if lo == hi: return 0
ans = 1 + fn(lo+1, hi)
for mid in range(lo+1, hi):
if s[lo] == s[mid]:
ans = min(ans, fn(lo, mid) + fn(mid+1, hi))
return ans
return fn(0, len(s)) | https://leetcode.com/problems/strange-printer/discuss/1492420/Python3-dp | 3 | There is a strange printer with the following two special properties:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".
Example 2:
Input: s = "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters. | [Python3] dp | 378 | strange-printer | 0.468 | ye15 | Hard | 11,066 | 664 |
non decreasing array | class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
cnt_violations=0
for i in range(1, len(nums)):
if nums[i]<nums[i-1]:
if cnt_violations==1:
return False
cnt_violations+=1
if i>=2 and nums[i-2]>nums[i]:
nums[i]=nums[i-1]
return True | https://leetcode.com/problems/non-decreasing-array/discuss/2193030/Python-Easy-Greedy-w-explanation-O(1)-space | 52 | Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
Constraints:
n == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105 | Python Easy Greedy w/ explanation - O(1) space | 2,800 | non-decreasing-array | 0.242 | constantine786 | Medium | 11,067 | 665 |
beautiful arrangement ii | class Solution:
def constructArray(self, n: int, k: int) -> List[int]:
lo, hi = 1, n
ans = []
while lo <= hi:
if k&1:
ans.append(lo)
lo += 1
else:
ans.append(hi)
hi -= 1
if k > 1: k -= 1
return ans | https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1158414/Python3-greedy | 1 | Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
Return the list answer. If there multiple valid answers, return any of them.
Example 1:
Input: n = 3, k = 1
Output: [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
Example 2:
Input: n = 3, k = 2
Output: [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
Constraints:
1 <= k < n <= 104 | [Python3] greedy | 57 | beautiful-arrangement-ii | 0.597 | ye15 | Medium | 11,096 | 667 |
kth smallest number in multiplication table | class Solution:
def findKthNumber(self, m: int, n: int, k: int) -> int:
# special cases: k == 1, k == m * n
if k == 1:
return 1
if k == m * n:
return m * n
# make the matrix a tall one - height >= width
# because later I will loop along the width. This will reduce the time
if n >= m:
m, n = n, m
# set the left, right boundaries and the ranks (the largest ranks for the values)
# e.g. in a 3 * 3 table, number 2 shows up twice, taking up ranks from 2 to 3
# so the largest rank here is 3 for number 2.
left = 1
# left_rank = 1
right = m * n
# right_rank = m * n
# binary search loop
while right - left > 1:
mid = (left + right) // 2
# mid_rank is the largest rank of the number
mid_rank = 0
# find the number of columns whose maximum < mid
# (mid - 1) is to prevent counting the column with maximum == mid.
num_cols = (mid - 1) // m
residual = mid - num_cols * m
mid_rank += num_cols * m
# flag to track if mid is a valid value in the table
flag = 0
for i in range(num_cols + 1, n + 1):
if i == mid:
mid_rank += 1
break
else:
mid_rank += mid // i
if mid % i == 0:
flag = 1
if flag == 1:
# mid is a valid number in the table
# if mid_rank == k: mid's largest rank is k and mid is the kth number
# if mid_rank < k: kth number > mid, so left = mid
# if mid_rank > k: mid's largest rank > k but mid still can be the kth number but kth number can be no larger than mid, so right = mid
if mid_rank == k:
return mid
elif mid_rank > k:
right = mid
else:
left = mid
else:
# mid is not a valid number in the table
# if mid_rank == k, it means there are k values in the table smaller than mid
# so there is a number smaller than mid ranking the kth.
# mid_rank > k or mid_rank < k: similar operation as above
if mid_rank >= k:
right = mid
else:
left = mid
# In case the while loop breaks out without returning
# let's assume when right - left == 2 and mid == left + 1. The solution must be among the three.
# right with its largest rank > k
# left with its largest rank < k
# Scenario 1. if mid is a valid number in the table
## 1a. if mid_rank < k: right has its rank from mid_rank + 1 (<= k) till right_rank (> k)
## 1b. if mid_rank > k: right = mid. Now right (== mid) has its rank from left_rank + 1 (<= k) till mid_rank (> k)
## in both cases, right is the solution
# Scenario 2. if mid is not a valid number in the table then we can just ignore mid and imply the solution is right.
## But step by step, as mid is not in the table, mid_rank == left_rank, so left = mid.
## So right has its rank from mid_rank + 1 (i.e. left_rank + 1) (<= k) till right_rank (> k). right is the solution.
return right | https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/1581461/Binary-Search-Solution-with-detailed-explanation-beating-98-in-time-and-86-in-space | 1 | Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).
Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.
Example 1:
Input: m = 3, n = 3, k = 5
Output: 3
Explanation: The 5th smallest number is 3.
Example 2:
Input: m = 2, n = 3, k = 6
Output: 6
Explanation: The 6th smallest number is 6.
Constraints:
1 <= m, n <= 3 * 104
1 <= k <= m * n | Binary Search Solution with detailed explanation, beating 98% in time and 86% in space | 83 | kth-smallest-number-in-multiplication-table | 0.515 | leonine9 | Hard | 11,104 | 668 |
trim a binary search tree | class Solution:
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
if not root: return root
if root.val < low: return self.trimBST(root.right, low, high)
if root.val > high: return self.trimBST(root.left, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root | https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1046286/Python.-faster-than-98.05.-recursive.-6-lines.-DFS. | 24 | Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]
Constraints:
The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 104
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 104 | Python. faster than 98.05%. recursive. 6 lines. DFS. | 1,000 | trim-a-binary-search-tree | 0.663 | m-d-f | Medium | 11,107 | 669 |
maximum swap | class Solution:
def maximumSwap(self, num: int) -> int:
s = list(str(num))
n = len(s)
for i in range(n-1): # find index where s[i] < s[i+1], meaning a chance to flip
if s[i] < s[i+1]: break
else: return num # if nothing find, return num
max_idx, max_val = i+1, s[i+1] # keep going right, find the maximum value index
for j in range(i+1, n):
if max_val <= s[j]: max_idx, max_val = j, s[j]
left_idx = i # going right from i, find most left value that is less than max_val
for j in range(i, -1, -1):
if s[j] < max_val: left_idx = j
s[max_idx], s[left_idx] = s[left_idx], s[max_idx] # swap maximum after i and most left less than max
return int(''.join(s)) # re-create the integer | https://leetcode.com/problems/maximum-swap/discuss/846837/Python-3-or-Greedy-Math-or-Explanations | 43 | You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
Example 1:
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = 9973
Output: 9973
Explanation: No swap.
Constraints:
0 <= num <= 108 | Python 3 | Greedy, Math | Explanations | 3,600 | maximum-swap | 0.479 | idontknoooo | Medium | 11,137 | 670 |
second minimum node in a binary tree | class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
def inorderTraversal(root):
if not root:
return []
else:
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
r = set(inorderTraversal(root))
if len(r)>=2:
return sorted(list(r))[1]
else:
return -1 | https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/405721/Beats-100-Python-Solution | 2 | Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
Constraints:
The number of nodes in the tree is in the range [1, 25].
1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val) for each internal node of the tree. | Beats 100% Python Solution | 424 | second-minimum-node-in-a-binary-tree | 0.44 | saffi | Easy | 11,162 | 671 |
bulb switcher ii | class Solution:
def flipLights(self, n: int, m: int) -> int:
def fn(n, m):
"""Return number of different status."""
if m * n == 0: return 1
return fn(n-1, m-1) + fn(n-1, m)
return fn(min(n, 3), min(m, 3)) | https://leetcode.com/problems/bulb-switcher-ii/discuss/897976/Python3-O(1) | 4 | There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:
Button 1: Flips the status of all the bulbs.
Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...).
Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...).
Button 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...).
You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.
Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.
Example 1:
Input: n = 1, presses = 1
Output: 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
Example 2:
Input: n = 2, presses = 1
Output: 3
Explanation: Status can be:
- [off, off] by pressing button 1
- [on, off] by pressing button 2
- [off, on] by pressing button 3
Example 3:
Input: n = 3, presses = 1
Output: 4
Explanation: Status can be:
- [off, off, off] by pressing button 1
- [off, on, off] by pressing button 2
- [on, off, on] by pressing button 3
- [off, on, on] by pressing button 4
Constraints:
1 <= n <= 1000
0 <= presses <= 1000 | [Python3] O(1) | 462 | bulb-switcher-ii | 0.51 | ye15 | Medium | 11,168 | 672 |
number of longest increasing subsequence | class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
dp = [1] * len(nums)
ct = [1] * len(nums)
maxLen, maxCt = 0, 0
# same as the LIS code, iterate
# over all the elements once and then
# from 0 -> i again to compute LISs
for i in range(len(nums)):
for j in range(i):
# If it's a valid LIS
if nums[i] > nums[j]:
# and if the length
# of LIS at i wrt j
# is going to be increased
# update the length dp
# and since this is just one
# continous LIS, count of i
# will become same as that of j
if dp[j]+1 > dp[i]:
dp[i] = dp[j] + 1
ct[i] = ct[j]
# if on the other hand, the
# length of the LIS at i becomes
# the same as it was, it means
# there's another LIS of this same
# length, in this case, add the LIS
# count of j to i, because the current
# LIS count at i consists of ways to get
# to this LIS from another path, and now
# we're at a new path, so sum thse up
# there's no point
# in updating the length LIS here.
elif dp[i] == dp[j] + 1:
ct[i] += ct[j]
# at any point, keep track
# of the maxLen and maxCt
# we'll use it to compute our result
if dp[i] > maxLen:
maxLen = dp[i]
# now, we have the maxLength
# of the given nums, we can iterate
# over all 3 arrays (hypothetically)
# and just add up the count of all those
# LIS which are the longest (maxLen)
# and that's the result
for i in range(len(nums)):
if maxLen == dp[i]:
maxCt += ct[i]
return maxCt | https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/1881188/Python-DP-solution-explained | 2 | Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
Constraints:
1 <= nums.length <= 2000
-106 <= nums[i] <= 106 | [Python] DP solution explained | 182 | number-of-longest-increasing-subsequence | 0.423 | buccatini | Medium | 11,171 | 673 |
longest continuous increasing subsequence | class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
counter=1
temp=1
for i in range(0,len(nums)-1):
if nums[i]<nums[i+1]:
temp+=1
if temp>counter:
counter=temp
else:
temp=1
return counter | https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2445685/Two-python-solutions-using-dp-and-a-straightforward-soln | 3 | Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
Example 1:
Input: nums = [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly
increasing.
Constraints:
1 <= nums.length <= 104
-109 <= nums[i] <= 109 | Two python solutions using dp and a straightforward soln | 182 | longest-continuous-increasing-subsequence | 0.491 | guneet100 | Easy | 11,178 | 674 |
cut off trees for golf event | class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
forest.append([0] * len(forest[0]))
for row in forest: row.append(0)
def bfs(end, start):
if end == start: return 0
visited, queue = set(), {start}
visited.add(start)
step = 0
while queue:
s = set()
step += 1
for p in queue:
for dr, dc in ((-1, 0), (1, 0), (0, 1), (0, -1)):
r, c = p[0] + dr, p[1] + dc
if not forest[r][c] or (r, c) in visited: continue
if (r, c) == end: return step
visited.add((r, c))
s.add((r, c))
queue = s
trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1]
# check
queue = [(0, 0)]
reached = set()
reached.add((0, 0))
while queue:
r, c = queue.pop()
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
row, col = r + dr, c + dc
if forest[row][col] and (row, col) not in reached:
queue.append((row, col))
reached.add((row,col))
if not all([(i, j) in reached for (height, i, j) in trees]): return -1
trees.sort()
return sum([bfs((I,J),(i,j)) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)]) | https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/1204000/Python-normal-and-priority-BFS-faster-than-99-and-faster-than-77 | 4 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:
0 means the cell cannot be walked through.
1 represents an empty cell that can be walked through.
A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.
In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.
You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).
Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.
Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.
Example 1:
Input: forest = [[1,2,3],[0,0,4],[7,6,5]]
Output: 6
Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
Example 2:
Input: forest = [[1,2,3],[0,0,0],[7,6,5]]
Output: -1
Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.
Example 3:
Input: forest = [[2,3,4],[0,0,5],[8,7,6]]
Output: 6
Explanation: You can follow the same path as Example 1 to cut off all the trees.
Note that you can cut off the first tree at (0, 0) before making any steps.
Constraints:
m == forest.length
n == forest[i].length
1 <= m, n <= 50
0 <= forest[i][j] <= 109
Heights of all trees are distinct. | Python, normal and priority BFS, faster than 99% and faster than 77% | 681 | cut-off-trees-for-golf-event | 0.342 | dustlihy | Hard | 11,200 | 675 |
valid parenthesis string | class Solution:
def checkValidString(self, s: str) -> bool:
# store the indices of '('
stk = []
# store the indices of '*'
star = []
for idx, char in enumerate(s):
if char == '(':
stk.append( idx )
elif char == ')':
if stk:
stk.pop()
elif star:
star.pop()
else:
return False
else:
star.append( idx )
# cancel ( and * with valid positions, i.e., '(' must be on the left hand side of '*'
while stk and star:
if stk[-1] > star[-1]:
return False
stk.pop()
star.pop()
# Accept when stack is empty, which means all braces are paired
# Reject, otherwise.
return len(stk) == 0 | https://leetcode.com/problems/valid-parenthesis-string/discuss/584655/Python-O(n)-by-stack.-85%2B-w-Comment | 23 | Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "(*)"
Output: true
Example 3:
Input: s = "(*))"
Output: true
Constraints:
1 <= s.length <= 100
s[i] is '(', ')' or '*'. | Python O(n) by stack. 85%+ [w/ Comment] | 813 | valid-parenthesis-string | 0.339 | brianchiang_tw | Medium | 11,206 | 678 |
valid palindrome ii | class Solution:
def validPalindrome(self, s: str) -> bool:
p1=0
p2=len(s)-1
while p1<=p2:
if s[p1]!=s[p2]:
string1=s[:p1]+s[p1+1:]
string2=s[:p2]+s[p2+1:]
return string1==string1[::-1] or string2==string2[::-1]
p1+=1
p2-=1
return True | https://leetcode.com/problems/valid-palindrome-ii/discuss/1409641/Python-3-oror-Two-Pointer-Approach-oror-Self-Understandable | 85 | Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters. | Python 3 || Two Pointer Approach || Self-Understandable | 5,500 | valid-palindrome-ii | 0.393 | bug_buster | Easy | 11,223 | 680 |