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 |
|---|---|---|---|---|---|---|---|
Easy Python Game Theory DP solution 2D | stone-game-ii | 0 | 1 | # Intuition\nEach player at any point of the game will the stones he collects at this round and the number of stones left minus the max number of stones the other player can get.\n```\nF(M, i) = max(sum(pile[i:i + x]) + postfix[i+1] - F(max(M, x), i + x))\n```\n# Approach\n<!-- Describe your approach to solving the pro... | 1 | Alice and Bob continue their games with piles of stones. There are a number of piles **arranged in a row**, and each pile has a positive integer number of stones `piles[i]`. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first. Initially, `M = 1`.
On each playe... | We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively? |
Easy Python Game Theory DP solution 2D | stone-game-ii | 0 | 1 | # Intuition\nEach player at any point of the game will the stones he collects at this round and the number of stones left minus the max number of stones the other player can get.\n```\nF(M, i) = max(sum(pile[i:i + x]) + postfix[i+1] - F(max(M, x), i + x))\n```\n# Approach\n<!-- Describe your approach to solving the pro... | 1 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Dynamic Programming Solution for Longest Common Subsequence Problem | longest-common-subsequence | 0 | 1 | # Intuition\nThe problem requires finding the length of the longest common subsequence (LCS) between two given strings, text1 and text2. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\nTo solve this problem, w... | 1 | Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the r... | Notice that each row has no duplicates. Is counting the frequency of elements enough to find the answer? Use a data structure to count the frequency of elements. Find an element whose frequency equals the number of rows. |
Dynamic Programming Solution for Longest Common Subsequence Problem | longest-common-subsequence | 0 | 1 | # Intuition\nThe problem requires finding the length of the longest common subsequence (LCS) between two given strings, text1 and text2. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\nTo solve this problem, w... | 1 | Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand.
Return `True` if the array is **good** otherwi... | Try dynamic programming.
DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise |
[Java/Python 3] Two DP codes of O(mn) & O(min(m, n)) spaces w/ picture and analysis | longest-common-subsequence | 1 | 1 | **Update:**\n**Q & A:**\n\nQ1: What is the difference between `[[0] * m] * n` and `[[0] * m for _ in range(n)]`? Why does the former update all the rows of that column when I try to update one particular cell ?\nA1: `[[0] * m] * n` creates `n` references to the exactly same list objet: `[0] * m`; In contrast: `[[0] * m... | 286 | Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the r... | Notice that each row has no duplicates. Is counting the frequency of elements enough to find the answer? Use a data structure to count the frequency of elements. Find an element whose frequency equals the number of rows. |
[Java/Python 3] Two DP codes of O(mn) & O(min(m, n)) spaces w/ picture and analysis | longest-common-subsequence | 1 | 1 | **Update:**\n**Q & A:**\n\nQ1: What is the difference between `[[0] * m] * n` and `[[0] * m for _ in range(n)]`? Why does the former update all the rows of that column when I try to update one particular cell ?\nA1: `[[0] * m] * n` creates `n` references to the exactly same list objet: `[0] * m`; In contrast: `[[0] * m... | 286 | Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand.
Return `True` if the array is **good** otherwi... | Try dynamic programming.
DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise |
Solution | longest-common-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int longestCommonSubsequence(string text1, string text2) {\n int n = text1.size();\n int m = text2.size();\n \n int t[n+1][m+1];\n \n for(int i=0;i<n+1;i++)\n {\n t[i][0] = 0;\n }\n \n for(int i=1;... | 2 | Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the r... | Notice that each row has no duplicates. Is counting the frequency of elements enough to find the answer? Use a data structure to count the frequency of elements. Find an element whose frequency equals the number of rows. |
Solution | longest-common-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int longestCommonSubsequence(string text1, string text2) {\n int n = text1.size();\n int m = text2.size();\n \n int t[n+1][m+1];\n \n for(int i=0;i<n+1;i++)\n {\n t[i][0] = 0;\n }\n \n for(int i=1;... | 2 | Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand.
Return `True` if the array is **good** otherwi... | Try dynamic programming.
DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise |
Python very detailed solution with explanation and walkthrough step by step. | longest-common-subsequence | 0 | 1 | **Why might we want to solve the longest common subsequence problem?**\n\n> File comparison. The Unix program "diff" is used to compare two different versions of the same file, to determine what changes have been made to the file. It works by finding a longest common subsequence of the lines of the two files; any line ... | 207 | Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the r... | Notice that each row has no duplicates. Is counting the frequency of elements enough to find the answer? Use a data structure to count the frequency of elements. Find an element whose frequency equals the number of rows. |
Python very detailed solution with explanation and walkthrough step by step. | longest-common-subsequence | 0 | 1 | **Why might we want to solve the longest common subsequence problem?**\n\n> File comparison. The Unix program "diff" is used to compare two different versions of the same file, to determine what changes have been made to the file. It works by finding a longest common subsequence of the lines of the two files; any line ... | 207 | Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand.
Return `True` if the array is **good** otherwi... | Try dynamic programming.
DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise |
Python (96% beats) || Tabulation || DP || Memorization || Optimize Way + 2D Matrix way | longest-common-subsequence | 0 | 1 | Try this also Similar to LCS:\n[516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/solutions/4122315/python-9972-beats-tabulation-memorization-lcs/)\n[583. Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/solutions/4122272/... | 6 | Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the r... | Notice that each row has no duplicates. Is counting the frequency of elements enough to find the answer? Use a data structure to count the frequency of elements. Find an element whose frequency equals the number of rows. |
Python (96% beats) || Tabulation || DP || Memorization || Optimize Way + 2D Matrix way | longest-common-subsequence | 0 | 1 | Try this also Similar to LCS:\n[516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/solutions/4122315/python-9972-beats-tabulation-memorization-lcs/)\n[583. Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/solutions/4122272/... | 6 | Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand.
Return `True` if the array is **good** otherwi... | Try dynamic programming.
DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j]
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise |
80% TC and 76% SC easy python solution | decrease-elements-to-make-array-zigzag | 0 | 1 | ```\ndef movesToMakeZigzag(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tif(n == 1):\n\t\treturn 0\n\tt1 = t2 = 0\n\tfor i in range(n):\n\t\t# for t1\n\t\tif(i % 2):\n\t\t\tif(i == n-1):\n\t\t\t\tt1 += max(0, nums[i] - nums[i-1] + 1)\n\t\t\telse:\n\t\t\t\tt1 += max(0, nums[i] - min(nums[i+1], nums[i-1]) + 1)\n\n\t... | 1 | Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**.
An array `A` is a _zigzag array_ if either:
* Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] < A[4] > ...`
* OR, every odd-indexed element is greater than adjacent... | What if we model this problem as a graph problem? A house is a node and a pipe is a weighted edge. How to represent building wells in the graph model? Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses. The problem is now reduced to a Minimum Spanning Tree problem. |
80% TC and 76% SC easy python solution | decrease-elements-to-make-array-zigzag | 0 | 1 | ```\ndef movesToMakeZigzag(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tif(n == 1):\n\t\treturn 0\n\tt1 = t2 = 0\n\tfor i in range(n):\n\t\t# for t1\n\t\tif(i % 2):\n\t\t\tif(i == n-1):\n\t\t\t\tt1 += max(0, nums[i] - nums[i-1] + 1)\n\t\t\telse:\n\t\t\t\tt1 += max(0, nums[i] - min(nums[i+1], nums[i-1]) + 1)\n\n\t... | 1 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Python3: TC O(N), SC O(1): DP | decrease-elements-to-make-array-zigzag | 0 | 1 | # Intuition\n\nUsually a sequence problem can be solved starting at index `i` if you know the answer for `i+1`. This is because you can have the answer for `i+1:`, and then prepend `i`.\n\nIn this case there are two choices for prepending `i` to a zigzag sequence formed from `i+1`:\n1. up case: decrease `nums[i]` if ne... | 0 | Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**.
An array `A` is a _zigzag array_ if either:
* Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] < A[4] > ...`
* OR, every odd-indexed element is greater than adjacent... | What if we model this problem as a graph problem? A house is a node and a pipe is a weighted edge. How to represent building wells in the graph model? Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses. The problem is now reduced to a Minimum Spanning Tree problem. |
Python3: TC O(N), SC O(1): DP | decrease-elements-to-make-array-zigzag | 0 | 1 | # Intuition\n\nUsually a sequence problem can be solved starting at index `i` if you know the answer for `i+1`. This is because you can have the answer for `i+1:`, and then prepend `i`.\n\nIn this case there are two choices for prepending `i` to a zigzag sequence formed from `i+1`:\n1. up case: decrease `nums[i]` if ne... | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
O(n) solution that beats 98% | decrease-elements-to-make-array-zigzag | 0 | 1 | # 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```\nclass Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n \n n = len(nums)\n\n def check... | 0 | Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**.
An array `A` is a _zigzag array_ if either:
* Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] < A[4] > ...`
* OR, every odd-indexed element is greater than adjacent... | What if we model this problem as a graph problem? A house is a node and a pipe is a weighted edge. How to represent building wells in the graph model? Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses. The problem is now reduced to a Minimum Spanning Tree problem. |
O(n) solution that beats 98% | decrease-elements-to-make-array-zigzag | 0 | 1 | # 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```\nclass Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n \n n = len(nums)\n\n def check... | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9% | decrease-elements-to-make-array-zigzag | 0 | 1 | \n# Code\n```\nclass Solution:\n def movesToMakeZigzag(self, A):\n A = [float(\'inf\')] + A + [float(\'inf\')]\n res = [0, 0]\n for i in range(1, len(A) - 1):\n res[i % 2] += max(0, A[i] - min(A[i - 1], A[i + 1]) + 1)\n return min(res)\n``` | 0 | Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**.
An array `A` is a _zigzag array_ if either:
* Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] < A[4] > ...`
* OR, every odd-indexed element is greater than adjacent... | What if we model this problem as a graph problem? A house is a node and a pipe is a weighted edge. How to represent building wells in the graph model? Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses. The problem is now reduced to a Minimum Spanning Tree problem. |
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9% | decrease-elements-to-make-array-zigzag | 0 | 1 | \n# Code\n```\nclass Solution:\n def movesToMakeZigzag(self, A):\n A = [float(\'inf\')] + A + [float(\'inf\')]\n res = [0, 0]\n for i in range(1, len(A) - 1):\n res[i % 2] += max(0, A[i] - min(A[i - 1], A[i + 1]) + 1)\n return min(res)\n``` | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Python Simple O(n) Solution | Faster than 80% | decrease-elements-to-make-array-zigzag | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nJust calculate moves if we fix elements at odd indices and moves if we fix elements at even indices and return the minimum of both\n\n# Code\n```\nclass Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n if len(nums) == 1: re... | 0 | Given an array `nums` of integers, a _move_ consists of choosing any element and **decreasing it by 1**.
An array `A` is a _zigzag array_ if either:
* Every even-indexed element is greater than adjacent elements, ie. `A[0] > A[1] < A[2] > A[3] < A[4] > ...`
* OR, every odd-indexed element is greater than adjacent... | What if we model this problem as a graph problem? A house is a node and a pipe is a weighted edge. How to represent building wells in the graph model? Add a virtual node, connect it to houses with edges weighted by the costs to build wells in these houses. The problem is now reduced to a Minimum Spanning Tree problem. |
Python Simple O(n) Solution | Faster than 80% | decrease-elements-to-make-array-zigzag | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nJust calculate moves if we fix elements at odd indices and moves if we fix elements at even indices and return the minimum of both\n\n# Code\n```\nclass Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n if len(nums) == 1: re... | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Python 3 || 12 lines, w/ explanation and example || T/M: 90%/93% | binary-tree-coloring-game | 0 | 1 | The problem reduces to whether any of the three subgraphs with edges to node `x` have at least `(n+1)//2` nodes.\n\nHere\'s the plan:\n- Traverse the tree with `dfs` recursively.\n- For each `node`, rewrite `node.val` with the count of nodes in its subtree.\n- Evaluate whether `node` is x, and if so, determine whether ... | 4 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Python 3 || 12 lines, w/ explanation and example || T/M: 90%/93% | binary-tree-coloring-game | 0 | 1 | The problem reduces to whether any of the three subgraphs with edges to node `x` have at least `(n+1)//2` nodes.\n\nHere\'s the plan:\n- Traverse the tree with `dfs` recursively.\n- For each `node`, rewrite `node.val` with the count of nodes in its subtree.\n- Evaluate whether `node` is x, and if so, determine whether ... | 4 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Python, DFS | binary-tree-coloring-game | 0 | 1 | # Intuition\nWe have 3 different ways to choose the element that will beat opponent.\n1. Choose left sub-tree of opponent node\n2. Choose right sub-tree of opponent node\n3. Choose parent of opponent node\n\nThen we should calculate amount of nodes in left and right sub-trees. If one of them grater than sum of others -... | 2 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Python, DFS | binary-tree-coloring-game | 0 | 1 | # Intuition\nWe have 3 different ways to choose the element that will beat opponent.\n1. Choose left sub-tree of opponent node\n2. Choose right sub-tree of opponent node\n3. Choose parent of opponent node\n\nThen we should calculate amount of nodes in left and right sub-trees. If one of them grater than sum of others -... | 2 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Python 3 | DFS | One pass & Three pass | Explanation | binary-tree-coloring-game | 0 | 1 | ### Intuition\n- When first player chose a node `x`, then there are 3 branches left there for second player to choose (left subtree of `x`, right subtree of `x`, parent end of `x`. \n- For the second player, to ensure a win, we need to make sure that there is one branch that dominate the sum of the other 2 branches. As... | 14 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Python 3 | DFS | One pass & Three pass | Explanation | binary-tree-coloring-game | 0 | 1 | ### Intuition\n- When first player chose a node `x`, then there are 3 branches left there for second player to choose (left subtree of `x`, right subtree of `x`, parent end of `x`. \n- For the second player, to ensure a win, we need to make sure that there is one branch that dominate the sum of the other 2 branches. As... | 14 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Iterative BFS, python with my explanation | binary-tree-coloring-game | 0 | 1 | There are three "zones" in the tree:\n1. Left subtree under Red\n2. Right subtree under Red\n3. The remainder of the tree "above" Red\n\nBlue can pick the left child, right child, or parent of Red to control zones 1, 2, or 3, respectivley.\n\nTherefore we count the number of nodes in two of the zones. The third zone is... | 11 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Iterative BFS, python with my explanation | binary-tree-coloring-game | 0 | 1 | There are three "zones" in the tree:\n1. Left subtree under Red\n2. Right subtree under Red\n3. The remainder of the tree "above" Red\n\nBlue can pick the left child, right child, or parent of Red to control zones 1, 2, or 3, respectivley.\n\nTherefore we count the number of nodes in two of the zones. The third zone is... | 11 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
PYTHON SOL | LINEAR TIME | EXPLAINED WITH PICTURE | EASY | TRAVERSING | | binary-tree-coloring-game | 0 | 1 | # TIME AND SPACE COMPLEXITY\nRuntime: 36 ms, faster than 89.14% of Python3 online submissions for Binary Tree Coloring Game.\nMemory Usage: 14 MB, less than 52.72% of Python3 online submissions for Binary Tree Coloring Game.\n\n\n# EXPLANATION\n time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
PYTHON SOL | LINEAR TIME | EXPLAINED WITH PICTURE | EASY | TRAVERSING | | binary-tree-coloring-game | 0 | 1 | # TIME AND SPACE COMPLEXITY\nRuntime: 36 ms, faster than 89.14% of Python3 online submissions for Binary Tree Coloring Game.\nMemory Usage: 14 MB, less than 52.72% of Python3 online submissions for Binary Tree Coloring Game.\n\n\n# EXPLANATION\n 3 different subtrees neighboring x? |
Single Pass, easy and clear solution T/M: 80%/83% | binary-tree-coloring-game | 0 | 1 | ```\nclass Solution:\n def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n self.ans = True\n def f(a,b,c): return not (a+b<c or a+c<b or b+c<a)\n \n def count(root):\n if not root: return 0\n l, r = count(root.left), count(root.right)\... | 0 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Single Pass, easy and clear solution T/M: 80%/83% | binary-tree-coloring-game | 0 | 1 | ```\nclass Solution:\n def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n self.ans = True\n def f(a,b,c): return not (a+b<c or a+c<b or b+c<a)\n \n def count(root):\n if not root: return 0\n l, r = count(root.left), count(root.right)\... | 0 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Easy and modular python solution | binary-tree-coloring-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition for the problem comes from the fact that in this game, we are trying to limit the area that player 1 can conquer through his/her turn. In order to limit the area, we must place the y directly as a neighbour to the x since the pl... | 0 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
Easy and modular python solution | binary-tree-coloring-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition for the problem comes from the fact that in this game, we are trying to limit the area that player 1 can conquer through his/her turn. In order to limit the area, we must place the y directly as a neighbour to the x since the pl... | 0 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
BFS | binary-tree-coloring-game | 0 | 1 | # Intuition\nWe try to choose the neighbor of the node our opponent choose since if we choose one step further, our opponent obtains one more node, which is not a wise choice. \n\nIf the first player choose the root node, then we could win if subtrees rooted at root.left or root.right has more than a half of nodes.\n\n... | 0 | Two players play a turn based game on a binary tree. We are given the `root` of this binary tree, and the number of nodes `n` in the tree. `n` is odd, and each node has a distinct value from `1` to `n`.
Initially, the first player names a value `x` with `1 <= x <= n`, and the second player names a value `y` with `1 <=... | Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time.
Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window. |
BFS | binary-tree-coloring-game | 0 | 1 | # Intuition\nWe try to choose the neighbor of the node our opponent choose since if we choose one step further, our opponent obtains one more node, which is not a wise choice. \n\nIf the first player choose the root node, then we could win if subtrees rooted at root.left or root.right has more than a half of nodes.\n\n... | 0 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
EASY PYTHON SOLUTION USING BINARY SEARCH || 2-D ARRAY | snapshot-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*n*2)$$\n<!-- Add your space complex... | 3 | Implement a SnapshotArray that supports the following interface:
* `SnapshotArray(int length)` initializes an array-like data structure with the given length. **Initially, each element equals 0**.
* `void set(index, val)` sets the element at the given `index` to be equal to `val`.
* `int snap()` takes a snapshot... | The greatest common divisor must be a prefix of each string, so we can try all prefixes. |
Python3 Solution | snapshot-array | 0 | 1 | \n```\nclass SnapshotArray:\n\n def __init__(self, length: int):\n self.array=[[[-1,0]] for _ in range(length)]\n self.snap_id=0\n \n \n\n def set(self, index: int, val: int) -> None:\n self.array[index].append([self.snap_id,val])\n\n def snap(self) -> int:\n self.snap... | 1 | Implement a SnapshotArray that supports the following interface:
* `SnapshotArray(int length)` initializes an array-like data structure with the given length. **Initially, each element equals 0**.
* `void set(index, val)` sets the element at the given `index` to be equal to `val`.
* `int snap()` takes a snapshot... | The greatest common divisor must be a prefix of each string, so we can try all prefixes. |
Python Solution Using dictionary || Easy to understand | snapshot-array | 0 | 1 | ```\nclass SnapshotArray:\n\n def __init__(self, length: int):\n self.id = 0\n\t\t# to store current elm as index: val pair\n self.arr = {}\n\t\t# to store self.id: self.arr pairs i.e. snaps\n self._snap = {}\n\n def set(self, index: int, val: int) -> None:\n\t\t# set the value of index\n ... | 1 | Implement a SnapshotArray that supports the following interface:
* `SnapshotArray(int length)` initializes an array-like data structure with the given length. **Initially, each element equals 0**.
* `void set(index, val)` sets the element at the given `index` to be equal to `val`.
* `int snap()` takes a snapshot... | The greatest common divisor must be a prefix of each string, so we can try all prefixes. |
✅Simple Java✔ || C++✔ ||Python✔ || Easy To Understand | snapshot-array | 1 | 1 | # Please Vote up :))\n**For this problem we need to optimize on space so we can\'t tradeoff memory for time. If you save the whole array for every snapshot there will be "Memory limit exceeded" error.\n\nEssentially we are interested only in history of changes for the index, and it could be only few changes of one inde... | 74 | Implement a SnapshotArray that supports the following interface:
* `SnapshotArray(int length)` initializes an array-like data structure with the given length. **Initially, each element equals 0**.
* `void set(index, val)` sets the element at the given `index` to be equal to `val`.
* `int snap()` takes a snapshot... | The greatest common divisor must be a prefix of each string, so we can try all prefixes. |
Easy | Python Solution | Two Pointers | longest-chunked-palindrome-decomposition | 0 | 1 | # Code\n```\nclass Solution:\n def longestDecomposition(self, text: str) -> int:\n left = 0\n right = len(text)-1\n temp1 = ""\n temp2 = ""\n count = 0\n while left < right:\n temp1 += text[left]\n temp2 += text[right]\n if temp1 == temp2[::-... | 3 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
Close to O(n) Python, Rabin Karp Algorithm with two pointer technique with explanation (~40ms) | longest-chunked-palindrome-decomposition | 0 | 1 | [Important edit: I stand corrected. This algorithm isn\'t actually O(n), technically it\'s O(n^2). But in practice, it\'s very close to O(n), and will achieve substantially better performance than the more traditional O(n^2) approaches. In terms of real world performance/ progamming competitions, just pick a good big p... | 36 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
Python3 FT 80%: Repeatedly Check if Prefix == Suffix | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n\nThe problem can be reworded to\n* find the smallest prefix of `m` that is a suffix of `text`\n* remove these two fragments\n* repeat until the string is empty\n* how many fragments do you remove?\n\nIn this problem I guessed that the greedy solution was optimal, with the intuition that\n* if it wasn\'t t... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
String Slicing | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
python super easy to understand dp top down + two pointer | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
Solution using Two Pointers and Maximized Chunking with Example Walkthrough | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe "Longest Chunked Palindrome Decomposition" problem challenges us to split a given string into as many substrings as possible, with each substring being a palindrome (a string that reads the same forwards and backwards). The task is to... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
{Not hard} beats 97.41% | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
Longest Chunked Palindrome Decomposition || O(n) || Easy Solution | longest-chunked-palindrome-decomposition | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nitrate 1 side check other side \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 you... | 0 | You are given a string `text`. You should split it to k substrings `(subtext1, subtext2, ..., subtextk)` such that:
* `subtexti` is a **non-empty** string.
* The concatenation of all the substrings is equal to `text` (i.e., `subtext1 + subtext2 + ... + subtextk == text`).
* `subtexti == subtextk - i + 1` for all... | Flipping a subset of columns is like doing a bitwise XOR of some number K onto each row. We want rows X with X ^ K = all 0s or all 1s. This is the same as X = X^K ^K = (all 0s or all 1s) ^ K, so we want to count rows that have opposite bits set. For example, if K = 1, then we count rows X = (00000...001, or 1111....... |
Easy Python Solution | Gregorian calendar | Beginner Friendly | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The function aims to calculate the day of the year given a date in the format \'YYYY-MM-DD\'.\n- It considers leap years and non-leap years, adjusting the number of days in February accordingly.\n# Approach\n<!-- Describe your approach ... | 4 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Easy Python Solution | Gregorian calendar | Beginner Friendly | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The function aims to calculate the day of the year given a date in the format \'YYYY-MM-DD\'.\n- It considers leap years and non-leap years, adjusting the number of days in February accordingly.\n# Approach\n<!-- Describe your approach ... | 4 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
✅✅✅ Easy and faster than 99% solution | day-of-the-year | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n y,m,d = map(int, date.split(\'-\'))\n if (y%400==0 or (y%100!=0 and y%4==0)) and m>2:... | 1 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
✅✅✅ Easy and faster than 99% solution | day-of-the-year | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n y,m,d = map(int, date.split(\'-\'))\n if (y%400==0 or (y%100!=0 and y%4==0)) and m>2:... | 1 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
very easy solution for python 3 with comments | day-of-the-year | 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)$$ --... | 16 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
very easy solution for python 3 with comments | day-of-the-year | 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)$$ --... | 16 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Easy | Python Solution | String Manipulation | day-of-the-year | 0 | 1 | # Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n cal = {\n 1 : 31,\n 2 : 28,\n 3 : 31,\n 4 : 30,\n 5 : 31, \n 6 : 30, \n 7 : 31,\n 8 : 31, \n 9 : 30,\n 10 : 31,\n 11 ... | 2 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Easy | Python Solution | String Manipulation | day-of-the-year | 0 | 1 | # Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n cal = {\n 1 : 31,\n 2 : 28,\n 3 : 31,\n 4 : 30,\n 5 : 31, \n 6 : 30, \n 7 : 31,\n 8 : 31, \n 9 : 30,\n 10 : 31,\n 11 ... | 2 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
python 3 easy solution easy to under stand | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
python 3 easy solution easy to under stand | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Beats 86.32% || Day of the year | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Beats 86.32% || Day of the year | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Python 3 - Four liner - Simple Solution | day-of-the-year | 0 | 1 | ```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n y, m, d = map(int, date.split(\'-\'))\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29\n return d + sum(days[:m-1])\n``` | 36 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Python 3 - Four liner - Simple Solution | day-of-the-year | 0 | 1 | ```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n y, m, d = map(int, date.split(\'-\'))\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29\n return d + sum(days[:m-1])\n``` | 36 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
One line solution in Python | day-of-the-year | 0 | 1 | \n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n\n return datetime.date.fromisoformat(date).timetuple().tm_yday\n``` | 2 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
One line solution in Python | day-of-the-year | 0 | 1 | \n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n\n return datetime.date.fromisoformat(date).timetuple().tm_yday\n``` | 2 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Python - Easy Solution | day-of-the-year | 0 | 1 | \tclass Solution:\n\t\tdef dayOfYear(self, date: str) -> int:\n\t\t\tmap={\n\t\t\t\t0:0,\n\t\t\t\t1:31,\n\t\t\t\t2:28,\n\t\t\t\t3:31,\n\t\t\t\t4:30,\n\t\t\t\t5:31,\n\t\t\t\t6:30,\n\t\t\t\t7:31,\n\t\t\t\t8:31,\n\t\t\t\t9:30,\n\t\t\t\t10:31,\n\t\t\t\t11:30,\n\t\t\t\t12:31 \n\t\t\t}\n\n\t\t\tyear=int(date.s... | 1 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Python - Easy Solution | day-of-the-year | 0 | 1 | \tclass Solution:\n\t\tdef dayOfYear(self, date: str) -> int:\n\t\t\tmap={\n\t\t\t\t0:0,\n\t\t\t\t1:31,\n\t\t\t\t2:28,\n\t\t\t\t3:31,\n\t\t\t\t4:30,\n\t\t\t\t5:31,\n\t\t\t\t6:30,\n\t\t\t\t7:31,\n\t\t\t\t8:31,\n\t\t\t\t9:30,\n\t\t\t\t10:31,\n\t\t\t\t11:30,\n\t\t\t\t12:31 \n\t\t\t}\n\n\t\t\tyear=int(date.s... | 1 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
My banging solution | day-of-the-year | 0 | 1 | # Intuition\nI thought I just need to check for leap years and then add the days from the months before the one in the date. After that just add the days of the current month in the date.\n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, ... | 1 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
My banging solution | day-of-the-year | 0 | 1 | # Intuition\nI thought I just need to check for leap years and then add the days from the months before the one in the date. After that just add the days of the current month in the date.\n# Code\n```\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, ... | 1 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Python 3 -> 88% faster | day-of-the-year | 0 | 1 | ```\ndef dayOfYear(self, date: str) -> int:\n dates = date.split(\'-\')\n year, month, day = int(dates[0]), int(dates[1]), int(dates[2])\n \n months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n countDays = 0\n i = 0\n\t\t\n while i < month - 1:\n count... | 7 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Python 3 -> 88% faster | day-of-the-year | 0 | 1 | ```\ndef dayOfYear(self, date: str) -> int:\n dates = date.split(\'-\')\n year, month, day = int(dates[0]), int(dates[1]), int(dates[2])\n \n months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n countDays = 0\n i = 0\n\t\t\n while i < month - 1:\n count... | 7 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
O(1) solution using hashmap in Python | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I first approached this problem, my initial idea was to utilize hashmaps to tackle the task.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in the dayOfYear method is as follows:\n\nCreate a... | 0 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
O(1) solution using hashmap in Python | day-of-the-year | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I first approached this problem, my initial idea was to utilize hashmaps to tackle the task.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in the dayOfYear method is as follows:\n\nCreate a... | 0 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Clean Python code easy to understand 🔥🔥🔥| PYTHON | EASY | day-of-the-year | 0 | 1 | # Intuition\nfetch the date, year, month from the format using slicing. Aftwards check the given year is leap or not if it is a leap year then follow the days of month of that year. Add it to noOfDays variable.\n\n\n# Approach\ncreate a function leap year to check whether the year is leap or not.\nUse sum in built func... | 0 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Clean Python code easy to understand 🔥🔥🔥| PYTHON | EASY | day-of-the-year | 0 | 1 | # Intuition\nfetch the date, year, month from the format using slicing. Aftwards check the given year is leap or not if it is a leap year then follow the days of month of that year. Add it to noOfDays variable.\n\n\n# Approach\ncreate a function leap year to check whether the year is leap or not.\nUse sum in built func... | 0 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Python3: Slow but Reliable: Use datetime | day-of-the-year | 0 | 1 | # Intuition\n\nWhen handling date and time types, it\'s rarely the "correct" answer to handle conversions yourself.\n\nInstead, use the painstakingly writted and debugged stuff your system provides for you already!\n\nIf I\'m an interviewer, and someone starts busting out leap year modular arithmetic stuff, it\'s a red... | 0 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Python3: Slow but Reliable: Use datetime | day-of-the-year | 0 | 1 | # Intuition\n\nWhen handling date and time types, it\'s rarely the "correct" answer to handle conversions yourself.\n\nInstead, use the painstakingly writted and debugged stuff your system provides for you already!\n\nIf I\'m an interviewer, and someone starts busting out leap year modular arithmetic stuff, it\'s a red... | 0 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
Wins 94.87% , Day of the Year easy solution | day-of-the-year | 0 | 1 | """#For example, 1600 and 2000 are leap years because they are divisible by 400. However, #1700, 1800, and 1900 are not leap years because they are not divisible by 400.\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n calender1=[31,28,31,30,31,30,31,31,30,31,30,31]\n calender2=[31,29,31,30,... | 0 | Given a string `date` representing a [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) date formatted as `YYYY-MM-DD`, return _the day number of the year_.
**Example 1:**
**Input:** date = "2019-01-09 "
**Output:** 9
**Explanation:** Given date is the 9th day of the year in 2019.
**Example 2:**... | null |
Wins 94.87% , Day of the Year easy solution | day-of-the-year | 0 | 1 | """#For example, 1600 and 2000 are leap years because they are divisible by 400. However, #1700, 1800, and 1900 are not leap years because they are not divisible by 400.\nclass Solution:\n def dayOfYear(self, date: str) -> int:\n calender1=[31,28,31,30,31,30,31,31,30,31,30,31]\n calender2=[31,29,31,30,... | 0 | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after... | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). |
😎Python3! As short as it gets! [T:96%] O(n*target) | number-of-dice-rolls-with-target-sum | 0 | 1 | Enjoy:\n```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n MOD = 1000 * 1000 * 1000 + 7 \n dp = defaultdict(int)\n dp[0] = 1 \n for c in range(n):\n sm = defaultdict(int)\n for i in range(target+1):\n sm[i] = sm[i-... | 4 | You have `n` dice, and each die has `k` faces numbered from `1` to `k`.
Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ `kn` _total ways)_ _to roll the dice, so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** `109 + ... | null |
😎Python3! As short as it gets! [T:96%] O(n*target) | number-of-dice-rolls-with-target-sum | 0 | 1 | Enjoy:\n```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n MOD = 1000 * 1000 * 1000 + 7 \n dp = defaultdict(int)\n dp[0] = 1 \n for c in range(n):\n sm = defaultdict(int)\n for i in range(target+1):\n sm[i] = sm[i-... | 4 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:... | Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far. |
86.7% Faster Solution || DP | number-of-dice-rolls-with-target-sum | 0 | 1 | ```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n mod = 10**9+7\n dp = [[0]*(target + 1) for _ in range(n + 1)]\n dp[0][0] = 1\n if target < 1 or target > n*k: return 0\n for x in range(1, n + 1):\n for y in range(1, k + 1):\n ... | 2 | You have `n` dice, and each die has `k` faces numbered from `1` to `k`.
Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ `kn` _total ways)_ _to roll the dice, so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** `109 + ... | null |
86.7% Faster Solution || DP | number-of-dice-rolls-with-target-sum | 0 | 1 | ```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n mod = 10**9+7\n dp = [[0]*(target + 1) for _ in range(n + 1)]\n dp[0][0] = 1\n if target < 1 or target > n*k: return 0\n for x in range(1, n + 1):\n for y in range(1, k + 1):\n ... | 2 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:... | Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far. |
✅[Python C++] ⏱90% Fast || Easy || Recursion + Bottom-Up | number-of-dice-rolls-with-target-sum | 0 | 1 | We can fix one die with any number `f`(f<k=number of faces) and from remaining `n-1` dices we can make the target = `targert-f`\n\n**Python**\n\n1. Recursive Solution using memorisation(`@lru_cache`)\n```\nclass Solution:\n @lru_cache(maxsize=None)\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:... | 2 | You have `n` dice, and each die has `k` faces numbered from `1` to `k`.
Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ `kn` _total ways)_ _to roll the dice, so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** `109 + ... | null |
✅[Python C++] ⏱90% Fast || Easy || Recursion + Bottom-Up | number-of-dice-rolls-with-target-sum | 0 | 1 | We can fix one die with any number `f`(f<k=number of faces) and from remaining `n-1` dices we can make the target = `targert-f`\n\n**Python**\n\n1. Recursive Solution using memorisation(`@lru_cache`)\n```\nclass Solution:\n @lru_cache(maxsize=None)\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:... | 2 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:... | Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far. |
python dp solution | number-of-dice-rolls-with-target-sum | 0 | 1 | ```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n def func(i,n,k,tr,dic):\n if i==n and tr==0:\n return 1\n if i>=n or tr<=0:\n return 0\n if (i,tr) in dic:\n return dic[(i,tr)]\n sm... | 2 | You have `n` dice, and each die has `k` faces numbered from `1` to `k`.
Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ `kn` _total ways)_ _to roll the dice, so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** `109 + ... | null |
python dp solution | number-of-dice-rolls-with-target-sum | 0 | 1 | ```\nclass Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n def func(i,n,k,tr,dic):\n if i==n and tr==0:\n return 1\n if i>=n or tr<=0:\n return 0\n if (i,tr) in dic:\n return dic[(i,tr)]\n sm... | 2 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:... | Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far. |
O(target*n*k) using Memorize Dynamic Programming | number-of-dice-rolls-with-target-sum | 0 | 1 | **Main Idea**:\n+ Applying memorize dynamic programming as follows:\n```\ndp[target][n] = sum(\n dp[target - ki][n-1] where target-ki>=0, n>=1\n)\ndp[target][n] = 0 when target==0 or target>k\ndp[target][n] = 1 when n = 1 and 1<=target<=k\n```\n\n**Code**:\n```\nclass Solution:\n def numRollsToTarget(self, n: int... | 1 | You have `n` dice, and each die has `k` faces numbered from `1` to `k`.
Given three integers `n`, `k`, and `target`, return _the number of possible ways (out of the_ `kn` _total ways)_ _to roll the dice, so the sum of the face-up numbers equals_ `target`. Since the answer may be too large, return it **modulo** `109 + ... | null |
O(target*n*k) using Memorize Dynamic Programming | number-of-dice-rolls-with-target-sum | 0 | 1 | **Main Idea**:\n+ Applying memorize dynamic programming as follows:\n```\ndp[target][n] = sum(\n dp[target - ki][n-1] where target-ki>=0, n>=1\n)\ndp[target][n] = 0 when target==0 or target>k\ndp[target][n] = 1 when n = 1 and 1<=target<=k\n```\n\n**Code**:\n```\nclass Solution:\n def numRollsToTarget(self, n: int... | 1 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box.
Your task is to move the box `'B'` to the target position `'T'` under the following rules:... | Use dynamic programming. The states are how many dice are remaining, and what sum total you have rolled so far. |
Python 3 || 9 lines, groupby, w/ example || T/M: 95% / 15% | swap-for-longest-repeated-character-substring | 0 | 1 | ```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int: # Example: text = "babbab"\n\n c = Counter(text) # c = {\'a\':2, \'b\':4}\n\n ch, ct = zip(*[(k, sum(1 for _ in g)) # ch = (\'b\',\'a\'... | 6 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python 3 || 9 lines, groupby, w/ example || T/M: 95% / 15% | swap-for-longest-repeated-character-substring | 0 | 1 | ```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int: # Example: text = "babbab"\n\n c = Counter(text) # c = {\'a\':2, \'b\':4}\n\n ch, ct = zip(*[(k, sum(1 for _ in g)) # ch = (\'b\',\'a\'... | 6 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python, very easy to understand approach | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\nidea is simple we can have only two characaters in a window and one should have freq = 1\n\n# Approach\nif size of window ==2 we try to see if current freq of\ncharacter (other than 1 freq character) is less than that of total freq of that character if yes we can replace this char with 1 freq char if not w... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python, very easy to understand approach | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\nidea is simple we can have only two characaters in a window and one should have freq = 1\n\n# Approach\nif size of window ==2 we try to see if current freq of\ncharacter (other than 1 freq character) is less than that of total freq of that character if yes we can replace this char with 1 freq char if not w... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python 3 run length encoding + Check Triplets | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python 3 run length encoding + Check Triplets | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python 3| O(N) | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python 3| O(N) | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
easiest python solution, beginner friendly | swap-for-longest-repeated-character-substring | 0 | 1 | \n\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n # Important Question\n \n d=defaultdict(int); out=0; res=0; i=0; c=Counter(text)\n \n for j in range(len(text)):\n d[text[j]]+=1\n while len(d)>2 or (min(d.values())>1 and len(d)>1):\n ... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
easiest python solution, beginner friendly | swap-for-longest-repeated-character-substring | 0 | 1 | \n\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n # Important Question\n \n d=defaultdict(int); out=0; res=0; i=0; c=Counter(text)\n \n for j in range(len(text)):\n d[text[j]]+=1\n while len(d)>2 or (min(d.values())>1 and len(d)>1):\n ... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.