title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python||Greedy||Fast||Easy to undestand|| With explanations
longest-binary-subsequence-less-than-or-equal-to-k
0
1
1. As the answer is a **subsequence** then we understand that we MUST get ALL zeroes from string to maximize the answer(it depends on length)\n2. Another greedy thing to consider is position of 1 in a binary representation and the greedy thing -> we must decrease the k starting by least position of 1\n\n```\nclass Solu...
6
You are given a binary string `s` and a positive integer `k`. Return _the length of the **longest** subsequence of_ `s` _that makes up a **binary** number less than or equal to_ `k`. Note: * The subsequence can contain **leading zeroes**. * The empty string is considered to be equal to `0`. * A **subsequence**...
Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not.
✅Python || Easy Approach || beats 90.00% Runtime
longest-binary-subsequence-less-than-or-equal-to-k
0
1
```\nclass Solution:\n def longestSubsequence(self, s: str, k: int) -> int:\n \n ans = 0\n n = len(s)\n \n if k > int(s, 2):\n return n\n \n for i in range(n):\n if int(s[n - 1 - i:], 2) > k:\n curr = i\n break\n ...
2
You are given a binary string `s` and a positive integer `k`. Return _the length of the **longest** subsequence of_ `s` _that makes up a **binary** number less than or equal to_ `k`. Note: * The subsequence can contain **leading zeroes**. * The empty string is considered to be equal to `0`. * A **subsequence**...
Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not.
Simple Python Solution with explanation 🔥
selling-pieces-of-wood
0
1
# Approach\n\n* Price Map -> \n\n Since prices is a list, it is costly to fetch the price of a specific height `h` and width `w`. \n Lets convert it to a map: `priceMap` where the first order key is height and second order key is width.\n\n ```\n height: h1\n width: w1\n price: priceMap[h1][w1]\n `...
3
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
Python bottom up DP faster than 99%
selling-pieces-of-wood
0
1
```\nclass Solution:\n def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n dp = [[0]*(n+1) for _ in range(m+1)]\n for h, w, p in prices:\n dp[h][w] = p\n for i in range(1, m+1):\n for j in range(1, n+1):\n v = max(dp[k][j] + dp[i - k][j] ...
1
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
93% Time and Memory | Commented and Explained
selling-pieces-of-wood
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a dp problem, where we need to build a cut profit chart to show profit attainable at a specific cutting combination which drives towards the profit of cutting the whole board or as much as possible. If printed, can show up to wher...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
py3 sol
selling-pieces-of-wood
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen facing an optimization problem like this, where we need to find the maximum value obtainable through a series of decisions (cuts, in this case), dynamic programming (DP) is a good fit. The problem has an optimal substructure, which m...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
python3 solution for me bp
selling-pieces-of-wood
0
1
# Code\n```\nclass Solution:\n def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n prices_dict = {(h,w): p for h,w,p in prices}\n\n dp = {}\n\n for i in range(1, m+1):\n for j in range(1, n+1):\n val = dp.get((i,j) , prices_dict.get((i,j), 0))\n ...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
Python 90% time and 57% space
selling-pieces-of-wood
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
Python, short and clean, memo+DP
selling-pieces-of-wood
0
1
# Intuition\nMain observation: we always cut <b>straight whole line</b> which splits rectangle into two. It gives fuel to DP solution over $m,n$: what is the maximal price we can get out of $$m*n$$ rectangle? We just try exact match in prices, each vertical and horizontal cut, and choose maximum option.\nDP formula: $f...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
Python (Simple DP)
selling-pieces-of-wood
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given two integers `m` and `n` that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array `prices`, where `prices[i] = [hi, wi, pricei]` indicates you can sell a rectangular piece of wood of height `hi` and width `wi` for `pricei` dollars. To cut a piece of wood, ...
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
Python Easy Solution By Counting Number of "|"
count-asterisks
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
Easy Python Solution using Flag
count-asterisks
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTraversing the string and whenever \'|\' encounter in string reverse the flag value. And If the flag value is Flase i only count those \'*\'.\n\n# Complexity\n- Time c...
2
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
Python O(n)
count-asterisks
0
1
\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def countAsterisks(self, s: str) -> int:\n ans,t = 0,0\n for i in s:\n if i == "|":\n t += 1\n elif t % 2 ==0:\n ans += i=="*"\n\n return ans\...
3
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
Python Elegant & Short | Two solutions | One pass / One line
count-asterisks
0
1
\tclass Solution:\n\t\t"""\n\t\tTime: O(n)\n\t\tMemory: O(1)\n\t\t"""\n\n\t\tdef countAsterisks(self, s: str) -> int:\n\t\t\tis_closed = True\n\t\t\tcount = 0\n\n\t\t\tfor c in s:\n\t\t\t\tcount += is_closed * c == \'*\'\n\t\t\t\tis_closed ^= c == \'|\'\n\n\t\t\treturn count\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime:...
3
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
[Java/Python 3] Count after bars reach even, w/ brief explanation and analysis.
count-asterisks
1
1
Traverse input `s` and check the number of bars (`|`), whenever it reaches even numbers, we are outside of the pairs, then count the stars (`*`) in.\n\n```java\n public int countAsterisks(String s) {\n int star = 0;\n boolean barEven = true;\n for (int i = 0; i < s.length(); ++i) {\n ...
14
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
Python3 solution using for loop and continue
count-asterisks
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo ignore the characters in between a pair of ```|```\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a ```for``` loop and ```continue``` to skip the characters in between a pair of ```|```\n\n# Complexity\n-...
2
You are given a string `s`, where every **two** consecutive vertical bars `'|'` are grouped into a **pair**. In other words, the 1st and 2nd `'|'` make a pair, the 3rd and 4th `'|'` make a pair, and so forth. Return _the number of_ `'*'` _in_ `s`_, **excluding** the_ `'*'` _between each pair of_ `'|'`. **Note** that ...
null
DFS approach
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
5
You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`. Return _the **number of pairs** of different nodes that are ...
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
O(n) Time and Space || Python || Disjoint Data Structure
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly those nodes are unreachable that are not in the connected component of the graph.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsed disjoint set data structure to find the parent of each node.\nThen found pai...
2
You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`. Return _the **number of pairs** of different nodes that are ...
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
Python BFS Solution beats 95% | Adj List
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0
1
\n# Code\n```\n def countPairs(self, n: int, edges: List[List[int]]) -> int:\n # We find the nodes in the present connected component\n # that means all the other nodes that are not connected are\n # notconnectednodes = n-connectedNodes\n # therefores required pairs = (connectedNodes)*(n-...
2
You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`. Return _the **number of pairs** of different nodes that are ...
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
Python short and clean. DSU (Disjoint-Set-Union) | Union-Find. Functional programming.
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0
1
# Approach\n1. Create a `DSU (Disjoint-Set-Union)`.\n\n2. `Union` the edges one by one.\n\n3. Count the number of `nodes` in each `disjoint-set`, let\'s call this `counts` array with length `m`.\n\n4. Return `total` number of pairs possible. i.e\n $$ \\mathrm{total} = \\sum_{i=1}^{i=m-1} \\sum_{j=0}^{j=i-1} \\mathrm...
3
You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`. Return _the **number of pairs** of different nodes that are ...
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
Python | BFS + prefix sum solution
count-unreachable-pairs-of-nodes-in-an-undirected-graph
0
1
# Approach\n1) Make graph using $$dictionary$$ with $$set$$\n2) Apply $$BFS$$ on this graph to count number of $$connectivity$$ $$components$$ (and number of nodes in each component)\n3) Count $$prefix-sum$$ of this components to calc answer fast\n\n# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(N...
1
You are given an integer `n`. There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`. Return _the **number of pairs** of different nodes that are ...
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
[Java/Python 3] Bit manipulations w/ brief explanation and analysis.
maximum-xor-after-operations
1
1
**Key observation: `nums[i] & (nums[i] ^ x) <= nums[i]`**. Therefoe, we can only set off the `1` bits of each number if necessary, in order to make greatest of the xor all numbers after operations.\n\nSince 2<sup>27</sup> > 10<sup>8</sup>, we can traverse the left-most `28` bits to count how many `1`\'s on each bits.\n...
8
You are given a **0-indexed** integer array `nums`. In one operation, select **any** non-negative integer `x` and an index `i`, then **update** `nums[i]` to be equal to `nums[i] AND (nums[i] XOR x)`. Note that `AND` is the bitwise AND operation and `XOR` is the bitwise XOR operation. Return _the **maximum** possible ...
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
Python One Line (Detailed Explanation)
maximum-xor-after-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem relies on a few key observations made in sequence, which lend themselves to a very elegant solution.\n\nObservation 1: Since x is arbitrary, we can make (nums[i] XOR x) anything we like. For a given target number T = (nums[i]...
2
You are given a **0-indexed** integer array `nums`. In one operation, select **any** non-negative integer `x` and an index `i`, then **update** `nums[i]` to be equal to `nums[i] AND (nums[i] XOR x)`. Note that `AND` is the bitwise AND operation and `XOR` is the bitwise XOR operation. Return _the **maximum** possible ...
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
Python3 || 1 line, bit operations, w/ explanation || T/M: 88%/87%
maximum-xor-after-operations
0
1
Points to consider:\n\n* The problem calls for choosing an integer x, selecting an element n of the list, applying the compound operator op(n,x) = (x&n)^n, and taking the bit-intersection of the modified set. Because of the associative and commutative properties of the XOR operator, it does not matter which n we choo...
8
You are given a **0-indexed** integer array `nums`. In one operation, select **any** non-negative integer `x` and an index `i`, then **update** `nums[i]` to be equal to `nums[i] AND (nums[i] XOR x)`. Note that `AND` is the bitwise AND operation and `XOR` is the bitwise XOR operation. Return _the **maximum** possible ...
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
[Python3] top-down dp
number-of-distinct-roll-sequences
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7a67de4e975be771355e048bf8dde4cf0906e360) for solutions of biweekly 81. \n\n```\nclass Solution:\n def distinctSequences(self, n: int) -> int:\n \n @lru_cache\n def fn(n, p0, p1): \n """Return total number of dist...
5
You are given an integer `n`. You roll a fair 6-sided dice `n` times. Determine the total number of **distinct** sequences of rolls possible such that the following conditions are satisfied: 1. The **greatest common divisor** of any **adjacent** values in the sequence is equal to `1`. 2. There is **at least** a gap ...
To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection.
Python3] | Clear Top Down DP
number-of-distinct-roll-sequences
0
1
## Idea\nUse memoization (e.g. `cache`, `lru_cache`) to store number of combinations of length `rem` that can come after each pair.\nHandle edge case of `n == 1` to return `6`.\n\n## FAQ\n- Why do we consider only two elements for memoization?\n-- because you only need to look back for the last two elements. Given by r...
2
You are given an integer `n`. You roll a fair 6-sided dice `n` times. Determine the total number of **distinct** sequences of rolls possible such that the following conditions are satisfied: 1. The **greatest common divisor** of any **adjacent** values in the sequence is equal to `1`. 2. There is **at least** a gap ...
To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection.
🐍Python3 easiest solution🔥🔥
check-if-matrix-is-x-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Traverse Diagonal and then whole matrix**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- traverse matrix by primary and secondary diagonal\n- check if any of diagonal element are 0 if yes then return False.\n-...
3
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
Simple Python Solution
check-if-matrix-is-x-matrix
0
1
\n\n# Code\n```\nclass Solution:\n def checkXMatrix(self, grid: List[List[int]]) -> bool:\n n=len(grid)\n for i in range(n):\n for j in range(n):\n if((i!=j and i+j!=n-1) and grid[i][j]!=0):\n return 0\n elif((i==j or i+j==n-1) and grid[i][j]=...
1
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
Python 3 Beat 94% 263ms two pointer
check-if-matrix-is-x-matrix
0
1
\n\n# Code\n```\nclass Solution:\n def checkXMatrix(self, grid: List[List[int]]) -> bool:\n i, j = 0, len(grid) - 1\n a, b = [], []\n while i < len(grid):\n if i != j and grid[i].count(0) != len(grid) - 2:\n return False\n if grid[i][i] and grid[i][j] != 0:\...
1
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
Easy Python Solution
check-if-matrix-is-x-matrix
0
1
\n\n# Code\n```\nclass Solution:\n def checkXMatrix(self, grid: List[List[int]]) -> bool:\n n=len(grid)\n sum=0\n c=0\n for x in range(n):\n for y in range(n):\n if not(x==y) and not(x==n-y-1):\n sum+=grid[x][y]\n elif (x==y) or ...
1
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
Easiest Python solution you will find....... Single loop
check-if-matrix-is-x-matrix
0
1
\n```class Solution:\n def checkXMatrix(self, grid: List[List[int]]) -> bool:\n lst=[]\n a=0\n j=len(grid)-1\n for i in range(0,len(grid)):\n if grid[i][i]==0:\n return False\n if grid[i][j]==0:\n return False\n if i!=j:\n ...
1
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
[ Go , Python , C++ ] one pass w/ comments
check-if-matrix-is-x-matrix
0
1
<iframe src="https://leetcode.com/playground/j49mCxmw/shared" frameBorder="0" width="800" height="500"></iframe>
6
A square matrix is said to be an **X-Matrix** if **both** of the following conditions hold: 1. All the elements in the diagonals of the matrix are **non-zero**. 2. All other elements are 0. Given a 2D integer array `grid` of size `n x n` representing a square matrix, return `true` _if_ `grid` _is an X-Matrix_. Othe...
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of ...
[Python] Simple dp from index 0 to n
count-number-of-ways-to-place-houses
0
1
```\nclass Solution:\n def countHousePlacements(self, n: int) -> int:\n # the two sides of the roads are identical. We just need to count one side\n self.dp = collections.defaultdict(lambda: None)\n self.dp[0, 0] = 1 # the number cases not building house at index 0\n self.dp[0, 1] = 2 #...
1
There is a street with `n * 2` **plots**, where there are `n` plots on each side of the street. The plots on each side are numbered from `1` to `n`. On each plot, a house can be placed. Return _the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street_. S...
For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices.
Python | Easy to Understand | With Explanation | No Kadane
maximum-score-of-spliced-array
0
1
```\nclass Solution:\n def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:\n # create a difference array between nums1 and nums2\n # idea: find two subarray(elements are contiguous) in the diff\n # one is the subarray that have the minimum negative sum\n # another o...
3
You are given two **0-indexed** integer arrays `nums1` and `nums2`, both of length `n`. You can choose two integers `left` and `right` where `0 <= left <= right < n` and **swap** the subarray `nums1[left...right]` with the subarray `nums2[left...right]`. * For example, if `nums1 = [1,2,3,4,5]` and `nums2 = [11,12,1...
Consider what the paths from src1 to dest and src2 to dest would look like in the optimal solution. It can be shown that in an optimal solution, the two paths from src1 and src2 will coincide at one node, and the remaining part to dest will be the same for both paths. Now consider how to find the node where the paths w...
[Python3] dfs
minimum-score-after-removals-on-a-tree
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/0cdc07e704aeceebd9f20162639cca47846e6641) for solutions of weekly 299. \n\n```\nclass Solution:\n def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: \n n = len(nums)\n graph = [[] for _ in range(n)]\n ...
6
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica...
A row of bricks can be represented uniquely by the points where two bricks are joined together. For a given row of bricks, how many configurations of bricks could you have put below this row such that the wall is sturdy? Use dynamic programming to store the number of possible sturdy walls with a given height and config...
Solution without LCA and actual edge deleting. Simpler DFS.
minimum-score-after-removals-on-a-tree
0
1
# Approach\n1) Let\'s fix some edge *x-y*, imaginary delete it and consider two trees with roots *x* and *y*.\n2) Count subtrees xors for both of them (*xors* array).\n3) Let\'s fix some other node *v* - bottom end of second edge we delete.\n4) If *v* is in *x* tree, xors of components will be *[xors[v], xors[x] ^ xors...
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica...
A row of bricks can be represented uniquely by the points where two bricks are joined together. For a given row of bricks, how many configurations of bricks could you have put below this row such that the wall is sturdy? Use dynamic programming to store the number of possible sturdy walls with a given height and config...
Python (Simple DFS)
minimum-score-after-removals-on-a-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica...
A row of bricks can be represented uniquely by the points where two bricks are joined together. For a given row of bricks, how many configurations of bricks could you have put below this row such that the wall is sturdy? Use dynamic programming to store the number of possible sturdy walls with a given height and config...
cccc
decode-the-message
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows: 1. Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table. 2. Align the substitution table with t...
There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let ...
Easy Python solution using Hashing
decode-the-message
0
1
```python\nclass Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n mapping = {\' \': \' \'}\n i = 0\n res = \'\'\n letters = \'abcdefghijklmnopqrstuvwxyz\'\n \n for char in key:\n if char not in mapping:\n mapping[char] = letters...
40
You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows: 1. Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table. 2. Align the substitution table with t...
There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let ...
Easy Python Solution
decode-the-message
0
1
# Intuition\nThis code creates a dictionary d that maps each unique character in key (excluding whitespace) to a lowercase letter of the alphabet (starting from \'a\'). It then iterates through each character in message, and if the character is in the dictionary d, it appends the corresponding letter to a string ans. I...
3
You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows: 1. Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table. 2. Align the substitution table with t...
There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let ...
EASY UNDERSTANDABLE | PYTHON O(N) SOLUTION | APPROACH
decode-the-message
0
1
\n**Bold**\n# Intuition\nMatch the characters of the key with the <index>+97 th ASCII value to it.\n\n# Approach\n* First try to remove all the spaces and the duplicate characters from the key and store it in str1\n* now itereate through the new string and find its index in the str1 now lets say "v" the index of "v in ...
2
You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows: 1. Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table. 2. Align the substitution table with t...
There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let ...
Python Solution with comment
decode-the-message
0
1
**Time Complexcity O(N^2)\nspace complexcity O(N)**\n```\nclass Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n st=[]\n # convert string to list \n lst1=key.split(" ")\n for words in lst1:\n for word in words:\n if word in st:\n ...
1
You are given the strings `key` and `message`, which represent a cipher key and a secret message, respectively. The steps to decode `message` are as follows: 1. Use the **first** appearance of all 26 lowercase English letters in `key` as the **order** of the substitution table. 2. Align the substitution table with t...
There are only 2 valid patterns: ‘101’ and ‘010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form ‘01’ or ‘10’ first. Let n01[i] be the number of ‘01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let ...
Beats 98.6% || Only LOOPS || Python 3 Explained
spiral-matrix-iv
0
1
# Intuition\nThe code is very similar to the SPIRAL MATRIX I / II but here you need to check if we reach at the end of head i.e head.next = None;\nif it is None return ans as we reached end and all other matrix coloumn will be -1 (ans matrix is prefilled with -1)\nIts a pretty long code and shorter codes are also avail...
1
You are given two integers `m` and `n`, which represent the dimensions of a matrix. You are also given the `head` of a linked list of integers. Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order **(clockwise)**, starting from the **top-left** of the matrix. If there...
Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?
🔥🔥BEATS 90.46%🔥🔥||Easy Basic Solution
spiral-matrix-iv
0
1
\n# Approach\n\n---\n\nFill Matrix By traverssing Linked List\n\n# Complexity\n\n- Space complexity:\nO(N^2)\n\n# Code\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n\n---\n\n def spiralMa...
1
You are given two integers `m` and `n`, which represent the dimensions of a matrix. You are also given the `head` of a linked list of integers. Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order **(clockwise)**, starting from the **top-left** of the matrix. If there...
Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?
Simple Simulation very clear and easy to understand
spiral-matrix-iv
0
1
```\n\nclass Solution:\n def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n result = [ [-1] * n for _ in range(m) ]\n node = head\n \n \n \n UP = 2\n DOWN = 3\n LEFT = 1\n RIGHT = 0\n \n directions = ( (0...
2
You are given two integers `m` and `n`, which represent the dimensions of a matrix. You are also given the `head` of a linked list of integers. Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order **(clockwise)**, starting from the **top-left** of the matrix. If there...
Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?
🔥🔥One Way approach using spiral matrix traversal technique!!🔥🔥
spiral-matrix-iv
0
1
\n# Approach\nFirst of all i created a 2-D matrix of size n*m . Then use spiral Matrix Traversal technique and assign the cur head value at each cell.\n\n\n# Complexity\n- Time complexity:\nO(N*M)\n\n- Space complexity:\nO(N*M)\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(...
2
You are given two integers `m` and `n`, which represent the dimensions of a matrix. You are also given the `head` of a linked list of integers. Generate an `m x n` matrix that contains the integers in the linked list presented in **spiral** order **(clockwise)**, starting from the **top-left** of the matrix. If there...
Each s_i is a suffix of the string s, so consider algorithms that can determine the longest prefix that is also a suffix. Could you use the Z array from the Z algorithm to find the score of each s_i?
Two Queues or Rolling Array
number-of-people-aware-of-a-secret
0
1
The second solution below is the optimized version of the first one, though it could be hard to debug.\n\nTherefore, we will start with the two queues solution, which should be easier to code and build an intuition.\n\n#### Two Queues\n\nWe use separate queues to track how many people are ready to tell the secret each ...
57
On day `1`, one person discovers a secret. You are given an integer `delay`, which means that each person will **share** the secret with a new person **every day**, starting from `delay` days after discovering the secret. You are also given an integer `forget`, which means that each person will **forget** the secret `...
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
Easy Simulation with Explanation
number-of-people-aware-of-a-secret
0
1
##### Explanation\n* We could simulate the given requriements with an Array\n* Let\'s maintain an Array, `people`, where every index, `idx`, tracks the delay and forget timeline for everybody. Note that we do not care about people who forget about the secret, so the size could be `forget` for the Array \n* Initially, o...
11
On day `1`, one person discovers a secret. You are given an integer `delay`, which means that each person will **share** the secret with a new person **every day**, starting from `delay` days after discovering the secret. You are also given an integer `forget`, which means that each person will **forget** the secret `...
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
Python | DP | Dynamic Programming
number-of-people-aware-of-a-secret
0
1
Iterate from delay->forget for each time, increment one count, in addition to the current people who remember. For the day a user forgets, decrement one count\n\n```\nclass Solution:\n def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n \n dp = [0]*(n+1)\n \n for i in...
4
On day `1`, one person discovers a secret. You are given an integer `delay`, which means that each person will **share** the secret with a new person **every day**, starting from `delay` days after discovering the secret. You are also given an integer `forget`, which means that each person will **forget** the secret `...
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
[Python] Tabulation with visual explanation
number-of-people-aware-of-a-secret
0
1
The main idea is that on each i\'th day, every person who knows the secret, can tell one new person on every day within the range (lower, upper-1). where - \n\t1. Lower is calculated based on current day + delay\n\t2. Upper is the day before the person forgets which is i + forget (not inclusive)\n\nthus the main tabula...
6
On day `1`, one person discovers a secret. You are given an integer `delay`, which means that each person will **share** the secret with a new person **every day**, starting from `delay` days after discovering the secret. You are also given an integer `forget`, which means that each person will **forget** the secret `...
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
easy C++/Python DFS solutions|| w Explanation
number-of-increasing-paths-in-a-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse standard DFS to solve! After the DFS process, the value for visited[i][j] is the number of ways for starting from position (i, j) modulo the pretty prime number $10^9+7$!( since the if-condition is set to be grid[a][b]>grid[i][j] for...
3
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Python3 Solution
number-of-increasing-paths-in-a-grid
0
1
\n```\nclass Solution:\n def countPaths(self, grid: List[List[int]]) -> int:\n mod = 10**9+7 \n n = len(grid) \n m = len(grid[0]) \n dp = [[-1 for _ in range(m)] for _ in range(n)]\n \n def solve(row,col,grid,prev,dp):\n \n if row < 0 o...
2
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Simple Python solution
number-of-increasing-paths-in-a-grid
0
1
\n\n# Code\n```\nclass Solution:\n def countPaths(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n mod = 10**9+7\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n res = 0\n\n @lru_cache(maxsize = None)\n def dfs(i, j):\n ans = 0\n ...
2
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Faster than 89% , DFS, Python3
number-of-increasing-paths-in-a-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Python simple DP solution
number-of-increasing-paths-in-a-grid
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic programming.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(N\\cdot M)$ for calculating paths for each cell.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(N\\...
1
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
[Python] Easy Understand Code, Bottom-up DP + Sorting
number-of-increasing-paths-in-a-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are caring about how many increasing sequences ending at each grid. The sum of number increasing sequences at each grid is the final answer.\n\nStarts from smallest number to the largest in the grid, if all surrounding numbers are larg...
1
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
number-of-increasing-paths-in-a-grid
1
1
# An Upvote will be encouraging \uD83D\uDC4D\n\n# Video Solution\n\n# Search \uD83D\uDC49` Number of Increasing Paths in a Grid By Tech Wired`\n# or\n# Click the Link in my Profile\n\n```Python []\nclass Solution:\n def countPaths(self, grid):\n rows = len(grid)\n cols = len(grid[0])\n mod = 10...
20
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
✅✅Java✔ || C++✔ ||Python✔ || Solution Easy To Understand
number-of-increasing-paths-in-a-grid
1
1
# :) Guys Please VoteUp\nThe code provided seems to be solving a problem related to counting paths in a grid. However, without a clear problem statement, it\'s difficult to provide specific intuition.\n\n# Approach\nThe code uses a dynamic programming approach to count the number of paths in the given grid. It employs ...
98
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Python short and clean. DP. DFS. Functional programming.
number-of-increasing-paths-in-a-grid
0
1
# Approach\nTL;DR, Similar to [Editorial solution, Approach 2](https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/editorial/) but using functional programming.\n\n# Complexity\n- Time complexity: $$O(m * n)$$\n\n- Space complexity: $$O(m * n)$$\n\nwhere, `m x n is the dimensions of grid.`\n\n# Code\n```...
2
You are given an `m x n` integer matrix `grid`, where you can move from a cell to any adjacent cell in all `4` directions. Return _the number of **strictly** **increasing** paths in the grid such that you can start from **any** cell and end at **any** cell._ Since the answer may be very large, return it **modulo** `10...
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
Simple solution with using Post-order traversal in Python3
evaluate-boolean-binary-tree
0
1
# Intuition\nThe problem descriprion is the following:\n- there\'s a **Full Binary Tree (FBT)**, whose values are in range **[0, 3]**\n- our goal is to **evaluate** the logical expressions over operands\n\n```py\n# Example\nroot = [2, 1, 3, null, null, 0, 1]\n\n# This tree can be interpreted as the next logical express...
1
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python recursion solution beats 85%
evaluate-boolean-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRecursive approach\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass...
2
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
[ Go , Python , C++ ] w/ comments
evaluate-boolean-binary-tree
0
1
<iframe src="https://leetcode.com/playground/a8k3xokf/shared" frameBorder="0" width="800" height="500"></iframe>
4
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Simple Python Solution
evaluate-boolean-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python Elegant & Short | 94.5% faster | O(n) | Two lines
evaluate-boolean-binary-tree
0
1
![image](https://assets.leetcode.com/users/images/8eb386ec-53ce-4543-b793-6f5151b1721c_1660336623.5139685.png)\n\n```\nfrom operator import and_, or_\n\n\nclass Solution:\n\t"""\n\tTime: O(n)\n\tMemory: O(n)\n\t"""\n\n\tMAPPING = {\n\t\t0: lambda *_: False,\n\t\t1: lambda *_: True,\n\t\t2: or_,\n\t\t3: and_,\n\t}\n\n...
14
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python 3 lines | easiest
evaluate-boolean-binary-tree
0
1
# Upvote it :)\n```\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n if root.val == 2: return self.evaluateTree(root.left) or self.evaluateTree(root.right)\n elif root.val == 3: return self.evaluateTree(root.left) and self.evaluateTree(root.right)\n else: return roo...
4
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
✅✅✅ 97.89% faster python solution
evaluate-boolean-binary-tree
0
1
![Screenshot 2022-12-18 at 16.23.45.png](https://assets.leetcode.com/users/images/405791d7-4448-46b2-a9bc-6c5291d04855_1671362645.393128.png)\n\n# Code\n```\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n if root.val==3:\n return self.evaluateTree(root.left) and self....
7
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Easy python 6 line solution
evaluate-boolean-binary-tree
0
1
```\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n if root.val==0 or root.val==1:\n return root.val\n if root.val==2:\n return self.evaluateTree(root.left) or self.evaluateTree(root.right)\n if root.val==3:\n ...
11
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python straightforward recursion
evaluate-boolean-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe big picture is that you need to evalute the root with left subtree and right subtree.\nSo what is the termination condition? The answer is when you reach the leaf of the tree and return the boolean value of the leaf node.\nAnd then le...
3
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python3 || Recursion and boolean logic || 5 lines
evaluate-boolean-binary-tree
0
1
```\nclass Solution:\n def evaluateTree(self, root: TreeNode) -> bool:\n #\n # Recursion:\n #\n # Base Case: node.val = 0 or 1. Return T or F\n # \n ...
3
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Python || Inorder Traversal || Easy To Understand 🔥
evaluate-boolean-binary-tree
0
1
# Code\n```\nclass Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n def inorder(root):\n if root is None: return True\n val = root.val\n if root.left is not None and root.right is not None:\n if val == 2:\n return inorde...
2
You are given the `root` of a **full binary tree** with the following properties: * **Leaf nodes** have either the value `0` or `1`, where `0` represents `False` and `1` represents `True`. * **Non-leaf nodes** have either the value `2` or `3`, where `2` represents the boolean `OR` and `3` represents the boolean `A...
null
Easiest one
the-latest-time-to-catch-a-bus
0
1
# Code\n```\nclass Solution:\n def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n buses.sort()\n passengers.sort()\n\n index = 0\n\n for start in buses:\n cap = capacity\n while index < len(passengers) and start >= passe...
1
You are given a **0-indexed** integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a **0-indexed** integer array `passengers` of length `m`, where `passengers[j]` represents the arrival time of the `jth` passenger. All bus departure times are unique. A...
null
Clean and Concise Greedy with Intuitive Explanation
the-latest-time-to-catch-a-bus
0
1
##### Rationale\n* We could imagine the time given in the `passengers` Array to be a seat. A passenger may take a seat only if it is not taken already. The problem then boils down to finding the last possible seat for our candidate. This analogy makes it easier to visualize the problem\n* Since we would like our candid...
7
You are given a **0-indexed** integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a **0-indexed** integer array `passengers` of length `m`, where `passengers[j]` represents the arrival time of the `jth` passenger. All bus departure times are unique. A...
null
Python Simple Solution 95.6%
the-latest-time-to-catch-a-bus
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given a **0-indexed** integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a **0-indexed** integer array `passengers` of length `m`, where `passengers[j]` represents the arrival time of the `jth` passenger. All bus departure times are unique. A...
null
[Python] Easy to understand binary search solution
minimum-sum-of-squared-difference
0
1
This solution can be broken down into two parts:\n\n1. Find the new max for the array of diffs\n2. Find the index to first start replacing diffs with our new max\n\nWe can use binary search to solve both of these problems.\n\n```\nclass Solution:\n def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: i...
1
You are given two positive **0-indexed** integer arrays `nums1` and `nums2`, both of length `n`. The **sum of squared difference** of arrays `nums1` and `nums2` is defined as the **sum** of `(nums1[i] - nums2[i])2` for each `0 <= i < n`. You are also given two positive integers `k1` and `k2`. You can modify any of th...
null
Python3. || Stack, 9 lines || T/M : 986 ms/28 MB
subarray-with-elements-greater-than-varying-threshold
0
1
```\nclass Solution:\n def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n # Stack elements are the array\'s indices idx, and montonic with respect to nums[idx].\n # When the index of the nearest smaller value to nums[idx] comes to the top of t...
8
You are given an integer array `nums` and an integer `threshold`. Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`. A **subarray** is a contiguous non-em...
null
[Python3] monotonic stack
subarray-with-elements-greater-than-varying-threshold
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/04944f0a6a1f4d50ee6efd64fabfc227724cdc7a) for solutions of biweekly 82. \n\n```\nclass Solution:\n def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n stack = []\n for hi, x in enumerate(nums + [0]): \n ...
1
You are given an integer array `nums` and an integer `threshold`. Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`. A **subarray** is a contiguous non-em...
null
[Python 3]Hint solution
subarray-with-elements-greater-than-varying-threshold
0
1
Again, hard needs hint...\n\n```\nclass Solution:\n def validSubarraySize(self, nums: List[int], t: int) -> int:\n n = len(nums)\n if t / n >= max(nums):\n return -1\n \n left = list(range(n))\n right = list(range(n))\n\n # leftmost boundary for the subarray for e...
1
You are given an integer array `nums` and an integer `threshold`. Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`. A **subarray** is a contiguous non-em...
null
Python (Simple Stack Solution)
subarray-with-elements-greater-than-varying-threshold
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an integer array `nums` and an integer `threshold`. Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`. A **subarray** is a contiguous non-em...
null
Simple Python solution with explanation
minimum-amount-of-time-to-fill-cups
0
1
Sort the list. Every time take two max numbers and decrement them by one. Aslo increment count by one. If only one non zero element present then add that number to count and return the count. If all are zero then return count. \n\n```\nimport math\nclass Solution:\n def fillCups(self, l: List[int]) -> int:\n ...
3
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up `2` cups with **different** types of water, or `1` cup of any type of water. You are given a **0-indexed** integer array `amount` of length `3` where `amount[0]`, `amount[1]`, and `amount[2]` denote the number ...
null
Simple Python3 Solution|| Lists || Dictionaries || Upto 50% faster ||
smallest-number-in-infinite-set
0
1
# Approach\nSimple Python3 code using Lists once and then dictionaries for the other.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\n\n```python []\nclass SmallestInfiniteSet:\n\n def __init__(self):\n self.nums = list(range(1,1001))\n \n\n def popSmallest(self...
2
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
python3 Solution
smallest-number-in-infinite-set
0
1
\n```\nclass SmallestInfiniteSet:\n\n def __init__(self):\n self.seen=[False]*1005\n\n\n def popSmallest(self) -> int:\n for i in range(1,1005):\n if not self.seen[i]:\n self.seen[i]=True\n return i\n\n def addBack(self, num: int) -> None:\n if num<...
2
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
Python3 beats 🚀 95.5% and 99.45% 🚀 || quibler7
smallest-number-in-infinite-set
0
1
![Screenshot 2023-04-25 at 8.29.50 AM.png](https://assets.leetcode.com/users/images/64fc7c75-034e-447b-807e-a4ef5e6e3a70_1682391604.414772.png)\n# Code\n```\nclass SmallestInfiniteSet:\n\n def __init__(self):\n self.curr = 1\n self.set = set()\n\n def popSmallest(self) -> int:\n if self.set:\...
1
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
Python easy solution
smallest-number-in-infinite-set
0
1
\n# Complexity\n- Time complexity:\n```SmallestInfiniteSet().popSmallest()```: if ```len(SmallestInfiniteSet().added) == n > 0``` -> $$O(n)$$ else $$O(1)$$\n```SmallestInfiniteSet().addBack()```: $$O(1)$$\n```SmallestInfiniteSet()```: $$O(1)$$\n\n- Space complexity:\n```SmallestInfiniteSet().popSmallest()```: if ```len...
1
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
[Python3] Heap approach
smallest-number-in-infinite-set
0
1
# Intuition\nWe need to maintain:\n1. Smallest number not yet retrieved\n2. Numbers that were already put back - in a heap and in a set\n\nWhen popping smallest - check if we have it pushed back - in the set - if it is present - then remove it from the set and from the heap, and return. \nOtherwise - return smallest an...
1
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
Python short and clean. 2-solutions.
smallest-number-in-infinite-set
0
1
# Approach\nTL;DR, Similar to the [Editorial solution](https://leetcode.com/problems/smallest-number-in-infinite-set/editorial/).\n\n# Complexity\n- Time complexity: $$O((m + n) * log(n))$$\n\n- Space complexity: $$O(n)$$\n\nwhere,\n`m is number of calls to popSmallest`,\n`n is number of calls to addBack`.\n\n# Code\nU...
2
You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. Implement the `SmallestInfiniteSet` class: * `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. * `int popSmallest()` **Removes** and returns the smallest integer contained in the ...
null
[Java/Python 3] Compare the sequences and the indices of 'L' and 'R'.
move-pieces-to-obtain-a-string
1
1
**Intuition:**\n\nSince `L`s and `R`s can ONLY move to empty spaces and can NOT swap, the sequences containing all `L`s and `R`s and only `L`s and `R`s of `start` and `target` must be same;\nSince `L`s and `R`s can move to left and right only respectively, all positions of `L`s in `start` must be no less than the corre...
79
You are given two strings `start` and `target`, both of length `n`. Each string consists **only** of the characters `'L'`, `'R'`, and `'_'` where: * The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the **left** only if there is a **blank** space directly to its left, and a piece `'R'`...
null
Python3 || 10 lines, w/ explanation || T/M: 96%/ 44%
move-pieces-to-obtain-a-string
0
1
```\nclass Solution:\n # Criteria for a valid transormation:\n\n # 1) The # of Ls, # of Rs , and # of _s must be equal between the two strings\n #\n # 2) The ordering of Ls and Rs in the two strings must be the same.\n #\...
3
You are given two strings `start` and `target`, both of length `n`. Each string consists **only** of the characters `'L'`, `'R'`, and `'_'` where: * The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the **left** only if there is a **blank** space directly to its left, and a piece `'R'`...
null
[Python3] greedy
move-pieces-to-obtain-a-string
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/f00c06cefbc1b2305f127a8cde7ff9b010197930) for solutions of weekly 301. \n\n```\nclass Solution:\n def canChange(self, s: str, e: str) -> bool:\n dl = dr = 0 \n for ss, ee in zip(s, e): \n if dl > 0 or dl < 0 and ss == \'...
2
You are given two strings `start` and `target`, both of length `n`. Each string consists **only** of the characters `'L'`, `'R'`, and `'_'` where: * The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the **left** only if there is a **blank** space directly to its left, and a piece `'R'`...
null
[Python3] freq table
count-the-number-of-ideal-arrays
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/f00c06cefbc1b2305f127a8cde7ff9b010197930) for solutions of weekly 301. \n\n**Intuition**\nIt is not hard to figure out that this is a DP problem. What\'s challenging is that due to the very tight time constraint, one has to come up with a linear-is...
32
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
null
[Python] Freq Table Solution (by ye15) with Explanations
count-the-number-of-ideal-arrays
0
1
First, full credits to @ye15\'s [amazing solution](https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261351/Python3-freq-table). Here are some explanations.\n\nInstead of counting the possible ideal arrays by different starting (or ending) values, we count the possible ideal arrays by the number o...
3
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
null
[Python] Stars and Bars combinatorics, beats 100%, O(M log^2 M)
count-the-number-of-ideal-arrays
0
1
**Idea**\n\n* Count the number of ideal arrays without allowing repeats.\n* Use [Stars and Bars](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)) to calculate the number of ideal arrays with repeats, given the unique counts. Each ideal array of length `x` without repeats can become `(n-1 choose x-1)` ideal...
1
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
null
Python (Simple Maths)
count-the-number-of-ideal-arrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: * Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. * Every `arr[i]` is divisible by `arr[i - ...
null
Simple solution with HashTable
maximum-number-of-pairs-in-array
0
1
# Intuition\nHere we have:\n- a list of `nums`\n- our goal is to find **the maximum count of pairs**, that has equal integers as `[1, 1], [2,2]` etc.\n\nWe don\'t need to **remove** integers, because it costs an auxillary **O(N)** time.\nInstead we define a **HashMap** to store frequencies of a particular integer.\n\n`...
1
You are given a **0-indexed** integer array `nums`. In one operation, you may do the following: * Choose **two** integers in `nums` that are **equal**. * Remove both integers from `nums`, forming a **pair**. The operation is done on `nums` as many times as possible. Return _a **0-indexed** integer array_ `answer...
null
Python using Set 96% beats
maximum-number-of-pairs-in-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a **0-indexed** integer array `nums`. In one operation, you may do the following: * Choose **two** integers in `nums` that are **equal**. * Remove both integers from `nums`, forming a **pair**. The operation is done on `nums` as many times as possible. Return _a **0-indexed** integer array_ `answer...
null
Python | Easy Solution✅
maximum-number-of-pairs-in-array
0
1
```\ndef numberOfPairs(self, nums: List[int]) -> List[int]: \n output = [] # nums = [1,3,2,1,3,2,2]\n pair = 0\n unique = list(set(nums)) # [1,3,2] get unique elements from nums\n for i in range(len(unique)):\n count = nums.count(unique[i]) # count no of element in nums\n ...
4
You are given a **0-indexed** integer array `nums`. In one operation, you may do the following: * Choose **two** integers in `nums` that are **equal**. * Remove both integers from `nums`, forming a **pair**. The operation is done on `nums` as many times as possible. Return _a **0-indexed** integer array_ `answer...
null
Simple and Easy to Understand | Python
maximum-number-of-pairs-in-array
0
1
If you have any **doubt** or **suggestion,** put in comments **:)**\n```\nclass Solution(object):\n def numberOfPairs(self, nums):\n hashT = {}\n for n in nums:\n if n not in hashT: hashT[n] = 1\n else: hashT[n] += 1\n pairs, rem = 0, 0\n for n in hashT:\n ...
5
You are given a **0-indexed** integer array `nums`. In one operation, you may do the following: * Choose **two** integers in `nums` that are **equal**. * Remove both integers from `nums`, forming a **pair**. The operation is done on `nums` as many times as possible. Return _a **0-indexed** integer array_ `answer...
null
Simple Readable Python solution
max-sum-of-a-pair-with-equal-sum-of-digits
0
1
\n\n# Code\n```\nclass Solution:\n def maximumSum(self, nums: List[int]) -> int:\n a = [[sum([int(x) for x in str(nums[i])]), nums[i]] for i in range(len(nums))]\n mx = 0\n b = [a[i][0] for i in range(len(a))]\n if len(b) == len(set(b)): return -1\n\n d = defaultdict(list)\n ...
1
You are given a **0-indexed** array `nums` consisting of **positive** integers. You can choose two indices `i` and `j`, such that `i != j`, and the sum of digits of the number `nums[i]` is equal to that of `nums[j]`. Return _the **maximum** value of_ `nums[i] + nums[j]` _that you can obtain over all possible indices_ ...
null
python 3 with TC O(n), using defaultdict
max-sum-of-a-pair-with-equal-sum-of-digits
0
1
# Intuition\n- **First Thoughts**: Use a hash table to track numbers with the same digit sum. Since the goal is to find the maximum sum pair, the hash map needs to only record the highest value for each digit sum.\n\n# Approach\n- **Strategy**: Implement a Python defaultdict with a zero initial value, simplifying the c...
0
You are given a **0-indexed** array `nums` consisting of **positive** integers. You can choose two indices `i` and `j`, such that `i != j`, and the sum of digits of the number `nums[i]` is equal to that of `nums[j]`. Return _the **maximum** value of_ `nums[i] + nums[j]` _that you can obtain over all possible indices_ ...
null
[Python] two sum
max-sum-of-a-pair-with-equal-sum-of-digits
0
1
```python\nclass Solution:\n def maximumSum(self, nums: List[int]) -> int:\n dict_map = {}\n \n res = -1\n for num in nums:\n temp = num\n new_num = 0\n while temp:\n new_num += temp % 10\n temp = temp // 10\n if ne...
3
You are given a **0-indexed** array `nums` consisting of **positive** integers. You can choose two indices `i` and `j`, such that `i != j`, and the sum of digits of the number `nums[i]` is equal to that of `nums[j]`. Return _the **maximum** value of_ `nums[i] + nums[j]` _that you can obtain over all possible indices_ ...
null
[Python 3] Quick Select - Simple solution
query-kth-smallest-trimmed-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(M)$$ for each queries in Average with M is length of nums\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space comp...
3
You are given a **0-indexed** array of strings `nums`, where each string is of **equal length** and consists of only digits. You are also given a **0-indexed** 2D integer array `queries` where `queries[i] = [ki, trimi]`. For each `queries[i]`, you need to: * **Trim** each number in `nums` to its **rightmost** `trim...
null