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 (Simple Hashmap) | triples-with-bitwise-and-equal-to-zero | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums):\n n, total, dict1 = len(nums), 0, collections.Counter(x&y for x in nums for y in nums)\n\n for i in nums:\n for j in dict1:\n if i&j == 0:\n total += dict1[j]\n\n return total\n\n\n``` | 2 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Python (Simple Hashmap) | triples-with-bitwise-and-equal-to-zero | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums):\n n, total, dict1 = len(nums), 0, collections.Counter(x&y for x in nums for y in nums)\n\n for i in nums:\n for j in dict1:\n if i&j == 0:\n total += dict1[j]\n\n return total\n\n\n``` | 2 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Something like 3sum | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n res = 0\n freq = {}\n n = len(nums)\n for i in range(n):\n for j in range(n):\n t = nums[i]&nums[j]\n if t not in freq:\n freq[t] = 0\n freq[t] += 1\n \n for n in nums:\n for t in freq:\n if n&t == 0:\n res += freq[t]\n return res\n\n \n``` | 1 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Something like 3sum | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n res = 0\n freq = {}\n n = len(nums)\n for i in range(n):\n for j in range(n):\n t = nums[i]&nums[j]\n if t not in freq:\n freq[t] = 0\n freq[t] += 1\n \n for n in nums:\n for t in freq:\n if n&t == 0:\n res += freq[t]\n return res\n\n \n``` | 1 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python 3: Galaxy Brain: Walsh-Hadamard-Like Transform, O(max*log(max) + N) Time, O(max) Space | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intro\n\nI read [this solution](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) by @basselbakr and was amazed, but also completely mystified by how it works.\n\nA couple of sources have some insights, but were VERY dense and IMO could be explained much better. For example, they discuss FFTs (Fast Fourier Transforms) at length, and multiplying n-digit numbers. But then skip over most of the details of this problem. They are worth reviewing though after reviewing this solution:\n* [Fast Fourier transforms and variations of it](https://csacademy.com/blog/fast-fourier-transform-and-variations-of-it)\n* [Fast Walsh Hadamard Transforms and it\'s inner workings](https://codeforces.com/blog/entry/71899)\n\n**NOTE:** Hadamard-Walsh transforms solve the `xor` version of this problem. Here we use something similar, but the matrix values are different because we want `and` instead of `xor`.\n\n# Outline\n\nHere\'s how the solution works at a high level:\n1. we start by solving the problem for 1-bit numbers\n2. knowing we have to solve the n-bit numbers case later, we look for a linear transform $T$ where $$ T(\\mathbf{c} \\$ \\mathbf{d}) = T\\mathbf{c} : T\\mathbf{d} $$ where $$ \\mathbf{c} \\$ \\mathbf{d} $$ is the solution with count vectors $\\mathbf{c}$ and $\\mathbf{d}$, and $:$ represents element-wise multiplication\n3. We find a way to write the transform for $2^n$ entries recursively using $2^{n-1}$ entries\n3. We use that recursive definition to compute the transform with divide-and-conquer in $O(M \\log(M))$ where $M$ is the max value\n4. Then we use (2) to show that the solution to this problem where we want size $k$ tuples of indices is $$ T \\mathbf{c}$$ element-wise raised to the $k$ power\n5. And finally we derive the inverse transform $T^{-1}$, which fortunately is a LOT easier once we\'ve done 1-4.\n\n# Intuition\n\nNaively we can use a brute-force algorithm: iterate over all possible triples. $O(M^3)$.\n\nIf we\'re smarter, as other solutions are, we realize that `m & n & p == (m & n) & p`: we can replace _triples_ with _tuples_.\n* get the frequency of each value\n* get the frequency of all possible `m & n` values\n* then for each value `p`, iterate over all `a == m & n` values where `m & n & p` is 0.\n\nThis is $O(M^2)$. Getting better.\n\nBut what if we could reduce the cost of getting all pairwise combinations down to $O(M \\log(M))$? Then\n* we could do all pairs in $O(M \\log(M))$\n* then combine all pairs with all singles to make triples, again in $O(M \\log(M))$\n* and so on\n\n# Approach\n\n## One-Bit Solution: Pairs\n\nSuppose we have a vector of counts $$\\mathbf{c}_2 = \\left[ \\begin{align} c_0 \\\\ c_1 \\end{align}\\right] $$. $$ \\mathbf{c}_2 $$ means we have counts for all 1 bit numbers, values $0$ and $1$. $$c_i$$ is the count of numbers with value $i$. Let $$\\mathbf{d}_2$$ be another vector of counts.\n\nWe represent the solution to "how many index pairs (i, j), where i is from $$\\mathbf{c}$$ and j is from $$\\mathbf{d}$$, have each possible bitwise `&` value?" as $$\\mathbf{c} \\$ \\mathbf{d}$$. Because answers are where the money is at.\n\nFor the 1-bit case the answer is pretty easy:\n* to get a bitwise `&` of 0: any zero in $$\\mathbf{c}$$, and any number in $$\\mathbf{d}$$. Or a one in $$\\mathbf{c}$$ and a zero value from $$\\mathbf{d}$$.\n * $$c_0 d_0 + c_0 d_1 + c_1 d_0$$\n* to get a bitwise `&` of 1: both numbers have to be 1\n * $$c_1 d_1$$\n\nThis gives us $$ \\mathbf{c}_2 = \\left[ \\begin{matrix} c_0 d_0 + c_0 d_1 + c_1 d_0 \\\\ c_1 d_1 \\end{matrix} \\right] $$\n\n## Linear Transform: Pairs\n\nThe above approach extends to n-bit numbers, but it involves $O(2^n)$ calculations to get the values in each row.\n\nInstead, we look for a linear transform where we\'ll do the following:\n* transform $$\\mathbf{c}$$ and $$\\mathbf{d}$$ with $T$\n* do an element-wise product of $$T\\mathbf{c} : T\\mathbf{d}$$. This will give us the transformed answer, i.e. $$T(\\mathbf{c} \\$ \\mathbf{d})$$\n* apply the inverse transform, $T^{-1}$, to get $$\\mathbf{c} \\$ \\mathbf{d}$$\n\nSo we let $$ T_2 = \\left[ \\begin{matrix} t_0 & t_1 \\\\ t_2 & t_3 \\end{matrix} \\right]$$ and solve for the entries so that $$ T_2(\\mathbf{c}_2 \\$ \\mathbf{d}_2) = T_2 \\mathbf{c}_2 : T_2 \\mathbf{d}_2 $$.\n\nWriting this out gives us\n\n$$ \\left[ \\begin{matrix} t_0 & t_1 \\\\ t_2 & t_3 \\end{matrix} \\right] \\, \\left[ \\begin{matrix} c_0 d_0 + c_0 d_1 + c_1 d_0 \\\\ c_1 d_1 \\end{matrix} \\right] = \\left[ \\begin{matrix} (t_0 c_0 + t_1 c_1) \\cdot (t_0 d_0 + t_1 c_1) \\\\ (t_2 c_0 + t_3 c_1) \\cdot (t_2 d_0 + t_3 c_1) \\end{matrix} \\right] $$\n\nTo review, the left is the transform of the solution, and the right is the element-wise product of transforms.\n\nNow we compare the coefficients of the powers for $$ c_i d_j $$ combinations, which have to match so the solution works for all possible counts. The algebra is tedious, but you can trust me when I saw you can solve the equations to get the following:\n* each $t_i$ is 0 or 1\n* if $t_0$ is 1, then $t_1$ cannot be 0, same for $t_2$ and $t_3$, respectively\n\nThis means that both rows of $$T_2$$ have to be one of the following:\n* $$\\left[ 0, 0 \\right]$$\n* $$\\left[ 1, 1 \\right]$$\n* $$\\left[ 0, 1 \\right]$$\n\nFinally, we realize that our plan above is to apply $T^{-1}$ at the end. This means we need $T$ to be full rank. Therefore we can\'t have $$\\left[ 0, 0 \\right]$$ as a row, and the columns must be linearly independent.\n\nSo we discover that $$T$$ must either be $$\\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right]$$ or $$\\left[ \\begin{matrix} 0 & 1 \\\\ 1 & 1 \\end{matrix} \\right]$$. It turns out that both work; the right one is the row flipped version of the left. They both work because we need leftSide = rightSide in the equation, but the order of the rows doesn\'t matter. So from that two-fold degree of freedom arises a size-2 family of $T_2$ matrices that both work. I suspect a situation with three rows would give 3!=6 different $T_3$ matrices.\n\nAnyway, we\'ll use the one on the left because it\'s more intuitive in the next section.\n\n## Finding the Transform for 2-bit Numbers from the 1-bit Transform\n\nNow we enter the most complicated part of the problem, but I\'ll do my best.\n\nWe now want to solve the problem for 2-bit numbers, 0..3. The goal is to write the solution in terms of the 1-bit numbers. This will show a recursive pattern where the solution for n-bit numbers depends on the the solutions for n-1-bit numbers.\n\nFor 2-bit numbers we have counts $$\\mathbf{c}_4 = \\left[ \\begin{matrix} c_{00} \\\\ c_{01} \\\\ c_{10} \\\\ c_{11} \\end{matrix} \\right]$$. Same with $$\\mathbf{d}_4$$. I\'ve written the subscripts in binary.\n\nTo simplify this, notice that we have two copies of the 1-bit subproblem:\n1. the top two entries, 0 and 1, where the new second bit is 0\n2. the bottom two entries, 0 and 1, where the new second bit is 1\n\nSo I\'ll rewrite it using the new vectors $$ \\mathbf{c}_2^0 = \\left[ \\begin{matrix} c_{00} \\\\ c_{01} \\end{matrix} \\right]$$ and $$ \\mathbf{c}_2^1 = \\left[ \\begin{matrix} c_{10} \\\\ c_{11} \\end{matrix} \\right]$$. Now we get $$\\mathbf{c}_4$$ in the new notation: $$\\left[ \\begin{matrix} \\mathbf{c}_2^0 \\\\ \\mathbf{c}_2^1 \\end{matrix} \\right]$$.\n\nThis temporarily makes it more complicated. But it also lets us see that the result is this: $$\\mathbf{c}_4 \\$ \\mathbf{d}_4 = \\left[ \\begin{matrix} \\mathbf{c}_2^0 \\$\\mathbf{d}_2^0 + \\mathbf{c}_2^1 \\$\\mathbf{d}_2^0 + \\mathbf{c}_2^0 \\$\\mathbf{d}_2^1 \\\\ \\mathbf{c}_2^1 \\$\\mathbf{d}_2^1 \\end{matrix} \\right]$$. The terms in the top row are all combinations that give us a 0 in the 2s digit of the `&` result, and the bottom row is the only combination that gives us a 1 in the 2s digit of the `&` result. **This is the same pattern as before for the 1-bit number**.\n\nHere\'s the transformed version:\n\n$$ T_4(\\mathbf{c}_4 \\$ \\mathbf{d}_4) = \\left[ \\begin{matrix} t_0 (T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^1) + t_1 (T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^1) \\\\ t_2 (T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^1) + t_3 (T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^1) \\end{matrix} \\right] = T_4 \\mathbf{c}_4 : T_4 \\mathbf{d}_4 = \\left[ \\begin{matrix} (t_0 T_2 \\mathbf{c}_2^0 + t_1 T_2 \\mathbf{c}_2^1) : (t_0 T_2 \\mathbf{d}_2^0 + t_1 T_2 \\mathbf{d}_2^1) \\\\ (t_2 T_2 \\mathbf{c}_2^0 + t_3 T_2 \\mathbf{c}_2^1) : (t_2 T_2 \\mathbf{d}_2^0 + t_3 T_2 \\mathbf{d}_2^1) \\end{matrix}\\right]$$ \n\nWhat we\'ve done is rewrite the 2-bit solution in terms of the 1-bit solutions. I know this looks absolutely horrifying. But it\'s a detailed way to show you that this is the same pattern as the 1-bit solution:\n* before we had $c_i$ and $d_i$, now we have $T_2 \\mathbf{c}_2^i$ and $T_2 \\mathbf{d}_2^i$\n* after comparing by parts, the $t_0 \\, ... \\, t_3$ have the same relationships and therefore the the same $t_0 = t_1 = t_3 = 1$ and $t_2 = 0$ values.\n\nFinally, plugging in the $t_i$ values shows us that\n$$ T_4 \\mathbf{c}_4 = \\left[ \\begin{matrix} t_0 T_2 \\mathbf{c}_2^0 + t_1 T_2 \\mathbf{c}_2^1 \\\\ t_2 T_2 \\mathbf{c}_2^0 + t_3 T_2 \\mathbf{c}_2^1 \\end{matrix}\\right] = \\left[ \\begin{matrix} T_2 \\mathbf{c}_2^0 + T_2 \\mathbf{c}_2^1 \\\\ T_2 \\mathbf{c}_2^1 \\end{matrix}\\right]$$\nand thus\n$$T_4 = \\left[ \\begin{matrix} T_2 & T_2 \\\\ 0 & T_2 \\end{matrix} \\right] \\equiv T_2 \\otimes \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right]$$\n\nSo the pattern for the 2-bit transform is\n* get the transform of the 1-bit problems, the first half and the second half\n* add the second half\'s trasnform to the first half\n\n## Recursion: Finding the n-bit Transform\n\nFor the 1-bit transform, we added the second half of the 2-entry vector, $c_1$, to the first half.\n\nFor the 2-bit transform, we added the second half of the transformed 4-entry vector, $\\mathbf{c}_2^1$, to the first half\n\nFor each next bit we follow the pattern; you can derive it above for each level by by replacing the _4/_2 with _8/_4, _16/_8, etc. Take the transform of the two halves, and add the second half to the first half.\n\nThe pattern in the $T$ matrices is $$ T_{2N} = \\left[ \\begin{matrix} T_N & T_N \\\\ 0 & T_N \\end{matrix} \\right]$$\n\n**NOTE:** this is similar to the Walsh-Hadamard transform. Same concept of a recursively defined matrix. Just different values. This solves `&` combinations, while Walsh-Hadamard solves `^` combinations.\n\n## Algorithm for n-bit Transform in O(n*log(n))\n\nThe pseudocode is actually in the prior section already! The transform for $T_N$ needs the transform of the first $N/2$ and second $N/2$ with $T_{N/2}$. That in turn needs transforms of groups of $N/4$ elements with $T_{N/4}$, and so on. So we\n* first apply T_2 to pairs of elements\n* then in groups of 4, add the now-transformed second half to the first half. This applies $T_4$ to each group of 4\n* repeat in groups of 8 for $T_8$, then 16 for $T_{16}$, and so on\n\nEach group size is a scan over all N elements. We do a scan for group sizes 2, 4, 8, etc. which is log(N) scans. So $O(N \\log(N))$ total!\n\n**Note:** this is basically the derivation of the fast Walsh-Hadamard transform, just for a matrix with slightly different entries.\n\n## (Transformed) Solutions for Pairs and Triples\n\nLet the number of pairs with each `&` result be $$\\mathbf{p}$$. Then $$T \\mathbf{p} = T (\\mathbf{c} \\$ \\mathbf{c}) = T\\mathbf{c} : T\\mathbf{c}$$.\n\nFor triples, we can find the number of combinations of pairs and singles with each `&` result. Let\'s call that $$\\mathbf{t}$$. Same situation as before:\n$$ T \\mathbf{t} = T(\\mathbf{p} \\$ \\mathbf{c}) = T \\mathbf{p} : T \\mathbf{c} = T \\mathbf{c} : T \\mathbf{c} : T \\mathbf{c}$$\n\nIf you keep going for quadruplets, quintuplets, etc. you find that the number of groups of `k` indices for each bitwise `&` is $$T \\mathbf{c}$$ raised element-wise to the power of `k`!\n\n## The Final Step: Inverse Transform\n\nThe last part is to be able to do the invese transform: we need $\\mathbf{t}$, not $T \\mathbf{t}$ from the prior section.\n\nFortunately it\'s much easier to derive the inverse transform than the forward one.\n\nFrom the formula for 2x2 matrix inverses, $$T_2^{-1} = \\left[ \\begin{matrix} 1 & -1 \\\\ 0 &1 \\end{matrix} \\right]$$.\n\nFor $$T_4 = \\left[ \\begin{matrix} T_2 & T_2 \\\\ 0 & T_2 \\end{matrix} \\right]$$, the matrix inverse is $$T_4^{-1} = \\left[ \\begin{matrix} T_2^{-1} & -T_2^{-1} \\\\ 0 & T_2^{-1} \\end{matrix} \\right]$$.\n\nFor $T_{2N}$, the pattern continues: $$T_{2N}^{-1} = \\left[ \\begin{matrix} T_{N}^{-1} & -T_{N}^{-1} \\\\ 0 & T_{N}^{-1} \\end{matrix} \\right]$$\n\nIf you look closely at the prior line, this is _almost_ exactly the same thing as the forward transform. There\'s just a minus sign instead of a plus sign in the upper-right entry. So the fast inverse Walsh-Hadamard-like transform _subtracts_ the second half instead of _adding_ it. Exactly the same idea and approach.\n\n## Putting it All Together\n\nTo recap:\n1. for pairs: we found a transform $T$ such that the transform of the answer is the element-wise product of the transforms. This reduces the complexity from $O(n^2)$ to $O(n \\log(n))$ if we can transform in $O(n \\log(n))$\n2. then we derived the transform for all problem sizes and how to actually compute it in $O(n \\log(n))$\n3. next, we derived that we can compute the number of triples, quaruplets, etc. with just one transform and an element-wise power\n4. finally, we derived the inverse transform so we can convert the transformed answers to actual answers\n\nOverall we can now get the number of $k$-tuples of indices in $O(M \\log(M) + N)$ time and just $O(M)$ space. $M$ is the max value; our count vector has to be the next power of 2 in length for the recursive transform to work.\n\nAs a bonus, this is among the highest-complexity-to-code-length ratios of anything I\'ve written. Neat.\n\n## Final Thoughts\n\nWalsh-Hadamard transforms, the transform used here, and others are all part of a conceptual family: recursively defined discrete transforms. Walsh-Hadamard is the most famous for transforms related to binary operations.\n\nBut there\'s an even more famous transform that can be defined recursively like this: the discrete Fourier transform. When you use the recursive definition to write a divide-and-conquer algorithm, you get the famous Fast Fourier Transform algorithm.\n\nThis is why other explanations of this approach start with explaining FFT. But IMO it\'s not needed here, and the recusrsive structure of DFT is different enough that I don\'t think it really helps you understand this one if you haven\'t seen it before. Deriving FFT is indeed really cool though.\n\nLastly, the links I included at the beginning show how this general approach can solve related combinatorics problems with bitwise operations.\n\n# Complexity\n- Time complexity: $O(M \\log(M) + N)$, where $M$ is the max value and $N$ is the number of values. The count vectors to transform have to be the next power of 2 after the max value because the transform only works with powers of two length.\n\n- Space complexity: $O(M)$ for the count vector, transformed in place.\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n # brute force: nope\n \n # better: make a vector with the ways to make all 2**16 possible AND values,\n # in O(n**2). Then for each number, iterate through all 2**16 AND values and\n # sum up all entries where counts[a] | a&n == 0\n # Speed up: use the brilliant "masked decrement."\n # let y = ~n & ((1<<16)-1), i.e. 1s everywhere n has zeros. The most ones possible.\n # then do y = (y-1) & ~n until y is 0. Each subtracts one from the LSB of ~n.\n # It basically counts down from 11111...11_2 down to 0000...000_2, but where the 1s\n # are where they are in ~n. It\'s brilliant. This cuts down on the number of combinations\n # significantly.\n\n # The galaxy brain solution: a modified Walsh-Hadamard transformation.\n\n def transform(c: list[int], forward: bool) -> None:\n """\n Applies the linear transformation T to c in-place.\n\n T has the property T*(c $ d) == T*c : T*d where\n c and d are vectors of counts\n c $ d is the answer: (c$d)[a] is the number of index pairs\n (i, j) where i is in c, j is in d, and i & j == a\n\n T is recursively defined:\n\n T_2 = [1 1]\n [0 1]\n\n T_{2N} = T_N x T_2; where x is the direct product\n = [T_N T_N]\n [ 0 T_N]\n\n @param forward: if True, applies T to c in place.\n if False, applies inverse(T) to c in place.\n """\n\n # exploits the recursive definition of \n # T_{2N} = [T_N*firstN + T_N*nextN; T_N*nextN]\n # to compute it with divide-and-conquer. Conceptually it\'s\n # recursive, but in this case it simplifies to an\n # iterative algorithm since T_4 depends on pairs,\n # T_8 depends on groups of 4, and so on.\n\n h = 1 # half current group size\n sign = +1 if forward else -1\n while h < len(c):\n for s in range(0, len(c), 2*h): # start of each group\n for i in range(s, s+h):\n c[i] += sign*c[i+h]\n\n h *= 2\n\n most = max(nums)\n if most == 0:\n return len(nums)**3\n\n bits = ceil(log2(most)) + 1\n\n N = (1 << bits) # number of possible & results (must be a power of 2)\n ALL = N-1 # bit mask\n\n c = [0] * N # counts of each value\n for n in nums:\n c[n] += 1\n\n transform(c, forward=True)\n for i in range(N):\n c[i] **= 3\n transform(c, forward=False)\n\n return c[0]\n``` | 1 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Python 3: Galaxy Brain: Walsh-Hadamard-Like Transform, O(max*log(max) + N) Time, O(max) Space | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intro\n\nI read [this solution](https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/) by @basselbakr and was amazed, but also completely mystified by how it works.\n\nA couple of sources have some insights, but were VERY dense and IMO could be explained much better. For example, they discuss FFTs (Fast Fourier Transforms) at length, and multiplying n-digit numbers. But then skip over most of the details of this problem. They are worth reviewing though after reviewing this solution:\n* [Fast Fourier transforms and variations of it](https://csacademy.com/blog/fast-fourier-transform-and-variations-of-it)\n* [Fast Walsh Hadamard Transforms and it\'s inner workings](https://codeforces.com/blog/entry/71899)\n\n**NOTE:** Hadamard-Walsh transforms solve the `xor` version of this problem. Here we use something similar, but the matrix values are different because we want `and` instead of `xor`.\n\n# Outline\n\nHere\'s how the solution works at a high level:\n1. we start by solving the problem for 1-bit numbers\n2. knowing we have to solve the n-bit numbers case later, we look for a linear transform $T$ where $$ T(\\mathbf{c} \\$ \\mathbf{d}) = T\\mathbf{c} : T\\mathbf{d} $$ where $$ \\mathbf{c} \\$ \\mathbf{d} $$ is the solution with count vectors $\\mathbf{c}$ and $\\mathbf{d}$, and $:$ represents element-wise multiplication\n3. We find a way to write the transform for $2^n$ entries recursively using $2^{n-1}$ entries\n3. We use that recursive definition to compute the transform with divide-and-conquer in $O(M \\log(M))$ where $M$ is the max value\n4. Then we use (2) to show that the solution to this problem where we want size $k$ tuples of indices is $$ T \\mathbf{c}$$ element-wise raised to the $k$ power\n5. And finally we derive the inverse transform $T^{-1}$, which fortunately is a LOT easier once we\'ve done 1-4.\n\n# Intuition\n\nNaively we can use a brute-force algorithm: iterate over all possible triples. $O(M^3)$.\n\nIf we\'re smarter, as other solutions are, we realize that `m & n & p == (m & n) & p`: we can replace _triples_ with _tuples_.\n* get the frequency of each value\n* get the frequency of all possible `m & n` values\n* then for each value `p`, iterate over all `a == m & n` values where `m & n & p` is 0.\n\nThis is $O(M^2)$. Getting better.\n\nBut what if we could reduce the cost of getting all pairwise combinations down to $O(M \\log(M))$? Then\n* we could do all pairs in $O(M \\log(M))$\n* then combine all pairs with all singles to make triples, again in $O(M \\log(M))$\n* and so on\n\n# Approach\n\n## One-Bit Solution: Pairs\n\nSuppose we have a vector of counts $$\\mathbf{c}_2 = \\left[ \\begin{align} c_0 \\\\ c_1 \\end{align}\\right] $$. $$ \\mathbf{c}_2 $$ means we have counts for all 1 bit numbers, values $0$ and $1$. $$c_i$$ is the count of numbers with value $i$. Let $$\\mathbf{d}_2$$ be another vector of counts.\n\nWe represent the solution to "how many index pairs (i, j), where i is from $$\\mathbf{c}$$ and j is from $$\\mathbf{d}$$, have each possible bitwise `&` value?" as $$\\mathbf{c} \\$ \\mathbf{d}$$. Because answers are where the money is at.\n\nFor the 1-bit case the answer is pretty easy:\n* to get a bitwise `&` of 0: any zero in $$\\mathbf{c}$$, and any number in $$\\mathbf{d}$$. Or a one in $$\\mathbf{c}$$ and a zero value from $$\\mathbf{d}$$.\n * $$c_0 d_0 + c_0 d_1 + c_1 d_0$$\n* to get a bitwise `&` of 1: both numbers have to be 1\n * $$c_1 d_1$$\n\nThis gives us $$ \\mathbf{c}_2 = \\left[ \\begin{matrix} c_0 d_0 + c_0 d_1 + c_1 d_0 \\\\ c_1 d_1 \\end{matrix} \\right] $$\n\n## Linear Transform: Pairs\n\nThe above approach extends to n-bit numbers, but it involves $O(2^n)$ calculations to get the values in each row.\n\nInstead, we look for a linear transform where we\'ll do the following:\n* transform $$\\mathbf{c}$$ and $$\\mathbf{d}$$ with $T$\n* do an element-wise product of $$T\\mathbf{c} : T\\mathbf{d}$$. This will give us the transformed answer, i.e. $$T(\\mathbf{c} \\$ \\mathbf{d})$$\n* apply the inverse transform, $T^{-1}$, to get $$\\mathbf{c} \\$ \\mathbf{d}$$\n\nSo we let $$ T_2 = \\left[ \\begin{matrix} t_0 & t_1 \\\\ t_2 & t_3 \\end{matrix} \\right]$$ and solve for the entries so that $$ T_2(\\mathbf{c}_2 \\$ \\mathbf{d}_2) = T_2 \\mathbf{c}_2 : T_2 \\mathbf{d}_2 $$.\n\nWriting this out gives us\n\n$$ \\left[ \\begin{matrix} t_0 & t_1 \\\\ t_2 & t_3 \\end{matrix} \\right] \\, \\left[ \\begin{matrix} c_0 d_0 + c_0 d_1 + c_1 d_0 \\\\ c_1 d_1 \\end{matrix} \\right] = \\left[ \\begin{matrix} (t_0 c_0 + t_1 c_1) \\cdot (t_0 d_0 + t_1 c_1) \\\\ (t_2 c_0 + t_3 c_1) \\cdot (t_2 d_0 + t_3 c_1) \\end{matrix} \\right] $$\n\nTo review, the left is the transform of the solution, and the right is the element-wise product of transforms.\n\nNow we compare the coefficients of the powers for $$ c_i d_j $$ combinations, which have to match so the solution works for all possible counts. The algebra is tedious, but you can trust me when I saw you can solve the equations to get the following:\n* each $t_i$ is 0 or 1\n* if $t_0$ is 1, then $t_1$ cannot be 0, same for $t_2$ and $t_3$, respectively\n\nThis means that both rows of $$T_2$$ have to be one of the following:\n* $$\\left[ 0, 0 \\right]$$\n* $$\\left[ 1, 1 \\right]$$\n* $$\\left[ 0, 1 \\right]$$\n\nFinally, we realize that our plan above is to apply $T^{-1}$ at the end. This means we need $T$ to be full rank. Therefore we can\'t have $$\\left[ 0, 0 \\right]$$ as a row, and the columns must be linearly independent.\n\nSo we discover that $$T$$ must either be $$\\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right]$$ or $$\\left[ \\begin{matrix} 0 & 1 \\\\ 1 & 1 \\end{matrix} \\right]$$. It turns out that both work; the right one is the row flipped version of the left. They both work because we need leftSide = rightSide in the equation, but the order of the rows doesn\'t matter. So from that two-fold degree of freedom arises a size-2 family of $T_2$ matrices that both work. I suspect a situation with three rows would give 3!=6 different $T_3$ matrices.\n\nAnyway, we\'ll use the one on the left because it\'s more intuitive in the next section.\n\n## Finding the Transform for 2-bit Numbers from the 1-bit Transform\n\nNow we enter the most complicated part of the problem, but I\'ll do my best.\n\nWe now want to solve the problem for 2-bit numbers, 0..3. The goal is to write the solution in terms of the 1-bit numbers. This will show a recursive pattern where the solution for n-bit numbers depends on the the solutions for n-1-bit numbers.\n\nFor 2-bit numbers we have counts $$\\mathbf{c}_4 = \\left[ \\begin{matrix} c_{00} \\\\ c_{01} \\\\ c_{10} \\\\ c_{11} \\end{matrix} \\right]$$. Same with $$\\mathbf{d}_4$$. I\'ve written the subscripts in binary.\n\nTo simplify this, notice that we have two copies of the 1-bit subproblem:\n1. the top two entries, 0 and 1, where the new second bit is 0\n2. the bottom two entries, 0 and 1, where the new second bit is 1\n\nSo I\'ll rewrite it using the new vectors $$ \\mathbf{c}_2^0 = \\left[ \\begin{matrix} c_{00} \\\\ c_{01} \\end{matrix} \\right]$$ and $$ \\mathbf{c}_2^1 = \\left[ \\begin{matrix} c_{10} \\\\ c_{11} \\end{matrix} \\right]$$. Now we get $$\\mathbf{c}_4$$ in the new notation: $$\\left[ \\begin{matrix} \\mathbf{c}_2^0 \\\\ \\mathbf{c}_2^1 \\end{matrix} \\right]$$.\n\nThis temporarily makes it more complicated. But it also lets us see that the result is this: $$\\mathbf{c}_4 \\$ \\mathbf{d}_4 = \\left[ \\begin{matrix} \\mathbf{c}_2^0 \\$\\mathbf{d}_2^0 + \\mathbf{c}_2^1 \\$\\mathbf{d}_2^0 + \\mathbf{c}_2^0 \\$\\mathbf{d}_2^1 \\\\ \\mathbf{c}_2^1 \\$\\mathbf{d}_2^1 \\end{matrix} \\right]$$. The terms in the top row are all combinations that give us a 0 in the 2s digit of the `&` result, and the bottom row is the only combination that gives us a 1 in the 2s digit of the `&` result. **This is the same pattern as before for the 1-bit number**.\n\nHere\'s the transformed version:\n\n$$ T_4(\\mathbf{c}_4 \\$ \\mathbf{d}_4) = \\left[ \\begin{matrix} t_0 (T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^1) + t_1 (T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^1) \\\\ t_2 (T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^0 + T_2 \\mathbf{c}_2^0 : T_2 \\mathbf{d}_2^1) + t_3 (T_2 \\mathbf{c}_2^1 : T_2 \\mathbf{d}_2^1) \\end{matrix} \\right] = T_4 \\mathbf{c}_4 : T_4 \\mathbf{d}_4 = \\left[ \\begin{matrix} (t_0 T_2 \\mathbf{c}_2^0 + t_1 T_2 \\mathbf{c}_2^1) : (t_0 T_2 \\mathbf{d}_2^0 + t_1 T_2 \\mathbf{d}_2^1) \\\\ (t_2 T_2 \\mathbf{c}_2^0 + t_3 T_2 \\mathbf{c}_2^1) : (t_2 T_2 \\mathbf{d}_2^0 + t_3 T_2 \\mathbf{d}_2^1) \\end{matrix}\\right]$$ \n\nWhat we\'ve done is rewrite the 2-bit solution in terms of the 1-bit solutions. I know this looks absolutely horrifying. But it\'s a detailed way to show you that this is the same pattern as the 1-bit solution:\n* before we had $c_i$ and $d_i$, now we have $T_2 \\mathbf{c}_2^i$ and $T_2 \\mathbf{d}_2^i$\n* after comparing by parts, the $t_0 \\, ... \\, t_3$ have the same relationships and therefore the the same $t_0 = t_1 = t_3 = 1$ and $t_2 = 0$ values.\n\nFinally, plugging in the $t_i$ values shows us that\n$$ T_4 \\mathbf{c}_4 = \\left[ \\begin{matrix} t_0 T_2 \\mathbf{c}_2^0 + t_1 T_2 \\mathbf{c}_2^1 \\\\ t_2 T_2 \\mathbf{c}_2^0 + t_3 T_2 \\mathbf{c}_2^1 \\end{matrix}\\right] = \\left[ \\begin{matrix} T_2 \\mathbf{c}_2^0 + T_2 \\mathbf{c}_2^1 \\\\ T_2 \\mathbf{c}_2^1 \\end{matrix}\\right]$$\nand thus\n$$T_4 = \\left[ \\begin{matrix} T_2 & T_2 \\\\ 0 & T_2 \\end{matrix} \\right] \\equiv T_2 \\otimes \\left[ \\begin{matrix} 1 & 1 \\\\ 0 & 1 \\end{matrix} \\right]$$\n\nSo the pattern for the 2-bit transform is\n* get the transform of the 1-bit problems, the first half and the second half\n* add the second half\'s trasnform to the first half\n\n## Recursion: Finding the n-bit Transform\n\nFor the 1-bit transform, we added the second half of the 2-entry vector, $c_1$, to the first half.\n\nFor the 2-bit transform, we added the second half of the transformed 4-entry vector, $\\mathbf{c}_2^1$, to the first half\n\nFor each next bit we follow the pattern; you can derive it above for each level by by replacing the _4/_2 with _8/_4, _16/_8, etc. Take the transform of the two halves, and add the second half to the first half.\n\nThe pattern in the $T$ matrices is $$ T_{2N} = \\left[ \\begin{matrix} T_N & T_N \\\\ 0 & T_N \\end{matrix} \\right]$$\n\n**NOTE:** this is similar to the Walsh-Hadamard transform. Same concept of a recursively defined matrix. Just different values. This solves `&` combinations, while Walsh-Hadamard solves `^` combinations.\n\n## Algorithm for n-bit Transform in O(n*log(n))\n\nThe pseudocode is actually in the prior section already! The transform for $T_N$ needs the transform of the first $N/2$ and second $N/2$ with $T_{N/2}$. That in turn needs transforms of groups of $N/4$ elements with $T_{N/4}$, and so on. So we\n* first apply T_2 to pairs of elements\n* then in groups of 4, add the now-transformed second half to the first half. This applies $T_4$ to each group of 4\n* repeat in groups of 8 for $T_8$, then 16 for $T_{16}$, and so on\n\nEach group size is a scan over all N elements. We do a scan for group sizes 2, 4, 8, etc. which is log(N) scans. So $O(N \\log(N))$ total!\n\n**Note:** this is basically the derivation of the fast Walsh-Hadamard transform, just for a matrix with slightly different entries.\n\n## (Transformed) Solutions for Pairs and Triples\n\nLet the number of pairs with each `&` result be $$\\mathbf{p}$$. Then $$T \\mathbf{p} = T (\\mathbf{c} \\$ \\mathbf{c}) = T\\mathbf{c} : T\\mathbf{c}$$.\n\nFor triples, we can find the number of combinations of pairs and singles with each `&` result. Let\'s call that $$\\mathbf{t}$$. Same situation as before:\n$$ T \\mathbf{t} = T(\\mathbf{p} \\$ \\mathbf{c}) = T \\mathbf{p} : T \\mathbf{c} = T \\mathbf{c} : T \\mathbf{c} : T \\mathbf{c}$$\n\nIf you keep going for quadruplets, quintuplets, etc. you find that the number of groups of `k` indices for each bitwise `&` is $$T \\mathbf{c}$$ raised element-wise to the power of `k`!\n\n## The Final Step: Inverse Transform\n\nThe last part is to be able to do the invese transform: we need $\\mathbf{t}$, not $T \\mathbf{t}$ from the prior section.\n\nFortunately it\'s much easier to derive the inverse transform than the forward one.\n\nFrom the formula for 2x2 matrix inverses, $$T_2^{-1} = \\left[ \\begin{matrix} 1 & -1 \\\\ 0 &1 \\end{matrix} \\right]$$.\n\nFor $$T_4 = \\left[ \\begin{matrix} T_2 & T_2 \\\\ 0 & T_2 \\end{matrix} \\right]$$, the matrix inverse is $$T_4^{-1} = \\left[ \\begin{matrix} T_2^{-1} & -T_2^{-1} \\\\ 0 & T_2^{-1} \\end{matrix} \\right]$$.\n\nFor $T_{2N}$, the pattern continues: $$T_{2N}^{-1} = \\left[ \\begin{matrix} T_{N}^{-1} & -T_{N}^{-1} \\\\ 0 & T_{N}^{-1} \\end{matrix} \\right]$$\n\nIf you look closely at the prior line, this is _almost_ exactly the same thing as the forward transform. There\'s just a minus sign instead of a plus sign in the upper-right entry. So the fast inverse Walsh-Hadamard-like transform _subtracts_ the second half instead of _adding_ it. Exactly the same idea and approach.\n\n## Putting it All Together\n\nTo recap:\n1. for pairs: we found a transform $T$ such that the transform of the answer is the element-wise product of the transforms. This reduces the complexity from $O(n^2)$ to $O(n \\log(n))$ if we can transform in $O(n \\log(n))$\n2. then we derived the transform for all problem sizes and how to actually compute it in $O(n \\log(n))$\n3. next, we derived that we can compute the number of triples, quaruplets, etc. with just one transform and an element-wise power\n4. finally, we derived the inverse transform so we can convert the transformed answers to actual answers\n\nOverall we can now get the number of $k$-tuples of indices in $O(M \\log(M) + N)$ time and just $O(M)$ space. $M$ is the max value; our count vector has to be the next power of 2 in length for the recursive transform to work.\n\nAs a bonus, this is among the highest-complexity-to-code-length ratios of anything I\'ve written. Neat.\n\n## Final Thoughts\n\nWalsh-Hadamard transforms, the transform used here, and others are all part of a conceptual family: recursively defined discrete transforms. Walsh-Hadamard is the most famous for transforms related to binary operations.\n\nBut there\'s an even more famous transform that can be defined recursively like this: the discrete Fourier transform. When you use the recursive definition to write a divide-and-conquer algorithm, you get the famous Fast Fourier Transform algorithm.\n\nThis is why other explanations of this approach start with explaining FFT. But IMO it\'s not needed here, and the recusrsive structure of DFT is different enough that I don\'t think it really helps you understand this one if you haven\'t seen it before. Deriving FFT is indeed really cool though.\n\nLastly, the links I included at the beginning show how this general approach can solve related combinatorics problems with bitwise operations.\n\n# Complexity\n- Time complexity: $O(M \\log(M) + N)$, where $M$ is the max value and $N$ is the number of values. The count vectors to transform have to be the next power of 2 after the max value because the transform only works with powers of two length.\n\n- Space complexity: $O(M)$ for the count vector, transformed in place.\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n # brute force: nope\n \n # better: make a vector with the ways to make all 2**16 possible AND values,\n # in O(n**2). Then for each number, iterate through all 2**16 AND values and\n # sum up all entries where counts[a] | a&n == 0\n # Speed up: use the brilliant "masked decrement."\n # let y = ~n & ((1<<16)-1), i.e. 1s everywhere n has zeros. The most ones possible.\n # then do y = (y-1) & ~n until y is 0. Each subtracts one from the LSB of ~n.\n # It basically counts down from 11111...11_2 down to 0000...000_2, but where the 1s\n # are where they are in ~n. It\'s brilliant. This cuts down on the number of combinations\n # significantly.\n\n # The galaxy brain solution: a modified Walsh-Hadamard transformation.\n\n def transform(c: list[int], forward: bool) -> None:\n """\n Applies the linear transformation T to c in-place.\n\n T has the property T*(c $ d) == T*c : T*d where\n c and d are vectors of counts\n c $ d is the answer: (c$d)[a] is the number of index pairs\n (i, j) where i is in c, j is in d, and i & j == a\n\n T is recursively defined:\n\n T_2 = [1 1]\n [0 1]\n\n T_{2N} = T_N x T_2; where x is the direct product\n = [T_N T_N]\n [ 0 T_N]\n\n @param forward: if True, applies T to c in place.\n if False, applies inverse(T) to c in place.\n """\n\n # exploits the recursive definition of \n # T_{2N} = [T_N*firstN + T_N*nextN; T_N*nextN]\n # to compute it with divide-and-conquer. Conceptually it\'s\n # recursive, but in this case it simplifies to an\n # iterative algorithm since T_4 depends on pairs,\n # T_8 depends on groups of 4, and so on.\n\n h = 1 # half current group size\n sign = +1 if forward else -1\n while h < len(c):\n for s in range(0, len(c), 2*h): # start of each group\n for i in range(s, s+h):\n c[i] += sign*c[i+h]\n\n h *= 2\n\n most = max(nums)\n if most == 0:\n return len(nums)**3\n\n bits = ceil(log2(most)) + 1\n\n N = (1 << bits) # number of possible & results (must be a power of 2)\n ALL = N-1 # bit mask\n\n c = [0] * N # counts of each value\n for n in nums:\n c[n] += 1\n\n transform(c, forward=True)\n for i in range(N):\n c[i] **= 3\n transform(c, forward=False)\n\n return c[0]\n``` | 1 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
[Python3] hash table | triples-with-bitwise-and-equal-to-zero | 0 | 1 | \n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans \n``` | 4 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
[Python3] hash table | triples-with-bitwise-and-equal-to-zero | 0 | 1 | \n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans \n``` | 4 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Trie based approach | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse trie to count the value values effectively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTrie carries and extra variable "count" to count the number of values are under it.\n\n\ncountTriplets Method:\nmemo: A dictionary to memoize the count of pairs (bitwise AND of two numbers).\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2 * M)\n\nN - length of nums. \nM - length of binary bit - say 16 in this case, so it is a constant value and the overall complexity is O(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N^2 * M)\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums):\n # Initialize a defaultdict to memoize bitwise AND counts\n memo = defaultdict(int)\n # Find the maximum length of binary representation among all numbers\n maxVal = len(bin(max(nums))) - 1\n\n # Build the memo dictionary with counts of bitwise AND results\n for first in nums:\n for second in nums:\n memo[first & second] += 1\n\n # Initialize a Trie data structure\n head = Trie()\n\n # Function to reverse and pad a binary representation with zeros\n def getReverseBin(num):\n bin_val = bin(num)[2:][::-1]\n bin_val += (maxVal - len(bin_val)) * "0"\n return bin_val\n\n # Build Trie using the memoized bitwise AND counts\n for key, value in memo.items():\n node = head\n bin_val = getReverseBin(key)\n node.count += value\n\n # Traverse the Trie, updating counts for each node\n for string in bin_val:\n if string not in node.data:\n node.data[string] = Trie()\n node = node.data[string]\n node.count += value\n node.end = True\n\n # Dynamic Programming function to count triplets based on Trie\n def getCount(nodes, s, remaining):\n if remaining == 0:\n count = 0\n for node in nodes:\n count += node.count\n return count\n elif not s:\n return 0\n else:\n if s[0] == ".":\n temp = []\n for node in nodes:\n temp.extend(node.data.values())\n return getCount(temp, s[1:], remaining)\n else:\n temp = []\n for node in nodes:\n if "0" not in node.data:\n continue\n temp.append(node.data["0"])\n return getCount(temp, s[1:], remaining-1)\n\n ans = 0\n\n # Iterate over each number in the input array\n for num in nums:\n # Convert the binary representation, replacing "0" with "."\n bin_val = getReverseBin(num)\n bin_val = bin_val.replace("0", ".")\n # Count triplets using the Trie and update the result\n remaining = bin_val.count("1")\n ans += getCount([head], bin_val, remaining)\n\n return ans\n\n\nclass Trie:\n def __init__(self):\n # Initialize Trie node with data, count, and end indicator\n self.data = {}\n self.count = 0\n self.end = False\n\n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Trie based approach | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse trie to count the value values effectively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTrie carries and extra variable "count" to count the number of values are under it.\n\n\ncountTriplets Method:\nmemo: A dictionary to memoize the count of pairs (bitwise AND of two numbers).\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2 * M)\n\nN - length of nums. \nM - length of binary bit - say 16 in this case, so it is a constant value and the overall complexity is O(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N^2 * M)\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums):\n # Initialize a defaultdict to memoize bitwise AND counts\n memo = defaultdict(int)\n # Find the maximum length of binary representation among all numbers\n maxVal = len(bin(max(nums))) - 1\n\n # Build the memo dictionary with counts of bitwise AND results\n for first in nums:\n for second in nums:\n memo[first & second] += 1\n\n # Initialize a Trie data structure\n head = Trie()\n\n # Function to reverse and pad a binary representation with zeros\n def getReverseBin(num):\n bin_val = bin(num)[2:][::-1]\n bin_val += (maxVal - len(bin_val)) * "0"\n return bin_val\n\n # Build Trie using the memoized bitwise AND counts\n for key, value in memo.items():\n node = head\n bin_val = getReverseBin(key)\n node.count += value\n\n # Traverse the Trie, updating counts for each node\n for string in bin_val:\n if string not in node.data:\n node.data[string] = Trie()\n node = node.data[string]\n node.count += value\n node.end = True\n\n # Dynamic Programming function to count triplets based on Trie\n def getCount(nodes, s, remaining):\n if remaining == 0:\n count = 0\n for node in nodes:\n count += node.count\n return count\n elif not s:\n return 0\n else:\n if s[0] == ".":\n temp = []\n for node in nodes:\n temp.extend(node.data.values())\n return getCount(temp, s[1:], remaining)\n else:\n temp = []\n for node in nodes:\n if "0" not in node.data:\n continue\n temp.append(node.data["0"])\n return getCount(temp, s[1:], remaining-1)\n\n ans = 0\n\n # Iterate over each number in the input array\n for num in nums:\n # Convert the binary representation, replacing "0" with "."\n bin_val = getReverseBin(num)\n bin_val = bin_val.replace("0", ".")\n # Count triplets using the Trie and update the result\n remaining = bin_val.count("1")\n ans += getCount([head], bin_val, remaining)\n\n return ans\n\n\nclass Trie:\n def __init__(self):\n # Initialize Trie node with data, count, and end indicator\n self.data = {}\n self.count = 0\n self.end = False\n\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
[Python3] 5 LOC; 3 sum variation, O(N**2) | triples-with-bitwise-and-equal-to-zero | 1 | 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)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def countTriplets(self, A: List[int]) -> int:\n pairs, N = defaultdict(int), len(A)\n for i in range(N):\n for j in range(N):\n pairs[A[i]&A[j]] += 1\n return sum(pairs[k] if A[i] & k == 0 else 0 for k in pairs for i in range(N))\n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
[Python3] 5 LOC; 3 sum variation, O(N**2) | triples-with-bitwise-and-equal-to-zero | 1 | 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)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def countTriplets(self, A: List[int]) -> int:\n pairs, N = defaultdict(int), len(A)\n for i in range(N):\n for j in range(N):\n pairs[A[i]&A[j]] += 1\n return sum(pairs[k] if A[i] & k == 0 else 0 for k in pairs for i in range(N))\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
python dp top down | triples-with-bitwise-and-equal-to-zero | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n @functools.lru_cache(None)\n def dp(n, s):\n if n == 3:\n if s == 0:\n return 1\n return 0\n ans = 0\n for j in range(len(nums)):\n ans += dp(n+1, nums[j] & s)\n return ans\n \n ans = 0\n for i in range(len(nums)):\n ans += dp(1, nums[i])\n return ans\n\n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
python dp top down | triples-with-bitwise-and-equal-to-zero | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n @functools.lru_cache(None)\n def dp(n, s):\n if n == 3:\n if s == 0:\n return 1\n return 0\n ans = 0\n for j in range(len(nums)):\n ans += dp(n+1, nums[j] & s)\n return ans\n \n ans = 0\n for i in range(len(nums)):\n ans += dp(1, nums[i])\n return ans\n\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Linear Algebra and Dimensional Reduction | Commented and Explained | O(N) time and space | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get this problem would really suck if you don\'t have linear algebra background. This is because you can take the problem, which naively runs in O(N^3), and reduce to O(N) if you are clever about it. To pull this off we need to realize that we can consider this problem as the determinant of the submatrices of a bit masked version of the binary values of our nums array. This is not a simple insight! I only came to it intuitively after setting up the problem in a different fashion and from there realized the striking symmetry of the problem; I leave in references to some others work with the venn diagram approach, who may or may not have realized the matrix space they were working in as a nod to other approaches as well. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo set this up, start by first getting the binary form of all values in nums and storing them, along with the longest length you encounter on the way. \n\nFrom there, loop through your binary value strings and find the extension needed at each point as the difference of max length and this length. \nAppend to extra bits this extension as another row in our overall extra bits matrix. \n\nAt the end of this, we will have a matrix not well seen but implicitly defined as the length of our extra bits and the length of the first item in our extra bits array. \n\nWe know make a cols to rows activated mapping where we will store which rows by index are activated by which columns in our extra bits matrix. We will find these in col major order so we progress in the fashion of linear algebra over the space, left to right and top to bottom. \n\nAs we do so, if we find that we have a \'1\' in our extra bits for this row and this column, we are to add this row to our mapping for this column. \n\nFinally, we can set up a venn diagram intersection, as stated in other posts (this is really a listing of the determinant based findings of the sub matrices in our overall matrix of size row by row from above, but that\'s a separate post entirely) \n\nSet a count equal to 0. We are technically counting the over counting of the total size of our row by row matrix of extension of bits. \n\nLoop in col major order and as you do \n- If you have rows activated for this column \n - we\'ve definitely overcounted by any here on 3 times occassions \n - Increment count by the number of rows cubed \n - then for prior column in range of this column up to but not at 0 \n - consider each previous calculation we have made of the determinant (each prior entry in the venn diagram at prior column)\n - calculate the number of intersections of the previous entry with the current entry of cols to rows activated at col as the bitwise and operation \n - if this intersection is not 0 \n - we also overcount here, we\'ll need to increase count \n - but! this is a determinant, and submatrix considerations must come into play. This was a positive value if the prior column is even, otherwise it is a negative value. The value of the increment is as expected, the length of the intersection cubed for our 3 loop consideration normally \n - Afterwards, whatever the intersection was, we will want to account for it on the next loop, so add it to the prior columns successor (prior column + 1) in the determinant calculations (venn diagram) \n - after considering all prior columns, the determinant calculation at index 1 will need to also have the rows activated here appeneded as well since we considered them as well \n\nWhen the loop finishes, take the size of our matrix cubed and subtract from it the amount we overcount in the processing. This is our final answer. \n\n# Complexity\n- Time complexity : O(N) \n - Take O(N) to build all binary nums \n - Take O(N) to build your extra bits \n - The largest size possible for the matrix dimensions col major order outer loop must be max length - 0 -> aka max length\n - The max length considerable in the problem is 16, based on 2^16 \n - So the max we can have on our first extension is when it is 2^8\n - This would have us add 16 and 8 to get a size of 24 \n - Row unfortunately can run all the way to 1000, so we have at worst a matrix of size 1000 by 1000, aka O(N) \n - Similarly we loop over cols, at worst 24 \n - and then do a sub loop of at worst 23 \n - but then have an inner loop of at worst N \n - which sets our max at O(N) \n - All told then, we have a run time of O(N) \n\n- Space complexity : O(N) \n - Store N binary values\n - Store N extra bits \n - Store 24 * N items in our cols activated \n - Store 24 * N items in our venn diagram intersection perhaps \n - All O(N) \n\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: \'List[int]\') -> \'int\' :\n # get binary string forms of the values \n binary_values = [] \n # and the maximal length possible \n max_length = 0 \n # by looping over nums and building as you go \n for num in nums : \n binary_values.append(bin(num)[2:])\n max_length = max(max_length, len(binary_values[-1]))\n \n # figure out how many extra bits you\'ll need for a bit masked matrix \n extra_bits = [] \n # by looping over your binary values \n for binary_value in binary_values : \n # determining any needed extensions \n extension = max_length - len(binary_value)\n # and extending it as needed \n extra_bits.append(\'0\'*extension + binary_value)\n \n # the length of the set up is your number of rows, and your initial is the number of cols \n matrix_dimensions = [len(extra_bits), len(extra_bits[0])]\n # use this to determine mapping of column to rows activated in the matrix \n cols_to_rows_activated = collections.defaultdict(set) \n # by looping in col major order \n for col in range(matrix_dimensions[1]) : \n for row in range(matrix_dimensions[0]) :\n # and if you have a value there \n if extra_bits[row][col] == "1" :\n # updating appropriately \n cols_to_rows_activated[col].add(row)\n # we could do the above since all cells will go up to at least cols positioning \n # as everything after that is longer overall. This lets us update without worries \n # we now build a venn diagram intersectioni using some linear algebra in the work \n venn_diagram_intersection = collections.defaultdict(list) \n # where we are going to use determinant basically in our evaluation \n count = 0 \n # col major order looping \n for col in range(matrix_dimensions[1]) :\n # if we have a length here that is not 0 -> some rows activated \n if len(cols_to_rows_activated[col]) != 0 : \n # update count by this amount cubed \n count += len(cols_to_rows_activated[col])**3\n # consider prior column entries up to the first but not including it \n for prior_col in range(col, 0, -1) : \n # get the previous entries there at prior column \n for previous_entry in venn_diagram_intersection[prior_col] : \n # find value of intersection. If not zero \n intersection = previous_entry & cols_to_rows_activated[col]\n if len(intersection) != 0 : \n # based on corresponding matrix position, you add or subtract \n # the appropriate valuation of the length of intersection cubed \n count += ((-1)**prior_col)*(len(intersection)) ** 3 \n # and be sure to update the priors successor based on this \n venn_diagram_intersection[prior_col + 1].append(intersection)\n # after considering all prior columns, be sure to note that for the final \n # entry we now must add the valuation of the cols to rows activated at col \n venn_diagram_intersection[1].append(cols_to_rows_activated[col])\n # return you matrix dimensions of the row cubed - count of total \n # this reduces us to the proper amount of values based on the cubing process \n # where we would normally consider num for num in nums 3 separate times \n return matrix_dimensions[0]**3 - count \n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Linear Algebra and Dimensional Reduction | Commented and Explained | O(N) time and space | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get this problem would really suck if you don\'t have linear algebra background. This is because you can take the problem, which naively runs in O(N^3), and reduce to O(N) if you are clever about it. To pull this off we need to realize that we can consider this problem as the determinant of the submatrices of a bit masked version of the binary values of our nums array. This is not a simple insight! I only came to it intuitively after setting up the problem in a different fashion and from there realized the striking symmetry of the problem; I leave in references to some others work with the venn diagram approach, who may or may not have realized the matrix space they were working in as a nod to other approaches as well. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo set this up, start by first getting the binary form of all values in nums and storing them, along with the longest length you encounter on the way. \n\nFrom there, loop through your binary value strings and find the extension needed at each point as the difference of max length and this length. \nAppend to extra bits this extension as another row in our overall extra bits matrix. \n\nAt the end of this, we will have a matrix not well seen but implicitly defined as the length of our extra bits and the length of the first item in our extra bits array. \n\nWe know make a cols to rows activated mapping where we will store which rows by index are activated by which columns in our extra bits matrix. We will find these in col major order so we progress in the fashion of linear algebra over the space, left to right and top to bottom. \n\nAs we do so, if we find that we have a \'1\' in our extra bits for this row and this column, we are to add this row to our mapping for this column. \n\nFinally, we can set up a venn diagram intersection, as stated in other posts (this is really a listing of the determinant based findings of the sub matrices in our overall matrix of size row by row from above, but that\'s a separate post entirely) \n\nSet a count equal to 0. We are technically counting the over counting of the total size of our row by row matrix of extension of bits. \n\nLoop in col major order and as you do \n- If you have rows activated for this column \n - we\'ve definitely overcounted by any here on 3 times occassions \n - Increment count by the number of rows cubed \n - then for prior column in range of this column up to but not at 0 \n - consider each previous calculation we have made of the determinant (each prior entry in the venn diagram at prior column)\n - calculate the number of intersections of the previous entry with the current entry of cols to rows activated at col as the bitwise and operation \n - if this intersection is not 0 \n - we also overcount here, we\'ll need to increase count \n - but! this is a determinant, and submatrix considerations must come into play. This was a positive value if the prior column is even, otherwise it is a negative value. The value of the increment is as expected, the length of the intersection cubed for our 3 loop consideration normally \n - Afterwards, whatever the intersection was, we will want to account for it on the next loop, so add it to the prior columns successor (prior column + 1) in the determinant calculations (venn diagram) \n - after considering all prior columns, the determinant calculation at index 1 will need to also have the rows activated here appeneded as well since we considered them as well \n\nWhen the loop finishes, take the size of our matrix cubed and subtract from it the amount we overcount in the processing. This is our final answer. \n\n# Complexity\n- Time complexity : O(N) \n - Take O(N) to build all binary nums \n - Take O(N) to build your extra bits \n - The largest size possible for the matrix dimensions col major order outer loop must be max length - 0 -> aka max length\n - The max length considerable in the problem is 16, based on 2^16 \n - So the max we can have on our first extension is when it is 2^8\n - This would have us add 16 and 8 to get a size of 24 \n - Row unfortunately can run all the way to 1000, so we have at worst a matrix of size 1000 by 1000, aka O(N) \n - Similarly we loop over cols, at worst 24 \n - and then do a sub loop of at worst 23 \n - but then have an inner loop of at worst N \n - which sets our max at O(N) \n - All told then, we have a run time of O(N) \n\n- Space complexity : O(N) \n - Store N binary values\n - Store N extra bits \n - Store 24 * N items in our cols activated \n - Store 24 * N items in our venn diagram intersection perhaps \n - All O(N) \n\n\n# Code\n```\nclass Solution:\n def countTriplets(self, nums: \'List[int]\') -> \'int\' :\n # get binary string forms of the values \n binary_values = [] \n # and the maximal length possible \n max_length = 0 \n # by looping over nums and building as you go \n for num in nums : \n binary_values.append(bin(num)[2:])\n max_length = max(max_length, len(binary_values[-1]))\n \n # figure out how many extra bits you\'ll need for a bit masked matrix \n extra_bits = [] \n # by looping over your binary values \n for binary_value in binary_values : \n # determining any needed extensions \n extension = max_length - len(binary_value)\n # and extending it as needed \n extra_bits.append(\'0\'*extension + binary_value)\n \n # the length of the set up is your number of rows, and your initial is the number of cols \n matrix_dimensions = [len(extra_bits), len(extra_bits[0])]\n # use this to determine mapping of column to rows activated in the matrix \n cols_to_rows_activated = collections.defaultdict(set) \n # by looping in col major order \n for col in range(matrix_dimensions[1]) : \n for row in range(matrix_dimensions[0]) :\n # and if you have a value there \n if extra_bits[row][col] == "1" :\n # updating appropriately \n cols_to_rows_activated[col].add(row)\n # we could do the above since all cells will go up to at least cols positioning \n # as everything after that is longer overall. This lets us update without worries \n # we now build a venn diagram intersectioni using some linear algebra in the work \n venn_diagram_intersection = collections.defaultdict(list) \n # where we are going to use determinant basically in our evaluation \n count = 0 \n # col major order looping \n for col in range(matrix_dimensions[1]) :\n # if we have a length here that is not 0 -> some rows activated \n if len(cols_to_rows_activated[col]) != 0 : \n # update count by this amount cubed \n count += len(cols_to_rows_activated[col])**3\n # consider prior column entries up to the first but not including it \n for prior_col in range(col, 0, -1) : \n # get the previous entries there at prior column \n for previous_entry in venn_diagram_intersection[prior_col] : \n # find value of intersection. If not zero \n intersection = previous_entry & cols_to_rows_activated[col]\n if len(intersection) != 0 : \n # based on corresponding matrix position, you add or subtract \n # the appropriate valuation of the length of intersection cubed \n count += ((-1)**prior_col)*(len(intersection)) ** 3 \n # and be sure to update the priors successor based on this \n venn_diagram_intersection[prior_col + 1].append(intersection)\n # after considering all prior columns, be sure to note that for the final \n # entry we now must add the valuation of the cols to rows activated at col \n venn_diagram_intersection[1].append(cols_to_rows_activated[col])\n # return you matrix dimensions of the row cubed - count of total \n # this reduces us to the proper amount of values based on the cubing process \n # where we would normally consider num for num in nums 3 separate times \n return matrix_dimensions[0]**3 - count \n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python - 5 lines, 3 sum variation, O(N**2) | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\nStore pairs of indices AND results and then compare each index value with stored values, storing should record number of repeats per AND value\n\n# Approach\nNested loop everything with everything (quadratic), count how many times each and sum repeats, then run again loop for every value check if there is stored AND sum that combines to 0, if so increase result with number of repeats of that AND sum.\n\n# Complexity\n- Time complexity:\nO(N**2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def countTriplets(self, A: List[int]) -> int:\n pairs, N = defaultdict(int), len(A)\n for i in range(N):\n for j in range(N):\n pairs[A[i]&A[j]] += 1\n return sum(pairs[k] if A[i] & k == 0 else 0 for k in pairs for i in range(N))\n\n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Python - 5 lines, 3 sum variation, O(N**2) | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Intuition\nStore pairs of indices AND results and then compare each index value with stored values, storing should record number of repeats per AND value\n\n# Approach\nNested loop everything with everything (quadratic), count how many times each and sum repeats, then run again loop for every value check if there is stored AND sum that combines to 0, if so increase result with number of repeats of that AND sum.\n\n# Complexity\n- Time complexity:\nO(N**2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def countTriplets(self, A: List[int]) -> int:\n pairs, N = defaultdict(int), len(A)\n for i in range(N):\n for j in range(N):\n pairs[A[i]&A[j]] += 1\n return sum(pairs[k] if A[i] & k == 0 else 0 for k in pairs for i in range(N))\n\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python3 🐍 concise solution beats 99% | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans \n``` | 0 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 12
**Explanation:** We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2
**Example 2:**
**Input:** nums = \[0,0,0\]
**Output:** 27
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < 216` | null |
Python3 🐍 concise solution beats 99% | triples-with-bitwise-and-equal-to-zero | 0 | 1 | # Code\n```\nclass Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans \n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python Top Down/ Bottom Up Solution for reference | minimum-cost-for-tickets | 0 | 1 | 1. Top Down method\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n # Variable definitions\n # dp: stores results from index , key till len(n)\n # idx: starting index from which we are calculating\n # res: storing the final results\n # tillday: day at which we have to buy ticket again\n # tidx: temprory index to skip through all days ahead \n # which are included in the ticket \n self.dp = defaultdict(int)\n def rec(days,idx):\n if(idx >= len(days)): return 0;\n elif(self.dp[idx] != 0 ): return self.dp[idx]\n nonlocal costs\n res = pow(2,31)\n #one day pass\n res = min(res,costs[0]+rec(days,idx+1))\n \n #one week pass\n tillday ,tidx = days[idx]+7 , idx\n while( tidx < len(days) and days[tidx] < tillday ):\n tidx+=1\n res = min(res,costs[1]+rec(days,tidx))\n \n #one month pass\n tillday , tidx = days[idx]+30 , idx \n while( tidx < len(days) and days[tidx] < tillday ):\n tidx+=1\n res = min(res,costs[2]+rec(days,tidx))\n self.dp[idx] = res \n return res\n\n return rec(days,0)\n\n```\n\n2. Converted it into bottom up\n\n```\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n\n dp = [ pow(2,31) for _ in range(0,len(days)+1)]\n n = len(days)\n dp[n] = 0\n for i in range(n-1,-1,-1):\n #one day pass\n dp[i] = min(dp[i],costs[0]+dp[i+1])\n\n #one week pass\n tillday ,tidx = days[i]+7 , i\n while( tidx < n and days[tidx] < tillday ):\n tidx+=1\n dp[i] = min(dp[i],costs[1]+dp[tidx])\n\n #one month pass\n tillday , tidx = days[i]+30 , i \n while( tidx < n and days[tidx] < tillday ):\n tidx+=1\n dp[i] = min(dp[i],costs[2]+dp[tidx])\n\n return dp[0]\n\n \n``` | 1 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
Python Top Down/ Bottom Up Solution for reference | minimum-cost-for-tickets | 0 | 1 | 1. Top Down method\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n # Variable definitions\n # dp: stores results from index , key till len(n)\n # idx: starting index from which we are calculating\n # res: storing the final results\n # tillday: day at which we have to buy ticket again\n # tidx: temprory index to skip through all days ahead \n # which are included in the ticket \n self.dp = defaultdict(int)\n def rec(days,idx):\n if(idx >= len(days)): return 0;\n elif(self.dp[idx] != 0 ): return self.dp[idx]\n nonlocal costs\n res = pow(2,31)\n #one day pass\n res = min(res,costs[0]+rec(days,idx+1))\n \n #one week pass\n tillday ,tidx = days[idx]+7 , idx\n while( tidx < len(days) and days[tidx] < tillday ):\n tidx+=1\n res = min(res,costs[1]+rec(days,tidx))\n \n #one month pass\n tillday , tidx = days[idx]+30 , idx \n while( tidx < len(days) and days[tidx] < tillday ):\n tidx+=1\n res = min(res,costs[2]+rec(days,tidx))\n self.dp[idx] = res \n return res\n\n return rec(days,0)\n\n```\n\n2. Converted it into bottom up\n\n```\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n\n dp = [ pow(2,31) for _ in range(0,len(days)+1)]\n n = len(days)\n dp[n] = 0\n for i in range(n-1,-1,-1):\n #one day pass\n dp[i] = min(dp[i],costs[0]+dp[i+1])\n\n #one week pass\n tillday ,tidx = days[i]+7 , i\n while( tidx < n and days[tidx] < tillday ):\n tidx+=1\n dp[i] = min(dp[i],costs[1]+dp[tidx])\n\n #one month pass\n tillday , tidx = days[i]+30 , i \n while( tidx < n and days[tidx] < tillday ):\n tidx+=1\n dp[i] = min(dp[i],costs[2]+dp[tidx])\n\n return dp[0]\n\n \n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Python | minimum-cost-for-tickets | 0 | 1 | # Complexity\n- Time complexity: 38*n\n\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = {}\n\n def dfs(i):\n if i==len(days):\n return 0\n if i in dp:\n return dp[i]\n dp[i] = float(\'inf\')\n for d,c in zip([1,7,30],costs):\n j = i\n while j<len(days) and days[j]<days[i]+d:\n j+=1\n dp[i] = min(dp[i],c+dfs(j))\n return dp[i]\n\n return dfs(0)\n``` | 1 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
Python | minimum-cost-for-tickets | 0 | 1 | # Complexity\n- Time complexity: 38*n\n\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp = {}\n\n def dfs(i):\n if i==len(days):\n return 0\n if i in dp:\n return dp[i]\n dp[i] = float(\'inf\')\n for d,c in zip([1,7,30],costs):\n j = i\n while j<len(days) and days[j]<days[i]+d:\n j+=1\n dp[i] = min(dp[i],c+dfs(j))\n return dp[i]\n\n return dfs(0)\n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
40MS || 87% BEATS||SIMPLE SOLUTION USING DP|| PYTHON | minimum-cost-for-tickets | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n``` | 1 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
40MS || 87% BEATS||SIMPLE SOLUTION USING DP|| PYTHON | minimum-cost-for-tickets | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
python3 Solution | minimum-cost-for-tickets | 0 | 1 | \n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp7=deque()\n dp30=deque()\n cost=0\n \n for d in days:\n while dp7 and dp7[0][0]<=d-7:\n dp7.popleft()\n \n while dp30 and dp30[0][0]<=d-30:\n dp30.popleft()\n \n dp7.append((d,cost+costs[1]))\n dp30.append((d,cost+costs[2]))\n cost=min(cost+costs[0],dp7[0][1],dp30[0][1])\n return cost \n``` | 1 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
python3 Solution | minimum-cost-for-tickets | 0 | 1 | \n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n dp7=deque()\n dp30=deque()\n cost=0\n \n for d in days:\n while dp7 and dp7[0][0]<=d-7:\n dp7.popleft()\n \n while dp30 and dp30[0][0]<=d-30:\n dp30.popleft()\n \n dp7.append((d,cost+costs[1]))\n dp30.append((d,cost+costs[2]))\n cost=min(cost+costs[0],dp7[0][1],dp30[0][1])\n return cost \n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Solution | minimum-cost-for-tickets | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int mincostTickets(vector<int>& days, vector<int>& costs) {\n sort(days.begin(), days.end());\n int n=days.size();\n vector<int> dp(n+1, 0);\n dp[n] = 0;\n\n for(int i=n-1; i>=0; i--) {\n int t1 = 0, t2 = 0, t3 = 0;\n t1 = costs[0] + dp[i+1];\n \n int j=i;\n for(; j<n && days[j] < days[i] + 7; j++);\n t2 = costs[1] + dp[j];\n\n j=i; \n for(; j<n && days[j] < days[i] + 30; j++);\n t3 = costs[2] + dp[j];\n \n dp[i] = min(t1, min(t2, t3));\n }\n return dp[0];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n \n _1day_pass, _7day_pass, _30day_pass = 0, 1, 2\n \n travel_days = set(days)\n \n last_traverl_day = days[-1]\n \n dp_cost = [ 0 for _ in range(last_traverl_day+1)]\n \n for day_i in range(1, last_traverl_day+1):\n \n if day_i not in travel_days:\n \n dp_cost[day_i] = dp_cost[day_i - 1]\n \n else:\n dp_cost[day_i] = min( dp_cost[ day_i - 1 ] + costs[ _1day_pass ],\n dp_cost[ max(day_i - 7, 0) ] + costs[ _7day_pass ],\n dp_cost[ max(day_i - 30, 0) ] + costs[ _30day_pass ] )\n \n return dp_cost[last_traverl_day]\n```\n\n```Java []\nclass Solution {\n int[] days,costs;\n int[] memo;\n int[] durations= {1,7,30};\n public int mincostTickets(int[] days, int[] costs) {\n this.days=days;\n this.costs=costs;\n memo = new int[days.length];\n return dp(0);\n }\n private int dp(int idx){\n if(idx>=days.length) return 0;\n if(memo[idx]>0) return memo[idx];\n\n int ans = Integer.MAX_VALUE;\n int j=idx;\n\n for(int k=0;k<3;k++){\n while(j < days.length && days[j] < days[idx] + durations[k]){\n j++;\n }\n ans = Math.min(ans, dp(j) + costs[k]);\n }\n memo[idx] = ans;\n return ans;\n }\n}\n```\n | 1 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
Solution | minimum-cost-for-tickets | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int mincostTickets(vector<int>& days, vector<int>& costs) {\n sort(days.begin(), days.end());\n int n=days.size();\n vector<int> dp(n+1, 0);\n dp[n] = 0;\n\n for(int i=n-1; i>=0; i--) {\n int t1 = 0, t2 = 0, t3 = 0;\n t1 = costs[0] + dp[i+1];\n \n int j=i;\n for(; j<n && days[j] < days[i] + 7; j++);\n t2 = costs[1] + dp[j];\n\n j=i; \n for(; j<n && days[j] < days[i] + 30; j++);\n t3 = costs[2] + dp[j];\n \n dp[i] = min(t1, min(t2, t3));\n }\n return dp[0];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n \n _1day_pass, _7day_pass, _30day_pass = 0, 1, 2\n \n travel_days = set(days)\n \n last_traverl_day = days[-1]\n \n dp_cost = [ 0 for _ in range(last_traverl_day+1)]\n \n for day_i in range(1, last_traverl_day+1):\n \n if day_i not in travel_days:\n \n dp_cost[day_i] = dp_cost[day_i - 1]\n \n else:\n dp_cost[day_i] = min( dp_cost[ day_i - 1 ] + costs[ _1day_pass ],\n dp_cost[ max(day_i - 7, 0) ] + costs[ _7day_pass ],\n dp_cost[ max(day_i - 30, 0) ] + costs[ _30day_pass ] )\n \n return dp_cost[last_traverl_day]\n```\n\n```Java []\nclass Solution {\n int[] days,costs;\n int[] memo;\n int[] durations= {1,7,30};\n public int mincostTickets(int[] days, int[] costs) {\n this.days=days;\n this.costs=costs;\n memo = new int[days.length];\n return dp(0);\n }\n private int dp(int idx){\n if(idx>=days.length) return 0;\n if(memo[idx]>0) return memo[idx];\n\n int ans = Integer.MAX_VALUE;\n int j=idx;\n\n for(int k=0;k<3;k++){\n while(j < days.length && days[j] < days[idx] + durations[k]){\n j++;\n }\n ans = Math.min(ans, dp(j) + costs[k]);\n }\n memo[idx] = ans;\n return ans;\n }\n}\n```\n | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Python3 || 39 ms || Beats 91.51 % (DP) | minimum-cost-for-tickets | 0 | 1 | The mincostTickets function takes in two arguments: days, a list of integers representing the days on which you want to travel, and costs, a list of integers representing the costs for a 1-day, 7-day, and 30-day travel pass, respectively.\n\nThe function initializes the cost to zero and two deques last7 and last30, which will store tuples of the form (day, cost) representing the last 7-day and 30-day passes, respectively.\n\nThe function then iterates over each day in the days list. For each day, it first removes any tuples from last7 and last30 that are no longer valid (i.e., the day is more than 7 or 30 days after the day in the tuple).\n\nNext, it adds a new tuple to each deque with the current day and the cost of a 7-day or 30-day pass plus the cost so far. This is because if you buy a 7-day or 30-day pass on the current day, you will also have to pay for the cost of the pass for the preceding days.\n\nFinally, the function sets the cost to the minimum of the following three values: the cost so far plus the cost of a 1-day pass, the cost of the earliest tuple in last7, and the cost of the earliest tuple in last30. This is because you can either buy a 1-day pass on the current day or use one of the 7-day or 30-day passes in the deques.\n\nThe function returns the final cost at the end.\n\n\n# Please Upvote \uD83D\uDE07\n\n## Python3\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n```\n | 41 | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null |
Python3 || 39 ms || Beats 91.51 % (DP) | minimum-cost-for-tickets | 0 | 1 | The mincostTickets function takes in two arguments: days, a list of integers representing the days on which you want to travel, and costs, a list of integers representing the costs for a 1-day, 7-day, and 30-day travel pass, respectively.\n\nThe function initializes the cost to zero and two deques last7 and last30, which will store tuples of the form (day, cost) representing the last 7-day and 30-day passes, respectively.\n\nThe function then iterates over each day in the days list. For each day, it first removes any tuples from last7 and last30 that are no longer valid (i.e., the day is more than 7 or 30 days after the day in the tuple).\n\nNext, it adds a new tuple to each deque with the current day and the cost of a 7-day or 30-day pass plus the cost so far. This is because if you buy a 7-day or 30-day pass on the current day, you will also have to pay for the cost of the pass for the preceding days.\n\nFinally, the function sets the cost to the minimum of the following three values: the cost so far plus the cost of a 1-day pass, the cost of the earliest tuple in last7, and the cost of the earliest tuple in last30. This is because you can either buy a 1-day pass on the current day or use one of the 7-day or 30-day passes in the deques.\n\nThe function returns the final cost at the end.\n\n\n# Please Upvote \uD83D\uDE07\n\n## Python3\n```\nclass Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n cost = 0\n last7 = deque()\n last30 = deque()\n for day in days:\n while last7 and last7[0][0] + 7 <= day:\n last7.popleft()\n while last30 and last30[0][0] + 30 <= day:\n last30.popleft()\n last7.append((day, cost + costs[1]))\n last30.append((day, cost + costs[2]))\n cost = min(cost + costs[0],\n last7[0][1],\n last30[0][1])\n return cost\n```\n | 41 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Python3 🐍 concise solution beats 99% | string-without-aaa-or-bbb | 0 | 1 | # Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n res.append(\'a\')\n a-=1\n elif a > b:\n res.append(\'a\')\n a-=1\n else:\n res.append(\'b\')\n b-=1\n \n return \'\'.join(res)\n``` | 1 | Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`. | null |
Python3 🐍 concise solution beats 99% | string-without-aaa-or-bbb | 0 | 1 | # Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == [\'a\', \'a\']:\n res.append(\'b\')\n b-=1\n elif len(res) >= 2 and res[-2:] == [\'b\', \'b\']:\n res.append(\'a\')\n a-=1\n elif a > b:\n res.append(\'a\')\n a-=1\n else:\n res.append(\'b\')\n b-=1\n \n return \'\'.join(res)\n``` | 1 | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null |
Solution | string-without-aaa-or-bbb | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n a-=1;\n }\n if(b>=1){\n arr=arr+\'b\';\n b-=1;\n }\n }\n else if(b>a){\n if(b>=2){\n arr=arr+"bb";\n b-=2;\n }\n else{\n arr=arr+\'b\';\n b-=1;\n }\n if(a>=1){\n arr=arr+\'a\';\n a-=1;\n }\n }\n else{\n arr=arr+\'a\'+\'b\';\n a-=1;\n b-=1;\n }\n generator(arr, a, b);\n }\n string strWithout3a3b(int a, int b) {\n string arr ="";\n generator(arr, a, b);\n return arr;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if a == b:\n return "ab" * a\n\n x, y = ("a", "b") if a < b else ("b", "a")\n xc, yc = (a, b) if a < b else (b, a)\n n_yyx = min(xc, yc - xc)\n n_yx = min(xc - n_yyx, yc - 2 * n_yyx)\n nx = xc - n_yyx - n_yx\n ny = yc - 2 * n_yyx - n_yx\n return (y + y + x) * n_yyx + (y + x) * n_yx + y * ny + x * nx\n```\n\n```Java []\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder res = new StringBuilder(A + B);\n char a = \'a\', b = \'b\';\n int i = A, j = B;\n if (B > A) { a = \'b\'; b = \'a\'; i = B; j = A; }\n while (i-- > 0) {\n res.append(a);\n if (i > j) { res.append(a); --i; }\n if (j-- > 0) res.append(b);\n }\n return res.toString();\n }\n}\n```\n | 1 | Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`. | null |
Solution | string-without-aaa-or-bbb | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n void generator(string &arr,int &a,int &b){\n if (a<=0 && b<=0){\n return;\n }\n if(a>b){\n if(a>=2){\n arr=arr+"aa";\n a-=2;\n }\n else{\n arr=arr+\'a\';\n a-=1;\n }\n if(b>=1){\n arr=arr+\'b\';\n b-=1;\n }\n }\n else if(b>a){\n if(b>=2){\n arr=arr+"bb";\n b-=2;\n }\n else{\n arr=arr+\'b\';\n b-=1;\n }\n if(a>=1){\n arr=arr+\'a\';\n a-=1;\n }\n }\n else{\n arr=arr+\'a\'+\'b\';\n a-=1;\n b-=1;\n }\n generator(arr, a, b);\n }\n string strWithout3a3b(int a, int b) {\n string arr ="";\n generator(arr, a, b);\n return arr;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if a == b:\n return "ab" * a\n\n x, y = ("a", "b") if a < b else ("b", "a")\n xc, yc = (a, b) if a < b else (b, a)\n n_yyx = min(xc, yc - xc)\n n_yx = min(xc - n_yyx, yc - 2 * n_yyx)\n nx = xc - n_yyx - n_yx\n ny = yc - 2 * n_yyx - n_yx\n return (y + y + x) * n_yyx + (y + x) * n_yx + y * ny + x * nx\n```\n\n```Java []\nclass Solution {\n public String strWithout3a3b(int A, int B) {\n StringBuilder res = new StringBuilder(A + B);\n char a = \'a\', b = \'b\';\n int i = A, j = B;\n if (B > A) { a = \'b\'; b = \'a\'; i = B; j = A; }\n while (i-- > 0) {\n res.append(a);\n if (i > j) { res.append(a); --i; }\n if (j-- > 0) res.append(b);\n }\n return res.toString();\n }\n}\n```\n | 1 | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null |
[Python]: O(a+b) solution with explanation: build a string based on sub-string patterns | string-without-aaa-or-bbb | 0 | 1 | # Intuition\n1. every substring will be based on the following building blocks\n - "aab" or "ab" (assume a > b, else swap a and b)\n2. there is a special case when a > 2xb (e.g. a = 3, b = 1). In this case, add the difference in a and 2xb in as at the end. This number will be either 1 or 2, otherwise the input would be invalid. \n\n# Approach\n1. establish if a or b is larger. based on that, initialize generic values (this makes the problem symmetric -- we can use the same code for either case: a>=b or b<a)\n2. construct the result array based on the building blocks (aab and ab).\na) the number of aabs is equal to a - b. \nb) the number of abs is equal to 2xb - a\nc) handle the special case of a > 2xb (add 1 or 2 "a"s to the end)\n3. return the resulting string\n\n\nNOTE: We handle the problem\'s symmetry. So, in the above description, I assume a >= b. But, if b > a, just swap all the as and bs. E.g. the patterns would be "bba" and "ba" and the end string would be "b" or "bb".\n\n# Complexity\n- Time complexity: O(n) where n = a + b, aka O(a+b)\n\n- Space complexity: O(1) auxillary space. However, the return string is, per problem spec, of length O(n) where n = a + b, aka O(a+b)\n\n# Code\n```py\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n # step 1) establish variables based on if a >= b. this is a symmteric problem\n source = "a"\n l = a\n add = "b"\n s = b\n if b > a:\n l = b\n source = "b"\n s = a\n add = "a"\n \n # step 2a) build the string, starting with the pattern "aab" (assuming a is longer)\n result = ""\n triple = source + source + add\n for i in range(min(l-s, s)):\n result += triple\n \n # step 2b) build the string with the pattern "ab" (direct alternate)\n double = source + add\n for i in range(2*s - l):\n result += double\n\n # step 2c) add 0,1, or 2 "a"s at the end of the result (e.g. aabaa)\n endAppend = l - (2*s)\n for i in range(endAppend):\n result += source\n\n # step 3) return result\n return result\n``` | 0 | Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`. | null |
[Python]: O(a+b) solution with explanation: build a string based on sub-string patterns | string-without-aaa-or-bbb | 0 | 1 | # Intuition\n1. every substring will be based on the following building blocks\n - "aab" or "ab" (assume a > b, else swap a and b)\n2. there is a special case when a > 2xb (e.g. a = 3, b = 1). In this case, add the difference in a and 2xb in as at the end. This number will be either 1 or 2, otherwise the input would be invalid. \n\n# Approach\n1. establish if a or b is larger. based on that, initialize generic values (this makes the problem symmetric -- we can use the same code for either case: a>=b or b<a)\n2. construct the result array based on the building blocks (aab and ab).\na) the number of aabs is equal to a - b. \nb) the number of abs is equal to 2xb - a\nc) handle the special case of a > 2xb (add 1 or 2 "a"s to the end)\n3. return the resulting string\n\n\nNOTE: We handle the problem\'s symmetry. So, in the above description, I assume a >= b. But, if b > a, just swap all the as and bs. E.g. the patterns would be "bba" and "ba" and the end string would be "b" or "bb".\n\n# Complexity\n- Time complexity: O(n) where n = a + b, aka O(a+b)\n\n- Space complexity: O(1) auxillary space. However, the return string is, per problem spec, of length O(n) where n = a + b, aka O(a+b)\n\n# Code\n```py\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n # step 1) establish variables based on if a >= b. this is a symmteric problem\n source = "a"\n l = a\n add = "b"\n s = b\n if b > a:\n l = b\n source = "b"\n s = a\n add = "a"\n \n # step 2a) build the string, starting with the pattern "aab" (assuming a is longer)\n result = ""\n triple = source + source + add\n for i in range(min(l-s, s)):\n result += triple\n \n # step 2b) build the string with the pattern "ab" (direct alternate)\n double = source + add\n for i in range(2*s - l):\n result += double\n\n # step 2c) add 0,1, or 2 "a"s at the end of the result (e.g. aabaa)\n endAppend = l - (2*s)\n for i in range(endAppend):\n result += source\n\n # step 3) return result\n return result\n``` | 0 | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null |
✅conditioonal code || pytthon | string-without-aaa-or-bbb | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if(a==0 and b==0):return ""\n ans=""\n n=a+b\n i=0\n while(i<n):\n if(len(ans)<2):\n if(a>b):\n ans+="a"\n a-=1\n else:\n ans+="b"\n b-=1\n elif(a>b):\n if(ans[i-1]==ans[i-2] and ans[i-1]==\'a\'):\n ans+="b"\n b-=1\n else:\n ans+="a"\n a-=1\n else:\n if(ans[i-1]==ans[i-2] and ans[i-1]==\'b\'):\n ans+="a"\n a-=1\n else:\n ans+="b"\n b-=1\n i+=1\n return ans \n``` | 0 | Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`. | null |
✅conditioonal code || pytthon | string-without-aaa-or-bbb | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n if(a==0 and b==0):return ""\n ans=""\n n=a+b\n i=0\n while(i<n):\n if(len(ans)<2):\n if(a>b):\n ans+="a"\n a-=1\n else:\n ans+="b"\n b-=1\n elif(a>b):\n if(ans[i-1]==ans[i-2] and ans[i-1]==\'a\'):\n ans+="b"\n b-=1\n else:\n ans+="a"\n a-=1\n else:\n if(ans[i-1]==ans[i-2] and ans[i-1]==\'b\'):\n ans+="a"\n a-=1\n else:\n ans+="b"\n b-=1\n i+=1\n return ans \n``` | 0 | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null |
Python Sol without loop, beats 100% | string-without-aaa-or-bbb | 0 | 1 | \n# Code\n```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n if A >= 2*B:\n return \'aab\'* B + \'a\'* (A-2*B)\n elif A >= B:\n return \'aab\' * (A-B) + \'ab\' * (2*B - A)\n elif B >= 2*A:\n return \'bba\' * A + \'b\' *(B-2*A)\n else:\n return \'bba\' * (B-A) + \'ab\' * (2*A - B)\n``` | 0 | Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`. | null |
Python Sol without loop, beats 100% | string-without-aaa-or-bbb | 0 | 1 | \n# Code\n```\nclass Solution(object):\n def strWithout3a3b(self, A, B):\n """\n :type A: int\n :type B: int\n :rtype: str\n """\n if A >= 2*B:\n return \'aab\'* B + \'a\'* (A-2*B)\n elif A >= B:\n return \'aab\' * (A-B) + \'ab\' * (2*B - A)\n elif B >= 2*A:\n return \'bba\' * A + \'b\' *(B-2*A)\n else:\n return \'bba\' * (B-A) + \'ab\' * (2*A - B)\n``` | 0 | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | sum-of-even-numbers-after-queries | 1 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n**C++**\n\n```cpp\nclass Solution {\npublic:\n // the idea is we don\'t calculate the even sum from scratch for each query\n // instead, we calculate it at the beginning\n // since each query only updates one value, \n // so we can adjust the even sum base on the original value and new value\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int evenSum = 0;\n // calculate the sum of all even numbers\n for (auto x : nums) {\n if (x % 2 == 0) {\n evenSum += x;\n }\n }\n vector<int> ans;\n for (auto q : queries) {\n int val = q[0], idx = q[1];\n // if original nums[idx] is even, then we deduct it from evenSum\n if (nums[idx] % 2 == 0) evenSum -= nums[idx];\n // in-place update nums\n nums[idx] += val;\n // check if we need to update evenSum for the new value\n if (nums[idx] % 2 == 0) evenSum += nums[idx];\n // then we have evenSum after this query, push it to ans \n ans.push_back(evenSum);\n }\n return ans;\n }\n};\n```\n\n**Python**\n\n```py\nclass Solution:\n # the idea is we don\'t calculate the even sum from scratch for each query\n # instead, we calculate it at the beginning\n # since each query only updates one value, \n # so we can adjust the even sum base on the original value and new value\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n # calculate the sum of all even numbers\n evenSum = sum(x for x in nums if x % 2 == 0)\n ans = []\n for val, idx in queries:\n # if original nums[idx] is even, then we deduct it from evenSum\n if nums[idx] % 2 == 0: evenSum -= nums[idx]\n # in-place update nums\n nums[idx] += val\n # check if we need to update evenSum for the new value\n if nums[idx] % 2 == 0: evenSum += nums[idx]\n # then we have evenSum after this query, push it to ans \n ans.append(evenSum)\n return ans\n```\n\n**Java**\n\n```java\nclass Solution {\n // the idea is we don\'t calculate the even sum from scratch for each query\n // instead, we calculate it at the beginning\n // since each query only updates one value, \n // so we can adjust the even sum base on the original value and new value\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int evenSum = 0, n = queries.length;\n // calculate the sum of all even numbers\n for (int x : nums) {\n if (x % 2 == 0) {\n evenSum += x;\n }\n }\n int[] ans = new int[n];\n for (int i = 0; i < n; i++) {\n int val = queries[i][0], idx = queries[i][1];\n // if original nums[idx] is even, then we deduct it from evenSum\n if (nums[idx] % 2 == 0) evenSum -= nums[idx];\n // in-place update nums\n nums[idx] += val;\n // check if we need to update evenSum for the new value\n if (nums[idx] % 2 == 0) evenSum += nums[idx];\n // then we have evenSum after this query, push it to ans \n ans[i] = evenSum;\n }\n return ans;\n }\n}\n```\n\n**Go**\n\n```go\n// the idea is we don\'t calculate the even sum from scratch for each query\n// instead, we calculate it at the beginning\n// since each query only updates one value, \n// so we can adjust the even sum base on the original value and new value\nfunc sumEvenAfterQueries(nums []int, queries [][]int) []int {\n evenSum := 0\n // calculate the sum of all even numbers\n for _, val := range nums {\n if val % 2 == 0 {\n evenSum += val\n }\n }\n ans := make([]int, len(queries))\n for i, q := range queries {\n val, idx := q[0], q[1]\n // if original nums[idx] is even, then we deduct it from evenSum\n if nums[idx] % 2 == 0 {\n evenSum -= nums[idx]\n }\n // in-place update nums\n nums[idx] += val\n // check if we need to update evenSum for the new value\n if nums[idx] % 2 == 0 {\n evenSum += nums[idx]\n }\n // then we have evenSum after this query, push it to ans \n ans[i] = evenSum\n }\n return ans\n}\n```\n\n**Just For Fun - Segment Tree**\n\n```cpp\nstruct segtree {\n int size;\n // used to store even sum\n vector<int> sums;\n\n void init(int n) {\n size = 1;\n while (size < n) size *= 2;\n sums.assign(2 * size, 0);\n }\n\n void set(int i, int v, int x, int lx, int rx) {\n if (rx - lx == 1){\n // set sums[x] to v only if v is even\n sums[x] = v % 2 == 0 ? v : 0;\n return;\n }\n int m = (lx + rx) / 2;\n if (i < m) set(i, v, 2 * x + 1, lx, m);\n else set(i, v, 2 * x + 2, m, rx);\n sums[x] = sums[2 * x + 1] + sums[2 * x + 2];\n }\n\n void set(int i, int v) {\n set(i, v, 0, 0, size);\n }\n\n int sum(int l, int r, int x, int lx, int rx) {\n // no intersection\n if (lx >= r || l >= rx) return 0;\n // inside\n if (lx >= l && rx <= r) return sums[x];\n // go to both left and right side\n int m = (lx + rx) / 2;\n int s1 = sum(l, r, 2 * x + 1, lx, m);\n int s2 = sum(l, r, 2 * x + 2, m, rx);\n return s1 + s2;\n }\n\n int sum(int l, int r) {\n return sum(l, r, 0, 0, size);\n }\n};\n\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int n = nums.size();\n // init segment tree\n segtree st;\n st.init(n);\n // set each number in segment tree\n for (int i = 0; i < n; i++) st.set(i, nums[i]);\n vector<int> ans;\n for (auto q : queries) {\n int val = q[0], idx = q[1];\n // update segment tree\n st.set(idx, nums[idx] += val);\n // query segement tree\n\t\t\t// or we can just add st.sums[0] \n\t\t\t// since the root value represents the even sum for the whole array\n ans.push_back(st.sum(0, n));\n }\n return ans;\n }\n};\n``` | 58 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | sum-of-even-numbers-after-queries | 1 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n**C++**\n\n```cpp\nclass Solution {\npublic:\n // the idea is we don\'t calculate the even sum from scratch for each query\n // instead, we calculate it at the beginning\n // since each query only updates one value, \n // so we can adjust the even sum base on the original value and new value\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int evenSum = 0;\n // calculate the sum of all even numbers\n for (auto x : nums) {\n if (x % 2 == 0) {\n evenSum += x;\n }\n }\n vector<int> ans;\n for (auto q : queries) {\n int val = q[0], idx = q[1];\n // if original nums[idx] is even, then we deduct it from evenSum\n if (nums[idx] % 2 == 0) evenSum -= nums[idx];\n // in-place update nums\n nums[idx] += val;\n // check if we need to update evenSum for the new value\n if (nums[idx] % 2 == 0) evenSum += nums[idx];\n // then we have evenSum after this query, push it to ans \n ans.push_back(evenSum);\n }\n return ans;\n }\n};\n```\n\n**Python**\n\n```py\nclass Solution:\n # the idea is we don\'t calculate the even sum from scratch for each query\n # instead, we calculate it at the beginning\n # since each query only updates one value, \n # so we can adjust the even sum base on the original value and new value\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n # calculate the sum of all even numbers\n evenSum = sum(x for x in nums if x % 2 == 0)\n ans = []\n for val, idx in queries:\n # if original nums[idx] is even, then we deduct it from evenSum\n if nums[idx] % 2 == 0: evenSum -= nums[idx]\n # in-place update nums\n nums[idx] += val\n # check if we need to update evenSum for the new value\n if nums[idx] % 2 == 0: evenSum += nums[idx]\n # then we have evenSum after this query, push it to ans \n ans.append(evenSum)\n return ans\n```\n\n**Java**\n\n```java\nclass Solution {\n // the idea is we don\'t calculate the even sum from scratch for each query\n // instead, we calculate it at the beginning\n // since each query only updates one value, \n // so we can adjust the even sum base on the original value and new value\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int evenSum = 0, n = queries.length;\n // calculate the sum of all even numbers\n for (int x : nums) {\n if (x % 2 == 0) {\n evenSum += x;\n }\n }\n int[] ans = new int[n];\n for (int i = 0; i < n; i++) {\n int val = queries[i][0], idx = queries[i][1];\n // if original nums[idx] is even, then we deduct it from evenSum\n if (nums[idx] % 2 == 0) evenSum -= nums[idx];\n // in-place update nums\n nums[idx] += val;\n // check if we need to update evenSum for the new value\n if (nums[idx] % 2 == 0) evenSum += nums[idx];\n // then we have evenSum after this query, push it to ans \n ans[i] = evenSum;\n }\n return ans;\n }\n}\n```\n\n**Go**\n\n```go\n// the idea is we don\'t calculate the even sum from scratch for each query\n// instead, we calculate it at the beginning\n// since each query only updates one value, \n// so we can adjust the even sum base on the original value and new value\nfunc sumEvenAfterQueries(nums []int, queries [][]int) []int {\n evenSum := 0\n // calculate the sum of all even numbers\n for _, val := range nums {\n if val % 2 == 0 {\n evenSum += val\n }\n }\n ans := make([]int, len(queries))\n for i, q := range queries {\n val, idx := q[0], q[1]\n // if original nums[idx] is even, then we deduct it from evenSum\n if nums[idx] % 2 == 0 {\n evenSum -= nums[idx]\n }\n // in-place update nums\n nums[idx] += val\n // check if we need to update evenSum for the new value\n if nums[idx] % 2 == 0 {\n evenSum += nums[idx]\n }\n // then we have evenSum after this query, push it to ans \n ans[i] = evenSum\n }\n return ans\n}\n```\n\n**Just For Fun - Segment Tree**\n\n```cpp\nstruct segtree {\n int size;\n // used to store even sum\n vector<int> sums;\n\n void init(int n) {\n size = 1;\n while (size < n) size *= 2;\n sums.assign(2 * size, 0);\n }\n\n void set(int i, int v, int x, int lx, int rx) {\n if (rx - lx == 1){\n // set sums[x] to v only if v is even\n sums[x] = v % 2 == 0 ? v : 0;\n return;\n }\n int m = (lx + rx) / 2;\n if (i < m) set(i, v, 2 * x + 1, lx, m);\n else set(i, v, 2 * x + 2, m, rx);\n sums[x] = sums[2 * x + 1] + sums[2 * x + 2];\n }\n\n void set(int i, int v) {\n set(i, v, 0, 0, size);\n }\n\n int sum(int l, int r, int x, int lx, int rx) {\n // no intersection\n if (lx >= r || l >= rx) return 0;\n // inside\n if (lx >= l && rx <= r) return sums[x];\n // go to both left and right side\n int m = (lx + rx) / 2;\n int s1 = sum(l, r, 2 * x + 1, lx, m);\n int s2 = sum(l, r, 2 * x + 2, m, rx);\n return s1 + s2;\n }\n\n int sum(int l, int r) {\n return sum(l, r, 0, 0, size);\n }\n};\n\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int n = nums.size();\n // init segment tree\n segtree st;\n st.init(n);\n // set each number in segment tree\n for (int i = 0; i < n; i++) st.set(i, nums[i]);\n vector<int> ans;\n for (auto q : queries) {\n int val = q[0], idx = q[1];\n // update segment tree\n st.set(idx, nums[idx] += val);\n // query segement tree\n\t\t\t// or we can just add st.sums[0] \n\t\t\t// since the root value represents the even sum for the whole array\n ans.push_back(st.sum(0, n));\n }\n return ans;\n }\n};\n``` | 58 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
Solution | sum-of-even-numbers-after-queries | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int S = 0;\n for (int x: nums)\n if (x % 2 == 0)\n S += x;\n\n vector<int> ans(queries.size());\n\n for (int i = 0; i < queries.size(); ++i) {\n int val = queries[i][0], index = queries[i][1];\n if (nums[index] % 2 == 0) S -= nums[index];\n nums[index] += val;\n if (nums[index] % 2 == 0) S += nums[index];\n ans[i] = S;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n total = 0\n\n for num in nums: \n if num%2 == 0: total += num\n answer = []\n\n for i in range(len(queries)):\n num = queries[i][0]\n idx = queries[i][1]\n idx_sum = nums[idx] + num\n if not (nums[idx] % 2 != 0 and idx_sum % 2!= 0):\n if idx_sum % 2 == 0:\n if nums[idx] % 2 != 0: total = total + idx_sum\n else: total = total + num\n else: total = total - nums[idx]\n \n nums[idx] = idx_sum\n answer.append(total)\n \n return answer\n```\n\n```Java []\nclass Solution {\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int n = queries.length;\n int[] ret = new int[n];\n\n int cur = 0;\n for (int i = 0; i < n; i++)\n if ((nums[i] & 1) == 0) cur += nums[i];\n\n for (int i = 0; i < n; i++) {\n int idx = queries[i][1];\n int del = queries[i][0];\n\n int oldV = nums[idx];\n int newV = oldV + del;\n\n if ((oldV & 1) == 0) cur -= oldV;\n if ((newV & 1) == 0) cur += newV;\n nums[idx] = newV;\n\n ret[i] = cur;\n }\n return ret;\n }\n}\n```\n | 1 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
Solution | sum-of-even-numbers-after-queries | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n int S = 0;\n for (int x: nums)\n if (x % 2 == 0)\n S += x;\n\n vector<int> ans(queries.size());\n\n for (int i = 0; i < queries.size(); ++i) {\n int val = queries[i][0], index = queries[i][1];\n if (nums[index] % 2 == 0) S -= nums[index];\n nums[index] += val;\n if (nums[index] % 2 == 0) S += nums[index];\n ans[i] = S;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n total = 0\n\n for num in nums: \n if num%2 == 0: total += num\n answer = []\n\n for i in range(len(queries)):\n num = queries[i][0]\n idx = queries[i][1]\n idx_sum = nums[idx] + num\n if not (nums[idx] % 2 != 0 and idx_sum % 2!= 0):\n if idx_sum % 2 == 0:\n if nums[idx] % 2 != 0: total = total + idx_sum\n else: total = total + num\n else: total = total - nums[idx]\n \n nums[idx] = idx_sum\n answer.append(total)\n \n return answer\n```\n\n```Java []\nclass Solution {\n public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n int n = queries.length;\n int[] ret = new int[n];\n\n int cur = 0;\n for (int i = 0; i < n; i++)\n if ((nums[i] & 1) == 0) cur += nums[i];\n\n for (int i = 0; i < n; i++) {\n int idx = queries[i][1];\n int del = queries[i][0];\n\n int oldV = nums[idx];\n int newV = oldV + del;\n\n if ((oldV & 1) == 0) cur -= oldV;\n if ((newV & 1) == 0) cur += newV;\n nums[idx] = newV;\n\n ret[i] = cur;\n }\n return ret;\n }\n}\n```\n | 1 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
Easy python solution | sum-of-even-numbers-after-queries | 0 | 1 | ```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n sm=0\n for i in range(len(nums)):\n if nums[i]%2==0:\n sm+=nums[i]\n lst=[]\n for i in range(len(queries)):\n prev=nums[queries[i][1]]\n nums[queries[i][1]]+=queries[i][0]\n curr=nums[queries[i][1]]\n if prev%2==0:\n if curr%2==0:\n sm+=(curr-prev)\n else:\n sm-=prev\n else:\n if curr%2==0:\n sm+=curr\n lst.append(sm)\n return lst\n``` | 5 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
Easy python solution | sum-of-even-numbers-after-queries | 0 | 1 | ```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n sm=0\n for i in range(len(nums)):\n if nums[i]%2==0:\n sm+=nums[i]\n lst=[]\n for i in range(len(queries)):\n prev=nums[queries[i][1]]\n nums[queries[i][1]]+=queries[i][0]\n curr=nums[queries[i][1]]\n if prev%2==0:\n if curr%2==0:\n sm+=(curr-prev)\n else:\n sm-=prev\n else:\n if curr%2==0:\n sm+=curr\n lst.append(sm)\n return lst\n``` | 5 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
[Python3] Memory Usage beats 99.49% Space O(1) (no extra array) | sum-of-even-numbers-after-queries | 0 | 1 | The solution is straight-forward. First we get the sum of all even numbers in **nums** and call it **s**. \nDuring each query **q**, if nums[q[0]] is even, we subtract it from our current **s**, otherwise we do nothing. \nThen we update `nums[q[0]] += q[1]`. If THIS **nums[q[0]]** is even, we add it to **s** again. After each query we append **s** to our **ans** list.\n### **Code**\n```\ndef sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n s = 0\n for i in nums:\n s += i if i % 2 == 0 else 0\n ans = []\n for q in queries:\n if nums[q[1]] % 2 == 0:\n s -= nums[q[1]]\n nums[q[1]] += q[0]\n if nums[q[1]] % 2 == 0:\n s += nums[q[1]]\n ans.append(s)\n return ans\n```\n### **Space optimize solution**\nWe don\'t need to create another array **ans**. We can reuse the list **queries** instead!\nThe reason for this is that after the **queries[i]**, we no longer use it.\nI think I don\'t need to explain much about this, the code is self-explanatory!\n### Code\n```\ndef sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n s = 0\n for i in nums:\n s += i if i % 2 == 0 else 0\n for i, q in enumerate(queries):\n if nums[q[1]] % 2 == 0:\n s -= nums[q[1]]\n nums[q[1]] += q[0]\n if nums[q[1]] % 2 == 0:\n s += nums[q[1]]\n queries[i] = s\n return queries\n``` | 2 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
[Python3] Memory Usage beats 99.49% Space O(1) (no extra array) | sum-of-even-numbers-after-queries | 0 | 1 | The solution is straight-forward. First we get the sum of all even numbers in **nums** and call it **s**. \nDuring each query **q**, if nums[q[0]] is even, we subtract it from our current **s**, otherwise we do nothing. \nThen we update `nums[q[0]] += q[1]`. If THIS **nums[q[0]]** is even, we add it to **s** again. After each query we append **s** to our **ans** list.\n### **Code**\n```\ndef sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n s = 0\n for i in nums:\n s += i if i % 2 == 0 else 0\n ans = []\n for q in queries:\n if nums[q[1]] % 2 == 0:\n s -= nums[q[1]]\n nums[q[1]] += q[0]\n if nums[q[1]] % 2 == 0:\n s += nums[q[1]]\n ans.append(s)\n return ans\n```\n### **Space optimize solution**\nWe don\'t need to create another array **ans**. We can reuse the list **queries** instead!\nThe reason for this is that after the **queries[i]**, we no longer use it.\nI think I don\'t need to explain much about this, the code is self-explanatory!\n### Code\n```\ndef sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n s = 0\n for i in nums:\n s += i if i % 2 == 0 else 0\n for i, q in enumerate(queries):\n if nums[q[1]] % 2 == 0:\n s -= nums[q[1]]\n nums[q[1]] += q[0]\n if nums[q[1]] % 2 == 0:\n s += nums[q[1]]\n queries[i] = s\n return queries\n``` | 2 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
Python Segment Tree Approach + Query Traversal Approach | sum-of-even-numbers-after-queries | 0 | 1 | ```\nclass SegmentTree:\n def __init__(self, arr, function):\n self.tree = [None for _ in range(len(arr))] + arr\n self.n = len(arr)\n self.fn = function\n self.build_tree()\n\n def build_tree(self):\n for i in range(self.n - 1, 0, -1):\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\n \n def query(self, l, r):\n l += self.n\n r += self.n\n ans = 0\n while l < r:\n if l & 1:\n ans = self.fn(ans, self.tree[l])\n l += 1\n if r & 1:\n r -= 1\n ans = self.fn(ans, self.tree[r])\n l >>= 1\n r >>= 1\n return ans\n \n def update(self, i, val):\n i += self.n\n self.tree[i] += val\n while i > 1:\n i >>= 1\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\nclass Solution:\n # Classic Segment Tree Quesiton\n # The update function of the tree has to be changed\n # The root node of the tree will contain the result\n # For 1 length nums array as an edge case just check if the res node has even value or not cuz even + even is always even\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n def dummy(x, y):\n if not x & 1 and not y & 1: return x + y\n elif not x & 1: return x\n elif not y & 1: return y\n else: return 0\n tree = SegmentTree(nums, dummy)\n res = []\n for val, i in queries:\n tree.update(i, val)\n res.append(tree.tree[1] if not tree.tree[1] & 1 else 0)\n return res\n```\n\nThe other way to do this could be - \n\n```\nclass Solution:\n # Simple query traversal approach\n\t# Check if previously the nums element was even or odd\n\t# If it was even we just need to remove it or update the ressum based on the new result being even or odd\n\t# If it was odd we need to add to the ressum only if the new value becomes even\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n ressum = sum([num for num in nums if not num & 1])\n res = []\n for val, i in queries:\n if nums[i] & 1:\n if not nums[i] + val & 1:\n ressum += nums[i] + val\n else:\n if not nums[i] + val & 1:ressum += val\n else: ressum -= nums[i]\n res.append(ressum) \n nums[i] += val\n return res\n``` | 2 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
Python Segment Tree Approach + Query Traversal Approach | sum-of-even-numbers-after-queries | 0 | 1 | ```\nclass SegmentTree:\n def __init__(self, arr, function):\n self.tree = [None for _ in range(len(arr))] + arr\n self.n = len(arr)\n self.fn = function\n self.build_tree()\n\n def build_tree(self):\n for i in range(self.n - 1, 0, -1):\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\n \n def query(self, l, r):\n l += self.n\n r += self.n\n ans = 0\n while l < r:\n if l & 1:\n ans = self.fn(ans, self.tree[l])\n l += 1\n if r & 1:\n r -= 1\n ans = self.fn(ans, self.tree[r])\n l >>= 1\n r >>= 1\n return ans\n \n def update(self, i, val):\n i += self.n\n self.tree[i] += val\n while i > 1:\n i >>= 1\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\nclass Solution:\n # Classic Segment Tree Quesiton\n # The update function of the tree has to be changed\n # The root node of the tree will contain the result\n # For 1 length nums array as an edge case just check if the res node has even value or not cuz even + even is always even\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n def dummy(x, y):\n if not x & 1 and not y & 1: return x + y\n elif not x & 1: return x\n elif not y & 1: return y\n else: return 0\n tree = SegmentTree(nums, dummy)\n res = []\n for val, i in queries:\n tree.update(i, val)\n res.append(tree.tree[1] if not tree.tree[1] & 1 else 0)\n return res\n```\n\nThe other way to do this could be - \n\n```\nclass Solution:\n # Simple query traversal approach\n\t# Check if previously the nums element was even or odd\n\t# If it was even we just need to remove it or update the ressum based on the new result being even or odd\n\t# If it was odd we need to add to the ressum only if the new value becomes even\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n ressum = sum([num for num in nums if not num & 1])\n res = []\n for val, i in queries:\n if nums[i] & 1:\n if not nums[i] + val & 1:\n ressum += nums[i] + val\n else:\n if not nums[i] + val & 1:ressum += val\n else: ressum -= nums[i]\n res.append(ressum) \n nums[i] += val\n return res\n``` | 2 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
Python Solution || With Explanation || Easy to understand | sum-of-even-numbers-after-queries | 0 | 1 | # APPROACH:-\n* Store Intial sum of even and odd values present in the array.\n* Initiatize output array/list and start traversing the queries\n* if value at provided index is even then subtract it from even count. if it\'s odd leave it.\n* Update the nums array as ` nums[idx] = nums[idx] + val` . where idx is the index and val is value provided in query.\n* If the new Value calculated in above step is even then add this value to even, if it\'s odd leave it.\n* Finally append the even count to the output array.\n\n\n\n# Code:-\n\n```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n\t\t# to store initial sum of even and odd numbers\n even,odd = 0,0\n for num in nums:\n if num&1:\n odd+=num\n else:\n even+=num\n\t\t\t\t\n ans = []\n for query in queries:\n\t\t\t# unpacking value and index\n val,idx = query\n\t\t\t\n\t\t\t# previous value at index idx\n preval = nums[idx]\n\t\t\t\n\t\t\t# if previous value was even we\'ll subtract it from sum of even\n if preval%2 == 0:\n even -= preval\n\t\t\t\t\n\t\t\t# update the nums array\n nums[idx] = nums[idx] + val\n\t\t\t\n\t\t\t# if new value is even add it to even count\n if nums[idx]%2==0:\n even += nums[idx]\n\t\t\t\t\n\t\t\t# append to the ans\n ans.append(even)\n return ans\n``` | 1 | You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length` | null |
Python Solution || With Explanation || Easy to understand | sum-of-even-numbers-after-queries | 0 | 1 | # APPROACH:-\n* Store Intial sum of even and odd values present in the array.\n* Initiatize output array/list and start traversing the queries\n* if value at provided index is even then subtract it from even count. if it\'s odd leave it.\n* Update the nums array as ` nums[idx] = nums[idx] + val` . where idx is the index and val is value provided in query.\n* If the new Value calculated in above step is even then add this value to even, if it\'s odd leave it.\n* Finally append the even count to the output array.\n\n\n\n# Code:-\n\n```\nclass Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n\t\t# to store initial sum of even and odd numbers\n even,odd = 0,0\n for num in nums:\n if num&1:\n odd+=num\n else:\n even+=num\n\t\t\t\t\n ans = []\n for query in queries:\n\t\t\t# unpacking value and index\n val,idx = query\n\t\t\t\n\t\t\t# previous value at index idx\n preval = nums[idx]\n\t\t\t\n\t\t\t# if previous value was even we\'ll subtract it from sum of even\n if preval%2 == 0:\n even -= preval\n\t\t\t\t\n\t\t\t# update the nums array\n nums[idx] = nums[idx] + val\n\t\t\t\n\t\t\t# if new value is even add it to even count\n if nums[idx]%2==0:\n even += nums[idx]\n\t\t\t\t\n\t\t\t# append to the ans\n ans.append(even)\n return ans\n``` | 1 | Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500` | null |
Solution recursive in python | interval-list-intersections | 0 | 1 | # Code\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n n1, n2 = len(firstList), len(secondList)\n if n1==0 or n2==0:\n return []\n e1, e2 = firstList[0], secondList[0]\n startPoint = e1[0]\n if e1[0]<e2[0]:\n startPoint = e2[0]\n endPoint = e1[1]\n if e1[1]>e2[1]:\n endPoint = e2[1] \n if n2>1 and e1[1]>= secondList[1][0]:\n secondList.pop(0)\n elif n1>1 and e2[1]>= firstList[1][0]:\n firstList.pop(0)\n else:\n if n1>=1:\n firstList.pop(0)\n if n2>=1:\n secondList.pop(0)\n if startPoint <= endPoint:\n output = [[startPoint, endPoint]]\n output.extend(self.intervalIntersection(firstList, secondList))\n return output\n return self.intervalIntersection(firstList, secondList)\n``` | 3 | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null |
Solution recursive in python | interval-list-intersections | 0 | 1 | # Code\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n n1, n2 = len(firstList), len(secondList)\n if n1==0 or n2==0:\n return []\n e1, e2 = firstList[0], secondList[0]\n startPoint = e1[0]\n if e1[0]<e2[0]:\n startPoint = e2[0]\n endPoint = e1[1]\n if e1[1]>e2[1]:\n endPoint = e2[1] \n if n2>1 and e1[1]>= secondList[1][0]:\n secondList.pop(0)\n elif n1>1 and e2[1]>= firstList[1][0]:\n firstList.pop(0)\n else:\n if n1>=1:\n firstList.pop(0)\n if n2>=1:\n secondList.pop(0)\n if startPoint <= endPoint:\n output = [[startPoint, endPoint]]\n output.extend(self.intervalIntersection(firstList, secondList))\n return output\n return self.intervalIntersection(firstList, secondList)\n``` | 3 | We run a preorder depth-first search (DFS) on the `root` of a binary tree.
At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.
If a node has only one child, that child is guaranteed to be **the left child**.
Given the output `traversal` of this traversal, recover the tree and return _its_ `root`.
**Example 1:**
**Input:** traversal = "1-2--3--4-5--6--7 "
**Output:** \[1,2,5,3,4,6,7\]
**Example 2:**
**Input:** traversal = "1-2--3---4-5--6---7 "
**Output:** \[1,2,5,3,null,6,null,4,null,7\]
**Example 3:**
**Input:** traversal = "1-401--349---90--88 "
**Output:** \[1,401,null,349,88,90\]
**Constraints:**
* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 109` | null |
Python two pointers solution | interval-list-intersections | 0 | 1 | **Python :**\n\n```\ndef intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\tif firstList == [] or secondList == []:\n\t\treturn []\n\n\tres = []\n\ti, j = 0, 0\n\n\twhile i < len(firstList) and j < len(secondList):\n\t\tl = max(firstList[i][0], secondList[j][0])\n\t\tr = min(firstList[i][1], secondList[j][1])\n\n\t\tif l <= r :\n\t\t\tres.append([l, r])\n\n\t\tif firstList[i][1] < secondList[j][1]:\n\t\t\ti += 1\n\n\t\telse:\n\t\t\tj += 1 \n\n\treturn res\n```\n\n**Like it ? please upvote !** | 17 | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null |
Python two pointers solution | interval-list-intersections | 0 | 1 | **Python :**\n\n```\ndef intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n\tif firstList == [] or secondList == []:\n\t\treturn []\n\n\tres = []\n\ti, j = 0, 0\n\n\twhile i < len(firstList) and j < len(secondList):\n\t\tl = max(firstList[i][0], secondList[j][0])\n\t\tr = min(firstList[i][1], secondList[j][1])\n\n\t\tif l <= r :\n\t\t\tres.append([l, r])\n\n\t\tif firstList[i][1] < secondList[j][1]:\n\t\t\ti += 1\n\n\t\telse:\n\t\t\tj += 1 \n\n\treturn res\n```\n\n**Like it ? please upvote !** | 17 | We run a preorder depth-first search (DFS) on the `root` of a binary tree.
At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.
If a node has only one child, that child is guaranteed to be **the left child**.
Given the output `traversal` of this traversal, recover the tree and return _its_ `root`.
**Example 1:**
**Input:** traversal = "1-2--3--4-5--6--7 "
**Output:** \[1,2,5,3,4,6,7\]
**Example 2:**
**Input:** traversal = "1-2--3---4-5--6---7 "
**Output:** \[1,2,5,3,null,6,null,4,null,7\]
**Example 3:**
**Input:** traversal = "1-401--349---90--88 "
**Output:** \[1,401,null,349,88,90\]
**Constraints:**
* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 109` | null |
78% TC and 84% SC easy python solution | interval-list-intersections | 0 | 1 | ```\ndef intervalIntersection(self, fir: List[List[int]], sec: List[List[int]]) -> List[List[int]]:\n\tans = []\n\tl1 = len(fir)\n\tl2 = len(sec)\n\ti = j = 0\n\twhile(i < l1 and j < l2):\n\t\tif(fir[i][1] < sec[j][0]): i += 1\n\t\telif(sec[j][1] < fir[i][0]): j += 1\n\t\telif(fir[i][0] <= sec[j][0] and sec[j][1] <= fir[i][1]):\n\t\t\tans.append(sec[j])\n\t\t\tj += 1\n\t\telif(sec[j][0] <= fir[i][0] and fir[i][1] <= sec[j][1]):\n\t\t\tans.append(fir[i])\n\t\t\ti += 1\n\t\telif(sec[j][1] > fir[i][1] >= sec[j][0]):\n\t\t\tans.append([sec[j][0], fir[i][1]])\n\t\t\ti += 1\n\t\telif(fir[i][1] > sec[j][1] >= fir[i][0]):\n\t\t\tans.append([fir[i][0], sec[j][1]])\n\t\t\tj += 1\n\n\treturn ans\n``` | 1 | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null |
78% TC and 84% SC easy python solution | interval-list-intersections | 0 | 1 | ```\ndef intervalIntersection(self, fir: List[List[int]], sec: List[List[int]]) -> List[List[int]]:\n\tans = []\n\tl1 = len(fir)\n\tl2 = len(sec)\n\ti = j = 0\n\twhile(i < l1 and j < l2):\n\t\tif(fir[i][1] < sec[j][0]): i += 1\n\t\telif(sec[j][1] < fir[i][0]): j += 1\n\t\telif(fir[i][0] <= sec[j][0] and sec[j][1] <= fir[i][1]):\n\t\t\tans.append(sec[j])\n\t\t\tj += 1\n\t\telif(sec[j][0] <= fir[i][0] and fir[i][1] <= sec[j][1]):\n\t\t\tans.append(fir[i])\n\t\t\ti += 1\n\t\telif(sec[j][1] > fir[i][1] >= sec[j][0]):\n\t\t\tans.append([sec[j][0], fir[i][1]])\n\t\t\ti += 1\n\t\telif(fir[i][1] > sec[j][1] >= fir[i][0]):\n\t\t\tans.append([fir[i][0], sec[j][1]])\n\t\t\tj += 1\n\n\treturn ans\n``` | 1 | We run a preorder depth-first search (DFS) on the `root` of a binary tree.
At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.
If a node has only one child, that child is guaranteed to be **the left child**.
Given the output `traversal` of this traversal, recover the tree and return _its_ `root`.
**Example 1:**
**Input:** traversal = "1-2--3--4-5--6--7 "
**Output:** \[1,2,5,3,4,6,7\]
**Example 2:**
**Input:** traversal = "1-2--3---4-5--6---7 "
**Output:** \[1,2,5,3,null,6,null,4,null,7\]
**Example 3:**
**Input:** traversal = "1-401--349---90--88 "
**Output:** \[1,401,null,349,88,90\]
**Constraints:**
* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 109` | null |
As easy as it comes(plain English), python3 solution with complexity analysis | interval-list-intersections | 0 | 1 | ```\nclass Solution:\n # O(n + m) time,\n # O(n + m) space,\n # Approach: two pointers\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n ans = []\n n = len(firstList)\n m = len(secondList)\n \n def findIntersection(interval1: List[int], interval2: List[int]) -> List[int]:\n \n lower_bound = max(interval1[0], interval2[0])\n upper_bound = min(interval1[1], interval2[1])\n \n if lower_bound > upper_bound:\n return [lower_bound]\n \n return [lower_bound, upper_bound]\n \n \n i, j = 0, 0\n while i < n and j < m:\n interval1 = firstList[i]\n interval2 = secondList[j]\n intersection = findIntersection(interval1, interval2)\n higher_bound = intersection[-1]\n \n if len(intersection) > 1:\n ans.append(intersection) \n \n if interval1[-1] > higher_bound:\n j+=1\n else:\n i +=1\n \n return ans\n``` | 1 | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null |
As easy as it comes(plain English), python3 solution with complexity analysis | interval-list-intersections | 0 | 1 | ```\nclass Solution:\n # O(n + m) time,\n # O(n + m) space,\n # Approach: two pointers\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n ans = []\n n = len(firstList)\n m = len(secondList)\n \n def findIntersection(interval1: List[int], interval2: List[int]) -> List[int]:\n \n lower_bound = max(interval1[0], interval2[0])\n upper_bound = min(interval1[1], interval2[1])\n \n if lower_bound > upper_bound:\n return [lower_bound]\n \n return [lower_bound, upper_bound]\n \n \n i, j = 0, 0\n while i < n and j < m:\n interval1 = firstList[i]\n interval2 = secondList[j]\n intersection = findIntersection(interval1, interval2)\n higher_bound = intersection[-1]\n \n if len(intersection) > 1:\n ans.append(intersection) \n \n if interval1[-1] > higher_bound:\n j+=1\n else:\n i +=1\n \n return ans\n``` | 1 | We run a preorder depth-first search (DFS) on the `root` of a binary tree.
At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.
If a node has only one child, that child is guaranteed to be **the left child**.
Given the output `traversal` of this traversal, recover the tree and return _its_ `root`.
**Example 1:**
**Input:** traversal = "1-2--3--4-5--6--7 "
**Output:** \[1,2,5,3,4,6,7\]
**Example 2:**
**Input:** traversal = "1-2--3---4-5--6---7 "
**Output:** \[1,2,5,3,null,6,null,4,null,7\]
**Example 3:**
**Input:** traversal = "1-401--349---90--88 "
**Output:** \[1,401,null,349,88,90\]
**Constraints:**
* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 109` | null |
Python3, easy to understand. Not too pythonic | interval-list-intersections | 0 | 1 | Let me know if you have any questions! I feel like the comments are self-explantory. There are ways to make this code less, but I was lazy and didn\'t feel like doing it. i.e. we could get rid of the min function and do a manual if-else condition.\n\nHope this helps :)\n\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n # a: [x, y], b: [u, v].\n ret = []\n \n # while there is still both, since will ignore everything that is not in.\n i = j = 0\n while i < len(firstList) and j < len(secondList):\n interval = firstList[i]\n interval2 = secondList[j]\n \n # case where x > u\n if interval[0] > interval2[0]:\n start = interval[0]\n # case where u >= x\n else:\n start = interval2[0]\n \n # could be optimized but I am lazy\n end = min(interval[1], interval2[1])\n \n if start <= end:\n ret.append([start, end])\n \n # too lazy to manually calculate min\n if end == interval[1]:\n i += 1\n \n # using if for a reason.\n # reason is because both could be at end lol.\n if end == interval2[1]:\n j += 1\n \n return ret\n``` | 1 | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null |
Python3, easy to understand. Not too pythonic | interval-list-intersections | 0 | 1 | Let me know if you have any questions! I feel like the comments are self-explantory. There are ways to make this code less, but I was lazy and didn\'t feel like doing it. i.e. we could get rid of the min function and do a manual if-else condition.\n\nHope this helps :)\n\n```\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n # a: [x, y], b: [u, v].\n ret = []\n \n # while there is still both, since will ignore everything that is not in.\n i = j = 0\n while i < len(firstList) and j < len(secondList):\n interval = firstList[i]\n interval2 = secondList[j]\n \n # case where x > u\n if interval[0] > interval2[0]:\n start = interval[0]\n # case where u >= x\n else:\n start = interval2[0]\n \n # could be optimized but I am lazy\n end = min(interval[1], interval2[1])\n \n if start <= end:\n ret.append([start, end])\n \n # too lazy to manually calculate min\n if end == interval[1]:\n i += 1\n \n # using if for a reason.\n # reason is because both could be at end lol.\n if end == interval2[1]:\n j += 1\n \n return ret\n``` | 1 | We run a preorder depth-first search (DFS) on the `root` of a binary tree.
At each node in this traversal, we output `D` dashes (where `D` is the depth of this node), then we output the value of this node. If the depth of a node is `D`, the depth of its immediate child is `D + 1`. The depth of the `root` node is `0`.
If a node has only one child, that child is guaranteed to be **the left child**.
Given the output `traversal` of this traversal, recover the tree and return _its_ `root`.
**Example 1:**
**Input:** traversal = "1-2--3--4-5--6--7 "
**Output:** \[1,2,5,3,4,6,7\]
**Example 2:**
**Input:** traversal = "1-2--3---4-5--6---7 "
**Output:** \[1,2,5,3,null,6,null,4,null,7\]
**Example 3:**
**Input:** traversal = "1-401--349---90--88 "
**Output:** \[1,401,null,349,88,90\]
**Constraints:**
* The number of nodes in the original tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 109` | null |
Solution in python using comparator class || Simple Traversal || hashmap | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\nfrom functools import cmp_to_key\n\n# comparator class for compare two elements in sorting to handle the cases which have same y but differ x\n# for eg self -> [(1,2), [3,4,..]] where (1,2) pair is (x,y) and [3,4,...] are the values of node that have same (x,y)\nclass Compare:\n def main(self,elm):\n\t\t# comparing the position of y\n if self[0][-1]<elm[0][-1]:\n return -1\n elif self[0][-1]>elm[0][-1]:\n return 1\n else:\n\t\t\t# if position of y is same for both self and elm, compare the position of x -1 represents for smaller and 1 represents for larger\n if self[0][0]<elm[0][0]:\n return -1\n else:\n return 1\n\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n self.vot = {}\n self.find(root)\n self.vot = sorted(self.vot.items(),key=cmp_to_key(Compare.main))\n mapp = {}\n\t\t# final merge\n for key,value in self.vot:\n mapp[key[-1]] = mapp.get(key[-1],[]) + value\n return list(mapp.values())\n \n \n def find(self,root,x=0,y=0):\n\t\t# traversing the root node to get all (x,y) pairs with node values\n if root == None:\n return\n self.vot[(x,y)] = self.insert(self.vot.get((x,y),[]),root.val)\n self.find(root.left,x+1,y-1)\n self.find(root.right,x+1,y+1)\n \n \n def insert(self, arr, elm):\n\t\t# function for inserting a value in our map that have same (x,y) while traversing \n if not arr:\n return [elm]\n for index,curr in enumerate(arr):\n if curr >= elm:\n return arr[:index] + [elm] + arr[index:]\n return arr + [elm]\n``` | 1 | Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`.
The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return _the **vertical order traversal** of the binary tree_.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Explanation:**
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
**Example 3:**
**Input:** root = \[1,2,3,4,6,5,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 1000` | null |
Solution in python using comparator class || Simple Traversal || hashmap | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\nfrom functools import cmp_to_key\n\n# comparator class for compare two elements in sorting to handle the cases which have same y but differ x\n# for eg self -> [(1,2), [3,4,..]] where (1,2) pair is (x,y) and [3,4,...] are the values of node that have same (x,y)\nclass Compare:\n def main(self,elm):\n\t\t# comparing the position of y\n if self[0][-1]<elm[0][-1]:\n return -1\n elif self[0][-1]>elm[0][-1]:\n return 1\n else:\n\t\t\t# if position of y is same for both self and elm, compare the position of x -1 represents for smaller and 1 represents for larger\n if self[0][0]<elm[0][0]:\n return -1\n else:\n return 1\n\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n self.vot = {}\n self.find(root)\n self.vot = sorted(self.vot.items(),key=cmp_to_key(Compare.main))\n mapp = {}\n\t\t# final merge\n for key,value in self.vot:\n mapp[key[-1]] = mapp.get(key[-1],[]) + value\n return list(mapp.values())\n \n \n def find(self,root,x=0,y=0):\n\t\t# traversing the root node to get all (x,y) pairs with node values\n if root == None:\n return\n self.vot[(x,y)] = self.insert(self.vot.get((x,y),[]),root.val)\n self.find(root.left,x+1,y-1)\n self.find(root.right,x+1,y+1)\n \n \n def insert(self, arr, elm):\n\t\t# function for inserting a value in our map that have same (x,y) while traversing \n if not arr:\n return [elm]\n for index,curr in enumerate(arr):\n if curr >= elm:\n return arr[:index] + [elm] + arr[index:]\n return arr + [elm]\n``` | 1 | A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000` | null |
Python BFS + Hashmap | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n results = defaultdict(list)\n \n queue = [ (root, 0, 0) ]\n \n while queue:\n node, pos, depth = queue.pop(0)\n if not node: continue\n results[(pos,depth)].append(node.val)\n results[(pos,depth)].sort()\n queue.extend( [ (node.left, pos-1, depth+1), (node.right, pos+1, depth+1) ] )\n \n \n res = defaultdict(list)\n keys = sorted(list(results.keys()), key=lambda x: (x[0], x[1]))\n \n \n for k in keys:\n pos, depth = k\n res[pos].extend(results[k])\n\n return res.values()\n``` | 17 | Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`.
The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return _the **vertical order traversal** of the binary tree_.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Explanation:**
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
**Example 3:**
**Input:** root = \[1,2,3,4,6,5,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 1000` | null |
Python BFS + Hashmap | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\nclass Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n results = defaultdict(list)\n \n queue = [ (root, 0, 0) ]\n \n while queue:\n node, pos, depth = queue.pop(0)\n if not node: continue\n results[(pos,depth)].append(node.val)\n results[(pos,depth)].sort()\n queue.extend( [ (node.left, pos-1, depth+1), (node.right, pos+1, depth+1) ] )\n \n \n res = defaultdict(list)\n keys = sorted(list(results.keys()), key=lambda x: (x[0], x[1]))\n \n \n for k in keys:\n pos, depth = k\n res[pos].extend(results[k])\n\n return res.values()\n``` | 17 | A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000` | null |
Python3 || 31 ms, faster than 96.95% of Python3 || Clean and Easy to Understand | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\ndef verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n d=defaultdict(list)\n q=deque()\n q.append([root,0,0])\n while(q):\n node,row,col=q.popleft()\n d[col].append([node.val,row])\n if node.left:\n q.append([node.left,row+1,col-1])\n if node.right:\n q.append([node.right,row+1,col+1])\n \n ans=[]\n for i in sorted(d.keys()):\n lst=d[i]\n lst.sort(key=lambda x:(x[1],x[0]))\n temp=[]\n for i in lst:\n temp.append(i[0])\n ans.append(temp)\n return ans\n``` | 2 | Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree.
For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`.
The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
Return _the **vertical order traversal** of the binary tree_.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[9\],\[3,15\],\[20\],\[7\]\]
**Explanation:**
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
**Example 3:**
**Input:** root = \[1,2,3,4,6,5,7\]
**Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\]
**Explanation:**
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 1000` | null |
Python3 || 31 ms, faster than 96.95% of Python3 || Clean and Easy to Understand | vertical-order-traversal-of-a-binary-tree | 0 | 1 | ```\ndef verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n d=defaultdict(list)\n q=deque()\n q.append([root,0,0])\n while(q):\n node,row,col=q.popleft()\n d[col].append([node.val,row])\n if node.left:\n q.append([node.left,row+1,col-1])\n if node.right:\n q.append([node.right,row+1,col+1])\n \n ans=[]\n for i in sorted(d.keys()):\n lst=d[i]\n lst.sort(key=lambda x:(x[1],x[0]))\n temp=[]\n for i in lst:\n temp.append(i[0])\n ans.append(temp)\n return ans\n``` | 2 | A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000` | null |
Solution | smallest-string-starting-from-leaf | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n void post(TreeNode* root,string s,set<string> &st)\n {\n if(root==NULL)\n return;\n \n s+=char(root->val+\'a\');\n if(root->left==NULL && root->right==NULL)\n {\n string temp=s;\n reverse(temp.begin(),temp.end());\n st.insert(temp);\n }\n post(root->left,s,st);\n post(root->right,s,st);\n }\n string smallestFromLeaf(TreeNode* root) {\n set<string> st;\n post(root,"",st);\n \n return *st.begin();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n\n def path(self,root , s) :\n if root==None :\n return \n if root.left == None and root.right == None :\n s += chr(root.val+97)\n self.ans.append(s[::-1])\n \n temp = s\n s += chr(root.val+97)\n self.path(root.left,s)\n self.path(root.right , s )\n return\n\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n self.ans = []\n self.path(root, "")\n self.ans.sort()\n return self.ans[0]\n```\n\n```Java []\nclass Solution {\n public String smallestFromLeaf(TreeNode root) {\n recur(root, new StringBuilder());\n return ans;\n }\n private String ans = "~";\n private void recur(TreeNode node, StringBuilder holder) {\n\n if (node != null) {\n holder.append((char)(\'a\' + node.val));\n\n if (node.left == null && node.right == null) {\n holder.reverse();\n String str = holder.toString();\n holder.reverse();\n\n if (str.compareTo(ans) < 0) {\n ans = str;\n }\n }\n recur(node.left, holder);\n recur(node.right, holder);\n holder.deleteCharAt(holder.length() - 1);\n }\n }\n}\n```\n | 1 | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25` | null |
Solution | smallest-string-starting-from-leaf | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n void post(TreeNode* root,string s,set<string> &st)\n {\n if(root==NULL)\n return;\n \n s+=char(root->val+\'a\');\n if(root->left==NULL && root->right==NULL)\n {\n string temp=s;\n reverse(temp.begin(),temp.end());\n st.insert(temp);\n }\n post(root->left,s,st);\n post(root->right,s,st);\n }\n string smallestFromLeaf(TreeNode* root) {\n set<string> st;\n post(root,"",st);\n \n return *st.begin();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n\n def path(self,root , s) :\n if root==None :\n return \n if root.left == None and root.right == None :\n s += chr(root.val+97)\n self.ans.append(s[::-1])\n \n temp = s\n s += chr(root.val+97)\n self.path(root.left,s)\n self.path(root.right , s )\n return\n\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n self.ans = []\n self.path(root, "")\n self.ans.sort()\n return self.ans[0]\n```\n\n```Java []\nclass Solution {\n public String smallestFromLeaf(TreeNode root) {\n recur(root, new StringBuilder());\n return ans;\n }\n private String ans = "~";\n private void recur(TreeNode node, StringBuilder holder) {\n\n if (node != null) {\n holder.append((char)(\'a\' + node.val));\n\n if (node.left == null && node.right == null) {\n holder.reverse();\n String str = holder.toString();\n holder.reverse();\n\n if (str.compareTo(ans) < 0) {\n ans = str;\n }\n }\n recur(node.left, holder);\n recur(node.right, holder);\n holder.deleteCharAt(holder.length() - 1);\n }\n }\n}\n```\n | 1 | You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.
The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.
**Example 1:**
**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]
**Example 2:**
**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.
**Example 3:**
**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rCenter < rows`
* `0 <= cCenter < cols` | null |
[Python] Simple and efficient recursive solution - 98% | smallest-string-starting-from-leaf | 0 | 1 | \n# Approach\n- We traverse the the tree and pass path to the node till now as parameter of recursive function\n- When we encounter a leaf node - compare it with lowestPath\n- if we encounter null we end recursive branch\n- for normal node we add value to path and pass on/ call recursive function for it\'s left and right child\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - time to traverse each node\n(assuming path to compare paths in negligible othervise)\n\n- Space complexity:\n$$O(1)$$ - not saving anything other one string\n\n# Code\n```\n\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n self.result="\u017DZZZZZZZZZZZZZZZ"\n\n #to check if a node is leaf node, return true if it is\n def isLeaf(node):\n if(node):\n return ((not node.left) and (not node.right))\n return False\n \n # recursive function to traverse\n def traversar(path,node):\n if (not node): return\n \n #convert value to char and append to current path\n path+=chr(ord(\'a\')+node.val)\n\n #if it\'s lexicographically smaller than current path, \n # then replace result with current path.reverse\n if(isLeaf(node) and path[::-1]<self.result):\n self.result=path[::-1]\n return\n \n traversar(path,node.left)\n traversar(path,node.right)\n\n traversar("",root)\n\n return self.result\n \n\n\n\n``` | 1 | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25` | null |
[Python] Simple and efficient recursive solution - 98% | smallest-string-starting-from-leaf | 0 | 1 | \n# Approach\n- We traverse the the tree and pass path to the node till now as parameter of recursive function\n- When we encounter a leaf node - compare it with lowestPath\n- if we encounter null we end recursive branch\n- for normal node we add value to path and pass on/ call recursive function for it\'s left and right child\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - time to traverse each node\n(assuming path to compare paths in negligible othervise)\n\n- Space complexity:\n$$O(1)$$ - not saving anything other one string\n\n# Code\n```\n\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n self.result="\u017DZZZZZZZZZZZZZZZ"\n\n #to check if a node is leaf node, return true if it is\n def isLeaf(node):\n if(node):\n return ((not node.left) and (not node.right))\n return False\n \n # recursive function to traverse\n def traversar(path,node):\n if (not node): return\n \n #convert value to char and append to current path\n path+=chr(ord(\'a\')+node.val)\n\n #if it\'s lexicographically smaller than current path, \n # then replace result with current path.reverse\n if(isLeaf(node) and path[::-1]<self.result):\n self.result=path[::-1]\n return\n \n traversar(path,node.left)\n traversar(path,node.right)\n\n traversar("",root)\n\n return self.result\n \n\n\n\n``` | 1 | You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.
The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.
**Example 1:**
**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]
**Example 2:**
**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.
**Example 3:**
**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rCenter < rows`
* `0 <= cCenter < cols` | null |
Python3 🐍 concise solution beats 99% | smallest-string-starting-from-leaf | 0 | 1 | \n# Code\n```\nclass Solution:\n res = \'z\' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, "")\n return self.res\n``` | 1 | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25` | null |
Python3 🐍 concise solution beats 99% | smallest-string-starting-from-leaf | 0 | 1 | \n# Code\n```\nclass Solution:\n res = \'z\' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, "")\n return self.res\n``` | 1 | You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.
The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.
**Example 1:**
**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]
**Example 2:**
**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.
**Example 3:**
**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rCenter < rows`
* `0 <= cCenter < cols` | null |
[Python3] | DFS +Sorting | smallest-string-starting-from-leaf | 0 | 1 | ```\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n ans=[]\n def dfs(root,ds):\n ds.append(chr(97+root.val))\n if not root.left and not root.right:\n ans.append("".join(ds[:]))\n return\n if root.left:\n dfs(root.left,ds)\n ds.pop()\n if root.right:\n dfs(root.right,ds)\n ds.pop() \n dfs(root,[])\n ans=sorted([i[::-1] for i in ans])\n return ans[0]\n\n``` | 1 | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25` | null |
[Python3] | DFS +Sorting | smallest-string-starting-from-leaf | 0 | 1 | ```\nclass Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n ans=[]\n def dfs(root,ds):\n ds.append(chr(97+root.val))\n if not root.left and not root.right:\n ans.append("".join(ds[:]))\n return\n if root.left:\n dfs(root.left,ds)\n ds.pop()\n if root.right:\n dfs(root.right,ds)\n ds.pop() \n dfs(root,[])\n ans=sorted([i[::-1] for i in ans])\n return ans[0]\n\n``` | 1 | You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.
The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.
**Example 1:**
**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]
**Example 2:**
**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.
**Example 3:**
**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rCenter < rows`
* `0 <= cCenter < cols` | null |
Pythonic Solution | smallest-string-starting-from-leaf | 0 | 1 | # Code\n```python\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 Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode], pre: str = \'\') -> str:\n if root is None:\n return pre\n current = self.intToChar(root.val) + pre\n left = self.smallestFromLeaf(root.left, current)\n right = self.smallestFromLeaf(root.right, current)\n if not root.left:\n return right\n if not root.right:\n return left\n return min(left, right)\n\n \n def intToChar(self, i: int) -> str:\n return chr(ord(\'a\') + i)\n``` | 0 | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25` | null |
Pythonic Solution | smallest-string-starting-from-leaf | 0 | 1 | # Code\n```python\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 Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode], pre: str = \'\') -> str:\n if root is None:\n return pre\n current = self.intToChar(root.val) + pre\n left = self.smallestFromLeaf(root.left, current)\n right = self.smallestFromLeaf(root.right, current)\n if not root.left:\n return right\n if not root.right:\n return left\n return min(left, right)\n\n \n def intToChar(self, i: int) -> str:\n return chr(ord(\'a\') + i)\n``` | 0 | You are given four integers `row`, `cols`, `rCenter`, and `cCenter`. There is a `rows x cols` matrix and you are on the cell with the coordinates `(rCenter, cCenter)`.
Return _the coordinates of all cells in the matrix, sorted by their **distance** from_ `(rCenter, cCenter)` _from the smallest distance to the largest distance_. You may return the answer in **any order** that satisfies this condition.
The **distance** between two cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`.
**Example 1:**
**Input:** rows = 1, cols = 2, rCenter = 0, cCenter = 0
**Output:** \[\[0,0\],\[0,1\]\]
**Explanation:** The distances from (0, 0) to other cells are: \[0,1\]
**Example 2:**
**Input:** rows = 2, cols = 2, rCenter = 0, cCenter = 1
**Output:** \[\[0,1\],\[0,0\],\[1,1\],\[1,0\]\]
**Explanation:** The distances from (0, 1) to other cells are: \[0,1,1,2\]
The answer \[\[0,1\],\[1,1\],\[0,0\],\[1,0\]\] would also be accepted as correct.
**Example 3:**
**Input:** rows = 2, cols = 3, rCenter = 1, cCenter = 2
**Output:** \[\[1,2\],\[0,2\],\[1,1\],\[0,1\],\[1,0\],\[0,0\]\]
**Explanation:** The distances from (1, 2) to other cells are: \[0,1,1,2,2,3\]
There are other answers that would also be accepted as correct, such as \[\[1,2\],\[1,1\],\[0,2\],\[1,0\],\[0,1\],\[0,0\]\].
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rCenter < rows`
* `0 <= cCenter < cols` | null |
Python 95% beats || 2 Approach || Simple Code | add-to-array-form-of-integer | 0 | 1 | **If you got help from this,... Plz Upvote .. it encourage me**\n# Code\n# Approach 1 Array\n```\nclass Solution(object):\n def addToArrayForm(self, A, K):\n A[-1] += K\n for i in range(len(A) - 1, -1, -1):\n carry, A[i] = divmod(A[i], 10)\n if i: A[i-1] += carry\n if carry:\n A = list(map(int, str(carry))) + A\n return A\n\n```\n\n.\n\n# Approach 2 (By Convert list into number then add and then convert number into digit)\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # List -> Number\n n = 0\n for ele in num:\n n = (n*10) + ele\n \n n = n+k\n \n # Number -> List\n num = []\n while n > 0:\n num.insert(0, n % 10) \n n //= 10 \n return num\n``` | 1 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Python 95% beats || 2 Approach || Simple Code | add-to-array-form-of-integer | 0 | 1 | **If you got help from this,... Plz Upvote .. it encourage me**\n# Code\n# Approach 1 Array\n```\nclass Solution(object):\n def addToArrayForm(self, A, K):\n A[-1] += K\n for i in range(len(A) - 1, -1, -1):\n carry, A[i] = divmod(A[i], 10)\n if i: A[i-1] += carry\n if carry:\n A = list(map(int, str(carry))) + A\n return A\n\n```\n\n.\n\n# Approach 2 (By Convert list into number then add and then convert number into digit)\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # List -> Number\n n = 0\n for ele in num:\n n = (n*10) + ele\n \n n = n+k\n \n # Number -> List\n num = []\n while n > 0:\n num.insert(0, n % 10) \n n //= 10 \n return num\n``` | 1 | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null |
Two simple approaches in python. | add-to-array-form-of-integer | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach - 1\n<!-- Describe your approach to solving the problem. -->\nThe implementation first concatenates the digits in $$num$$ into a single string using $$map$$ and $$join$$, then converts the resulting string to an integer using int. The $$k$$ value is added to the resulting integer, and the result is again converted into a string. Finally, the string is converted back to a list of integers using $$map$$.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the $$addToArrayForm$$ method is $$O(n)$$, where n is the length of the input list $$num$$. This is because the method needs to first concatenate all the elements in $$num$$ into a string, which takes $$O(n)$$ time. Then, the string needs to be converted into an integer, which takes $$O(n)$$ time as well. Finally, the integer is converted back to a string, which takes $$O(n)$$ time, and then to a list of integers using $$map$$, which takes $$O(n)$$ time. The overall time complexity is thus $$O(n)$$.\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Approach - 2:\nWe can solve the problem by converting integer k into array form. Then add the two arrays by calculating carry and update it at every digit addition and storing resulting digit after addition in $$result$$ list. \n\n# Code\n**Approach - 1:**\n```\nimport sys\nsys.set_int_max_str_digits(10**6)\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(map(int,str(int("".join(map(str,num))) + k)))\n```\n**Approach - 2:**\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # Convert the second number \'k\' into an array of its digits.\n kArray = []\n while k:\n remainder = k % 10\n kArray.append(remainder)\n k = k // 10\n kArray = kArray[::-1] # Reverse the array to get the correct order of digits.\n\n carry = 0 # Initialize a variable to keep track of the carry during addition.\n\n # Initialize pointers to the last elements of \'num\' and \'kArray\'.\n numP, kP = len(num) - 1, len(kArray) - 1\n\n result = [] # Initialize an array to store the result of the addition.\n\n # Perform addition while both \'num\' and \'kArray\' have digits left.\n while numP >= 0 and kP >= 0:\n value = (num[numP] + kArray[kP] + carry) % 10 # Calculate the sum of digits.\n carry = (num[numP] + kArray[kP] + carry) // 10 # Update the carry for the next addition.\n numP -= 1 \n kP -= 1 \n result.append(value) \n\n # If there are still digits left in \'num\', perform addition with the remaining digits.\n while numP >= 0:\n value = (num[numP] + carry) % 10\n carry = (num[numP] + carry) // 10\n result.append(value)\n numP -= 1\n\n # If there are still digits left in \'kArray\', perform addition with the remaining digits.\n while kP >= 0:\n value = (kArray[kP] + carry) % 10\n carry = (kArray[kP] + carry) // 10\n result.append(value)\n kP -= 1\n\n # If there is a carry left after all additions, add it to the result.\n if carry != 0:\n result.append(carry)\n\n # Reverse the result array to get the correct order of digits and return it.\n return result[::-1]\n\n``` | 1 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Two simple approaches in python. | add-to-array-form-of-integer | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach - 1\n<!-- Describe your approach to solving the problem. -->\nThe implementation first concatenates the digits in $$num$$ into a single string using $$map$$ and $$join$$, then converts the resulting string to an integer using int. The $$k$$ value is added to the resulting integer, and the result is again converted into a string. Finally, the string is converted back to a list of integers using $$map$$.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the $$addToArrayForm$$ method is $$O(n)$$, where n is the length of the input list $$num$$. This is because the method needs to first concatenate all the elements in $$num$$ into a string, which takes $$O(n)$$ time. Then, the string needs to be converted into an integer, which takes $$O(n)$$ time as well. Finally, the integer is converted back to a string, which takes $$O(n)$$ time, and then to a list of integers using $$map$$, which takes $$O(n)$$ time. The overall time complexity is thus $$O(n)$$.\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Approach - 2:\nWe can solve the problem by converting integer k into array form. Then add the two arrays by calculating carry and update it at every digit addition and storing resulting digit after addition in $$result$$ list. \n\n# Code\n**Approach - 1:**\n```\nimport sys\nsys.set_int_max_str_digits(10**6)\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(map(int,str(int("".join(map(str,num))) + k)))\n```\n**Approach - 2:**\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n # Convert the second number \'k\' into an array of its digits.\n kArray = []\n while k:\n remainder = k % 10\n kArray.append(remainder)\n k = k // 10\n kArray = kArray[::-1] # Reverse the array to get the correct order of digits.\n\n carry = 0 # Initialize a variable to keep track of the carry during addition.\n\n # Initialize pointers to the last elements of \'num\' and \'kArray\'.\n numP, kP = len(num) - 1, len(kArray) - 1\n\n result = [] # Initialize an array to store the result of the addition.\n\n # Perform addition while both \'num\' and \'kArray\' have digits left.\n while numP >= 0 and kP >= 0:\n value = (num[numP] + kArray[kP] + carry) % 10 # Calculate the sum of digits.\n carry = (num[numP] + kArray[kP] + carry) // 10 # Update the carry for the next addition.\n numP -= 1 \n kP -= 1 \n result.append(value) \n\n # If there are still digits left in \'num\', perform addition with the remaining digits.\n while numP >= 0:\n value = (num[numP] + carry) % 10\n carry = (num[numP] + carry) // 10\n result.append(value)\n numP -= 1\n\n # If there are still digits left in \'kArray\', perform addition with the remaining digits.\n while kP >= 0:\n value = (kArray[kP] + carry) % 10\n carry = (kArray[kP] + carry) // 10\n result.append(value)\n kP -= 1\n\n # If there is a carry left after all additions, add it to the result.\n if carry != 0:\n result.append(carry)\n\n # Reverse the result array to get the correct order of digits and return it.\n return result[::-1]\n\n``` | 1 | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null |
Python3 👍||⚡ 83/86 T/M beats,only 1 line 🔥|| clean solution || | add-to-array-form-of-integer | 0 | 1 | \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return map(int,list(str(int("".join(map(str, num))) + k)))\n``` | 1 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Python3 👍||⚡ 83/86 T/M beats,only 1 line 🔥|| clean solution || | add-to-array-form-of-integer | 0 | 1 | \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return map(int,list(str(int("".join(map(str, num))) + k)))\n``` | 1 | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null |
🔥🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3 || Java | add-to-array-form-of-integer | 1 | 1 | # Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nWe are taking `k` as carry.\nWe start from the last or lowest digit in array `num` add `k`.\nThen **update** `k` and move untill the highest digit.\nAfter traversing array if carry is **>** `0` then we add it to begining of `num`.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Example: `num` = [2,1,5], `k` = 806\n At index 2 num = [2, 1, 811] \n So, `k` = 81 and `num` = [2, 1, 1]\n\n At index 1 num = [2, 82, 1]\n So, `k` = 8 and `num` = [2, 2, 1]\n\n At index 0 num = [10, 2, 1]\n So, `k` = 1 and `num` = [0, 2, 1]\n\n Now `k` > 0\n So, we add at the beginning of num\n `num` = [1, 0, 2, 1]\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n for(int i=num.size()-1;i>=0;i--){\n num[i] += k;\n k = num[i]/10;\n num[i] %= 10;\n }\n while(k > 0){\n num.insert(num.begin(), k%10);\n k /= 10;\n }\n return num;\n }\n};\n```\n```python []\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n for i in range(len(num) - 1, -1, -1):\n k, num[i] = divmod(num[i] + k, 10)\n while k:\n k, a = divmod(k, 10)\n num = [a] + num\n return num\n```\n```Java []\npublic List<Integer> addToArrayForm(int[] num, int K) {\n List<Integer> res = new LinkedList<>();\n for (int i = num.length - 1; i >= 0; --i) {\n res.add(0, (num[i] + K) % 10);\n K = (num[i] + K) / 10;\n }\n while (K > 0) {\n res.add(0, K % 10);\n K /= 10;\n }\n return res;\n}\n```\n\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/) | 301 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
🔥🚀Simplest Solution🚀||🔥Full Explanation||🔥C++🔥|| Python3 || Java | add-to-array-form-of-integer | 1 | 1 | # Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nWe are taking `k` as carry.\nWe start from the last or lowest digit in array `num` add `k`.\nThen **update** `k` and move untill the highest digit.\nAfter traversing array if carry is **>** `0` then we add it to begining of `num`.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Example: `num` = [2,1,5], `k` = 806\n At index 2 num = [2, 1, 811] \n So, `k` = 81 and `num` = [2, 1, 1]\n\n At index 1 num = [2, 82, 1]\n So, `k` = 8 and `num` = [2, 2, 1]\n\n At index 0 num = [10, 2, 1]\n So, `k` = 1 and `num` = [0, 2, 1]\n\n Now `k` > 0\n So, we add at the beginning of num\n `num` = [1, 0, 2, 1]\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> addToArrayForm(vector<int>& num, int k) {\n for(int i=num.size()-1;i>=0;i--){\n num[i] += k;\n k = num[i]/10;\n num[i] %= 10;\n }\n while(k > 0){\n num.insert(num.begin(), k%10);\n k /= 10;\n }\n return num;\n }\n};\n```\n```python []\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n for i in range(len(num) - 1, -1, -1):\n k, num[i] = divmod(num[i] + k, 10)\n while k:\n k, a = divmod(k, 10)\n num = [a] + num\n return num\n```\n```Java []\npublic List<Integer> addToArrayForm(int[] num, int K) {\n List<Integer> res = new LinkedList<>();\n for (int i = num.length - 1; i >= 0; --i) {\n res.add(0, (num[i] + K) % 10);\n K = (num[i] + K) / 10;\n }\n while (K > 0) {\n res.add(0, K % 10);\n K /= 10;\n }\n return res;\n}\n```\n\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin](https://www.linkedin.com/in/naman-agarwal-0551aa1aa/) | 301 | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null |
Python short and clean. | add-to-array-form-of-integer | 0 | 1 | # Approach\n1. Convert `k` to reversed iterable of digits using `rdigits`.\n\n2. Add backwards, digit by digit with carry, of `num` and `rdigits(k)`\n\n3. Push the results into a queue to un-reverse the sum, and return.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the max length of num and k`\n\n# Code\n```python\nclass Solution:\n def addToArrayForm(self, num: list[int], k: int) -> list[int]:\n def rdigits(n: int) -> Iterable[int]:\n while n: n, r = divmod(n, 10); yield r\n \n def sum_iter(xs: Iterable[int], ys: Iterable[int]) -> Iterable[int]:\n c = 0\n for x, y in zip_longest(xs, ys, fillvalue=0):\n c, s = divmod(x + y + c, 10)\n yield s\n if c: yield c\n \n sum_ = deque()\n sum_.extendleft(sum_iter(reversed(num), rdigits(k)))\n return sum_\n\n\n``` | 2 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Python short and clean. | add-to-array-form-of-integer | 0 | 1 | # Approach\n1. Convert `k` to reversed iterable of digits using `rdigits`.\n\n2. Add backwards, digit by digit with carry, of `num` and `rdigits(k)`\n\n3. Push the results into a queue to un-reverse the sum, and return.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the max length of num and k`\n\n# Code\n```python\nclass Solution:\n def addToArrayForm(self, num: list[int], k: int) -> list[int]:\n def rdigits(n: int) -> Iterable[int]:\n while n: n, r = divmod(n, 10); yield r\n \n def sum_iter(xs: Iterable[int], ys: Iterable[int]) -> Iterable[int]:\n c = 0\n for x, y in zip_longest(xs, ys, fillvalue=0):\n c, s = divmod(x + y + c, 10)\n yield s\n if c: yield c\n \n sum_ = deque()\n sum_.extendleft(sum_iter(reversed(num), rdigits(k)))\n return sum_\n\n\n``` | 2 | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null |
PYTHON SOLUTION USING DISJOINT SET | satisfiability-of-equality-equations | 0 | 1 | # Intuition\nWE WOULD MAKE ALL alphabet that are equal in same component. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUNION DISJOINT\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)$$ -->\n\n# Code\n```\nclass Disjoint:\n def __init__(self):\n self.rank=[0]*26\n self.parent=[i for i in range(26)]\n\n def finduPar(self,node):\n if self.parent[node]==node:\n return node\n self.parent[node]=self.finduPar(self.parent[node])\n return self.parent[node]\n\n def byrank(self,u,v):\n ulp_u=self.finduPar(u)\n ulp_v=self.finduPar(v)\n if ulp_u==ulp_v:\n return False\n if self.rank[ulp_u]>self.rank[ulp_v]:\n self.parent[ulp_v]=ulp_u\n elif self.rank[ulp_u]<self.rank[ulp_v]:\n self.parent[ulp_u]=ulp_v\n else:\n self.parent[ulp_v]=ulp_u\n self.rank[ulp_u]+=1\n\n\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n disjoint=Disjoint()\n nq=[]\n n=len(equations)\n for i in range(n):\n if equations[i][1]==\'!\':\n if equations[i][0]==equations[i][-1]:\n return False\n else:\n nq.append(equations[i])\n else:\n disjoint.byrank(ord(equations[i][0])-97,ord(equations[i][-1])-97)\n for i in range(len(nq)):\n x=ord(nq[i][0])-97\n y=ord(nq[i][-1])-97\n if disjoint.finduPar(x)==disjoint.finduPar(y):\n return False\n return True\n``` | 1 | You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter. | null |
PYTHON SOLUTION USING DISJOINT SET | satisfiability-of-equality-equations | 0 | 1 | # Intuition\nWE WOULD MAKE ALL alphabet that are equal in same component. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUNION DISJOINT\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)$$ -->\n\n# Code\n```\nclass Disjoint:\n def __init__(self):\n self.rank=[0]*26\n self.parent=[i for i in range(26)]\n\n def finduPar(self,node):\n if self.parent[node]==node:\n return node\n self.parent[node]=self.finduPar(self.parent[node])\n return self.parent[node]\n\n def byrank(self,u,v):\n ulp_u=self.finduPar(u)\n ulp_v=self.finduPar(v)\n if ulp_u==ulp_v:\n return False\n if self.rank[ulp_u]>self.rank[ulp_v]:\n self.parent[ulp_v]=ulp_u\n elif self.rank[ulp_u]<self.rank[ulp_v]:\n self.parent[ulp_u]=ulp_v\n else:\n self.parent[ulp_v]=ulp_u\n self.rank[ulp_u]+=1\n\n\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n disjoint=Disjoint()\n nq=[]\n n=len(equations)\n for i in range(n):\n if equations[i][1]==\'!\':\n if equations[i][0]==equations[i][-1]:\n return False\n else:\n nq.append(equations[i])\n else:\n disjoint.byrank(ord(equations[i][0])-97,ord(equations[i][-1])-97)\n for i in range(len(nq)):\n x=ord(nq[i][0])-97\n y=ord(nq[i][-1])-97\n if disjoint.finduPar(x)==disjoint.finduPar(y):\n return False\n return True\n``` | 1 | Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query. | null |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | satisfiability-of-equality-equations | 1 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n<iframe src="https://leetcode.com/playground/GYaVCPSb/shared" frameBorder="0" width="100%" height="500"></iframe>\n | 95 | You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter. | null |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | satisfiability-of-equality-equations | 1 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n<iframe src="https://leetcode.com/playground/GYaVCPSb/shared" frameBorder="0" width="100%" height="500"></iframe>\n | 95 | Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query. | null |
Solution | satisfiability-of-equality-equations | 1 | 1 | ```C++ []\nclass DisjointSet{\npublic:\n vector<int>size;\n vector<int>parent;\n DisjointSet(int n){\n size.resize(n,1);\n parent.resize(n);\n for(int i=0;i<n;i++){\n parent[i]=i;\n }\n }\n int findUPar(int node){\n if(parent[node]==node)return node;\n return parent[node]=findUPar(parent[node]);\n }\n void unionBySize(int u,int v){\n int ulp_u=findUPar(u);\n int ulp_v=findUPar(v);\n if(ulp_u==ulp_v)return;\n if(size[ulp_u]>=size[ulp_v]){\n parent[ulp_v]=ulp_u;\n size[ulp_u]+=size[ulp_v];\n }\n else{\n parent[ulp_u]=ulp_v;\n size[ulp_v]+=size[ulp_u];\n }\n }\n};\nclass Solution {\npublic:\n bool equationsPossible(vector<string>& equations) {\n DisjointSet ds(26);\n for(auto it:equations){\n int u=it[0]-\'a\';\n int v=it[3]-\'a\';\n if(it[1]==\'=\'){\n if(ds.findUPar(u)!=ds.findUPar(v)){\n ds.unionBySize(u,v);\n }\n }\n }\n for(auto it:equations){\n int u=it[0]-\'a\';\n int v=it[3]-\'a\';\n if(it[1]==\'!\'){\n if(ds.findUPar(u)==ds.findUPar(v))return false;\n }\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n\n graph = {}\n\n def find(char):\n if graph[char] == char:\n return char\n else:\n return find(graph[char])\n\n stack = [e for e in equations if e[1] == "="]\n inequs = [e for e in equations if e[1] == "!"]\n\n for char in "".join(equations):\n graph[char] = char\n\n while len(stack) > 0:\n e = stack.pop()\n graph[find(e[0])] = find(e[3])\n \n for ine in inequs:\n x = ine[0]; y = ine[3]\n if find(x) == find(y):\n return False\n return True\n```\n\n```Java []\nclass Solution {\n private int[] values;\n public boolean equationsPossible(String[] equations) {\n int size = equations.length;\n values = new int[26];\n \n for(int i = 0; i < 26; i++){\n values[i] = i;\n }\n for(String equation : equations){\n if(equation.charAt(1) == \'=\'){\n union(equation.charAt(0) - \'a\', equation.charAt(3) - \'a\');\n }\n }\n for(String equation : equations){\n if(equation.charAt(1) == \'!\' && find(equation.charAt(0) - \'a\') == find(equation.charAt(3) - \'a\')){\n return false;\n }\n }\n return true;\n }\n private void union(int a, int b){\n int rootA = find(a);\n int rootB = find(b);\n values[rootA] = rootB;\n }\n private int find(int a){\n int root = values[a];\n\n while(values[root] != root){\n root = values[root];\n }\n while(values[a] != root){\n int b = values[a];\n values[a] = root;\n a = b;\n }\n return root;\n }\n}\n```\n | 2 | You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter. | null |
Solution | satisfiability-of-equality-equations | 1 | 1 | ```C++ []\nclass DisjointSet{\npublic:\n vector<int>size;\n vector<int>parent;\n DisjointSet(int n){\n size.resize(n,1);\n parent.resize(n);\n for(int i=0;i<n;i++){\n parent[i]=i;\n }\n }\n int findUPar(int node){\n if(parent[node]==node)return node;\n return parent[node]=findUPar(parent[node]);\n }\n void unionBySize(int u,int v){\n int ulp_u=findUPar(u);\n int ulp_v=findUPar(v);\n if(ulp_u==ulp_v)return;\n if(size[ulp_u]>=size[ulp_v]){\n parent[ulp_v]=ulp_u;\n size[ulp_u]+=size[ulp_v];\n }\n else{\n parent[ulp_u]=ulp_v;\n size[ulp_v]+=size[ulp_u];\n }\n }\n};\nclass Solution {\npublic:\n bool equationsPossible(vector<string>& equations) {\n DisjointSet ds(26);\n for(auto it:equations){\n int u=it[0]-\'a\';\n int v=it[3]-\'a\';\n if(it[1]==\'=\'){\n if(ds.findUPar(u)!=ds.findUPar(v)){\n ds.unionBySize(u,v);\n }\n }\n }\n for(auto it:equations){\n int u=it[0]-\'a\';\n int v=it[3]-\'a\';\n if(it[1]==\'!\'){\n if(ds.findUPar(u)==ds.findUPar(v))return false;\n }\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n\n graph = {}\n\n def find(char):\n if graph[char] == char:\n return char\n else:\n return find(graph[char])\n\n stack = [e for e in equations if e[1] == "="]\n inequs = [e for e in equations if e[1] == "!"]\n\n for char in "".join(equations):\n graph[char] = char\n\n while len(stack) > 0:\n e = stack.pop()\n graph[find(e[0])] = find(e[3])\n \n for ine in inequs:\n x = ine[0]; y = ine[3]\n if find(x) == find(y):\n return False\n return True\n```\n\n```Java []\nclass Solution {\n private int[] values;\n public boolean equationsPossible(String[] equations) {\n int size = equations.length;\n values = new int[26];\n \n for(int i = 0; i < 26; i++){\n values[i] = i;\n }\n for(String equation : equations){\n if(equation.charAt(1) == \'=\'){\n union(equation.charAt(0) - \'a\', equation.charAt(3) - \'a\');\n }\n }\n for(String equation : equations){\n if(equation.charAt(1) == \'!\' && find(equation.charAt(0) - \'a\') == find(equation.charAt(3) - \'a\')){\n return false;\n }\n }\n return true;\n }\n private void union(int a, int b){\n int rootA = find(a);\n int rootB = find(b);\n values[rootA] = rootB;\n }\n private int find(int a){\n int root = values[a];\n\n while(values[root] != root){\n root = values[root];\n }\n while(values[a] != root){\n int b = values[a];\n values[a] = root;\n a = b;\n }\n return root;\n }\n}\n```\n | 2 | Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query. | null |
python3 || 13 lines, sets || 1 T/M: 89%/67% | satisfiability-of-equality-equations | 0 | 1 | ```\nclass Solution: # Here\'s the plan:\n # 1) We make an undirected graph in which the nodes are integers\n # (as lower-case letters) and each edge connects integers\n # that are equal.\n # 2) We use a union-find process to determine the connected graphs\n # 3) We keep track of the pairs (a,b) such that a =! b. If the any\n # such pair are in the same connected graph, then return False,\n # otherwise return True.\n def equationsPossible(self, equations: List[str]) -> bool:\n parent, diff = {}, []\n\n def find(x):\n if x not in parent: return x\n else: return find(parent[x])\n\n for s in equations: # <-- 1)\n a, b = s[0], s[3]\n\n if s[1]== "=": # <-- 2)\n x, y = find(a), find(b)\n if x!=y:\n parent[y] = x\n else: \n diff.append((a,b)) # <-- 3)\n\n return all(find(a)!=find(b) for a, b in diff) | 28 | You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter. | null |
python3 || 13 lines, sets || 1 T/M: 89%/67% | satisfiability-of-equality-equations | 0 | 1 | ```\nclass Solution: # Here\'s the plan:\n # 1) We make an undirected graph in which the nodes are integers\n # (as lower-case letters) and each edge connects integers\n # that are equal.\n # 2) We use a union-find process to determine the connected graphs\n # 3) We keep track of the pairs (a,b) such that a =! b. If the any\n # such pair are in the same connected graph, then return False,\n # otherwise return True.\n def equationsPossible(self, equations: List[str]) -> bool:\n parent, diff = {}, []\n\n def find(x):\n if x not in parent: return x\n else: return find(parent[x])\n\n for s in equations: # <-- 1)\n a, b = s[0], s[3]\n\n if s[1]== "=": # <-- 2)\n x, y = find(a), find(b)\n if x!=y:\n parent[y] = x\n else: \n diff.append((a,b)) # <-- 3)\n\n return all(find(a)!=find(b) for a, b in diff) | 28 | Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query. | null |
Solution | broken-calculator | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int brokenCalc(int X, int Y) {\n int ops = 0;\n\n while (X < Y) {\n if (Y % 2 == 0)\n Y /= 2;\n else\n Y += 1;\n ++ops;\n }\n return ops + X - Y;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n ans = 0 \n while target > startValue:\n if not target % 2:\n target /= 2\n else:\n target += 1\n\n ans += 1\n\n return ans + int(startValue - target)\n```\n\n```Java []\nclass Solution {\n public int brokenCalc(int startValue, int target) {\n if(startValue >= target) return startValue - target;\n if(target % 2 == 0){\n return 1 + brokenCalc(startValue, target / 2);\n }\n return 1 + brokenCalc(startValue, target + 1);\n }\n}\n```\n | 1 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109` | null |
Solution | broken-calculator | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int brokenCalc(int X, int Y) {\n int ops = 0;\n\n while (X < Y) {\n if (Y % 2 == 0)\n Y /= 2;\n else\n Y += 1;\n ++ops;\n }\n return ops + X - Y;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n ans = 0 \n while target > startValue:\n if not target % 2:\n target /= 2\n else:\n target += 1\n\n ans += 1\n\n return ans + int(startValue - target)\n```\n\n```Java []\nclass Solution {\n public int brokenCalc(int startValue, int target) {\n if(startValue >= target) return startValue - target;\n if(target % 2 == 0){\n return 1 + brokenCalc(startValue, target / 2);\n }\n return 1 + brokenCalc(startValue, target + 1);\n }\n}\n```\n | 1 | There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions `x`, `y`, and `z` with `x < y < z`. You pick up the stone at either position `x` or position `z`, and move that stone to an integer position `k`, with `x < k < z` and `k != y`.
The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).
Return _an integer array_ `answer` _of length_ `2` _where_:
* `answer[0]` _is the minimum number of moves you can play, and_
* `answer[1]` _is the maximum number of moves you can play_.
**Example 1:**
**Input:** a = 1, b = 2, c = 5
**Output:** \[1,2\]
**Explanation:** Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.
**Example 2:**
**Input:** a = 4, b = 3, c = 2
**Output:** \[0,0\]
**Explanation:** We cannot make any moves.
**Example 3:**
**Input:** a = 3, b = 5, c = 1
**Output:** \[1,2\]
**Explanation:** Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.
**Constraints:**
* `1 <= a, b, c <= 100`
* `a`, `b`, and `c` have different values. | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.