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 |
|---|---|---|---|---|---|---|---|
Solution in Python 3 (With Detailed Proof) | divisor-game | 0 | 1 | The proof of why this works can be done formally using Mathematical Induction, specifically using <a href="https://en.wikipedia.org/wiki/Mathematical_induction#Complete_(strong)_induction">Strong Mathematical Induction</a>. However an informal proof will also suffice. Note that it is not enough to show that a player wh... | 177 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
Python Easy 1-liner | Faster than 80% | divisor-game | 0 | 1 | Simple. Alice wins on even numbers. Bob wins otherwise\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return not n % 2\n``` | 2 | 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... | null |
Python Easy 1-liner | Faster than 80% | divisor-game | 0 | 1 | Simple. Alice wins on even numbers. Bob wins otherwise\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return not n % 2\n``` | 2 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
1 liner python solution | divisor-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return n%2==0\n``` | 5 | 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... | null |
1 liner python solution | divisor-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return n%2==0\n``` | 5 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
Python One Liner | divisor-game | 0 | 1 | Yea...\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return True if n%2 == 0 else False\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... | null |
Python One Liner | divisor-game | 0 | 1 | Yea...\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return True if n%2 == 0 else False\n``` | 1 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
📚Divisor game || 🫱🏻🫲🏼Beginners friendly || 🐍Python... | divisor-game | 0 | 1 | # KARRAR\n>Divisor game...\n>>Brainteaser...\n>>>Game theory...\n>>>>Optimized code...\n>>>>>Beginners friendly...\n- PLEASE UPVOTE...\uD83D\uDC4D\uD83C\uDFFB\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach:\n Notice that if we subtract 1 from n...\n Answer w... | 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... | null |
📚Divisor game || 🫱🏻🫲🏼Beginners friendly || 🐍Python... | divisor-game | 0 | 1 | # KARRAR\n>Divisor game...\n>>Brainteaser...\n>>>Game theory...\n>>>>Optimized code...\n>>>>>Beginners friendly...\n- PLEASE UPVOTE...\uD83D\uDC4D\uD83C\uDFFB\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach:\n Notice that if we subtract 1 from n...\n Answer w... | 1 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
[Python] DP | divisor-game | 0 | 1 | ```python\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False for i in range(N+1)]\n for i in range(N+1):\n for j in range(1, i//2 + 1):\n if i % j == 0 and (not dp[i - j]):\n dp[i] = True\n break\n ... | 55 | 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... | null |
[Python] DP | divisor-game | 0 | 1 | ```python\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n dp = [False for i in range(N+1)]\n for i in range(N+1):\n for j in range(1, i//2 + 1):\n if i % j == 0 and (not dp[i - j]):\n dp[i] = True\n break\n ... | 55 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
Python3 - One liner, explained maths | divisor-game | 0 | 1 | This is a very nice math problem.\n\nA move is defined as choosing ```x```, a divisor of ```N``` which is lesser than ```N```, and replacing the number with ```N - x```. Since ```x``` is a divisor of ```N```, there exists some positive integer ```d``` such that```N = x*d```.\nNow, the new number will be of the form ```... | 24 | 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... | null |
Python3 - One liner, explained maths | divisor-game | 0 | 1 | This is a very nice math problem.\n\nA move is defined as choosing ```x```, a divisor of ```N``` which is lesser than ```N```, and replacing the number with ```N - x```. Since ```x``` is a divisor of ```N```, there exists some positive integer ```d``` such that```N = x*d```.\nNow, the new number will be of the form ```... | 24 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` ... | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
recursive approach | maximum-difference-between-node-and-ancestor | 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)$$ --... | 3 | 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... | null |
recursive approach | maximum-difference-between-node-and-ancestor | 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)$$ --... | 3 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Python DFS Iterative Solution | maximum-difference-between-node-and-ancestor | 0 | 1 | \n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n mini, maxi = ro... | 2 | 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... | null |
Python DFS Iterative Solution | maximum-difference-between-node-and-ancestor | 0 | 1 | \n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n mini, maxi = ro... | 2 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Python | DFS | O(N) | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition\nDFS walk through the binary tree. Save the max value and min value on the path. \n\n# Approach\nImplement a DFS helper function, with ancestor holds the max and min value so far. Recursive terminated at the leaves.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n# Def... | 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... | null |
Python | DFS | O(N) | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition\nDFS walk through the binary tree. Save the max value and min value on the path. \n\n# Approach\nImplement a DFS helper function, with ancestor holds the max and min value so far. Recursive terminated at the leaves.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n# Def... | 1 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Short and easy to understand solution with explanation. TC - O(N) and SC - O(1) | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis problem can be solved with 2 approaches and with different Time Complexity.\n\n**1st Approach (Naive Solution):-**\nWe can iterate over every node one by one and we will create another function which will traverse its ... | 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... | null |
Short and easy to understand solution with explanation. TC - O(N) and SC - O(1) | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis problem can be solved with 2 approaches and with different Time Complexity.\n\n**1st Approach (Naive Solution):-**\nWe can iterate over every node one by one and we will create another function which will traverse its ... | 1 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Python DFS Simple Solution | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition\nUsing DFS, we find the min and max values and their absolute difference in all the paths from root to leaf nodes.\n\n# Approach\nSolved using DFS Traversal of the Binary Tree.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\n# Definition for a binary tree node.\n# class ... | 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... | null |
Python DFS Simple Solution | maximum-difference-between-node-and-ancestor | 0 | 1 | # Intuition\nUsing DFS, we find the min and max values and their absolute difference in all the paths from root to leaf nodes.\n\n# Approach\nSolved using DFS Traversal of the Binary Tree.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\n# Definition for a binary tree node.\n# class ... | 1 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Python DFS approach | maximum-difference-between-node-and-ancestor | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n def dfs(root,mini,maxi,res):\n if not root:\n return\n res[0]=max(res[0],abs(mini-root.val),abs(maxi-root.val))\n mini = min(root.val, mini)\n maxi = max(... | 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... | null |
Python DFS approach | maximum-difference-between-node-and-ancestor | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n def dfs(root,mini,maxi,res):\n if not root:\n return\n res[0]=max(res[0],abs(mini-root.val),abs(maxi-root.val))\n mini = min(root.val, mini)\n maxi = max(... | 1 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Java/Python easy solution using max and min | Backtracking | maximum-difference-between-node-and-ancestor | 1 | 1 | # Please upvote if you find this helpful.\n```java []\nclass Solution {\n public int maxAncestorDiff(TreeNode root) {\n return dfs(root, root.val, root.val);\n }\n\n public int dfs(TreeNode node, int currmax, int currmin) {\n if (node == null) {\n return currmax - currmin;\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... | null |
Java/Python easy solution using max and min | Backtracking | maximum-difference-between-node-and-ancestor | 1 | 1 | # Please upvote if you find this helpful.\n```java []\nclass Solution {\n public int maxAncestorDiff(TreeNode root) {\n return dfs(root, root.val, root.val);\n }\n\n public int dfs(TreeNode node, int currmax, int currmin) {\n if (node == null) {\n return currmax - currmin;\n }\n... | 1 | Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`... | For each subtree, find the minimum value and maximum value of its descendants. |
Simple DP in Python. | longest-arithmetic-subsequence | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = defaultdict(dict)\n n = len(nums)\n ans = 1\n\n for i in range(n):\n for j in range(i):\n diff = nums[i] - nums[j]\n if diff not in dp[j]:\n ... | 3 | 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 `s... | null |
Simple DP in Python. | longest-arithmetic-subsequence | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = defaultdict(dict)\n n = len(nums)\n ans = 1\n\n for i in range(n):\n for j in range(i):\n diff = nums[i] - nums[j]\n if diff not in dp[j]:\n ... | 3 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
Python3 Solution | longest-arithmetic-subsequence | 0 | 1 | \n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n n=len(nums)\n dp=[{} for _ in range(n)]\n ans=0\n for i in range(n):\n dp[i][0]=1\n for j in range(i):\n diff=nums[i]-nums[j]\n\n if diff not in dp[j]:\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 `s... | null |
Python3 Solution | longest-arithmetic-subsequence | 0 | 1 | \n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n n=len(nums)\n dp=[{} for _ in range(n)]\n ans=0\n for i in range(n):\n dp[i][0]=1\n for j in range(i):\n diff=nums[i]-nums[j]\n\n if diff not in dp[j]:\n... | 2 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
✅Beats 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | longest-arithmetic-subsequence | 1 | 1 | # Intuition\nThe intuition behind this solution is to use dynamic programming to find the length of the longest arithmetic subsequence in the given array. We iterate through each pair of indices (i, j), where i > j, and check if we can extend the arithmetic subsequence ending at index i by including the element at inde... | 238 | 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 `s... | null |
✅Beats 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | longest-arithmetic-subsequence | 1 | 1 | # Intuition\nThe intuition behind this solution is to use dynamic programming to find the length of the longest arithmetic subsequence in the given array. We iterate through each pair of indices (i, j), where i > j, and check if we can extend the arithmetic subsequence ending at index i by including the element at inde... | 238 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
(Python) Longest Arithmetic Subsequence | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nTo find the length of the longest arithmetic subsequence, we can use dynamic programming. We\'ll define a dynamic programming table, dp, where dp[i][diff] represents the length of the longest arithmetic subsequence ending at index i with a common difference of diff.\n# Approach\n1. Initialize the dynamic p... | 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 `s... | null |
(Python) Longest Arithmetic Subsequence | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nTo find the length of the longest arithmetic subsequence, we can use dynamic programming. We\'ll define a dynamic programming table, dp, where dp[i][diff] represents the length of the longest arithmetic subsequence ending at index i with a common difference of diff.\n# Approach\n1. Initialize the dynamic p... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
Short and Simple 🐍🐍 | longest-arithmetic-subsequence | 0 | 1 | # Code\n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = {}; res = 2\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n diff = nums[j] - nums[i]\n dp[j, diff] = dp.get((i, diff), 1) + 1\n res = m... | 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 `s... | null |
Short and Simple 🐍🐍 | longest-arithmetic-subsequence | 0 | 1 | # Code\n```\nclass Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n dp = {}; res = 2\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n diff = nums[j] - nums[i]\n dp[j, diff] = dp.get((i, diff), 1) + 1\n res = m... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
[Python] DP solution with Japanese explanation | longest-arithmetic-subsequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- \u72B6\u614B\u3092\u914D\u5217\u3067\u306F\u306A\u304Fdict\u578B\u3067\u4FDD\u6301\u3059\u308B\u3068\u76F4\u611F\u7684\u306B\u89E3\u304D\u3084\u3059\u3044\u3002\n- \u5DEE\u5206\u3092\u56FA\u5B9A\u3057\u3066\u8003\u3048\u308B\u3068\u554F... | 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 `s... | null |
[Python] DP solution with Japanese explanation | longest-arithmetic-subsequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- \u72B6\u614B\u3092\u914D\u5217\u3067\u306F\u306A\u304Fdict\u578B\u3067\u4FDD\u6301\u3059\u308B\u3068\u76F4\u611F\u7684\u306B\u89E3\u304D\u3084\u3059\u3044\u3002\n- \u5DEE\u5206\u3092\u56FA\u5B9A\u3057\u3066\u8003\u3048\u308B\u3068\u554F... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
python 3 - top down DP with greedy | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nThis question is easy in terms of TC. But getting accepted is kind of "hard".\n\nObviously you need DP. But bottom up can get accepted way easier than top down. For top down DP, you need further optimization.\n\nSince for each diff value, you will ALWAYS get the closest one. So you don\'t need to check the... | 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 `s... | null |
python 3 - top down DP with greedy | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nThis question is easy in terms of TC. But getting accepted is kind of "hard".\n\nObviously you need DP. But bottom up can get accepted way easier than top down. For top down DP, you need further optimization.\n\nSince for each diff value, you will ALWAYS get the closest one. So you don\'t need to check the... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
DP Solution Explained by a Novice | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nHi everyone! Today\'s question was challenging maybe just because I\'m a novice at dp. I\'m preparing this section to those who are having hard time to solve dp questions. Hope it would be helpful.\n\nNow if the nums was sorted and we were trying to search arithmetic sequence in subsequent manner then the ... | 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 `s... | null |
DP Solution Explained by a Novice | longest-arithmetic-subsequence | 0 | 1 | # Intuition\nHi everyone! Today\'s question was challenging maybe just because I\'m a novice at dp. I\'m preparing this section to those who are having hard time to solve dp questions. Hope it would be helpful.\n\nNow if the nums was sorted and we were trying to search arithmetic sequence in subsequent manner then the ... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
Solution | longest-arithmetic-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int longestArithSeqLength(vector<int>& n)\n { \n int out{1};\n for(int i{}; i<501/out; ++i)\n for(int d[1001]{}, D[1001]{}; const auto & n: n)\n out=max({out, d[n+500]=d[n-i+500]+1, D[n]=D[n+i]+1});\n return out;\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 `s... | null |
Solution | longest-arithmetic-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int longestArithSeqLength(vector<int>& n)\n { \n int out{1};\n for(int i{}; i<501/out; ++i)\n for(int d[1001]{}, D[1001]{}; const auto & n: n)\n out=max({out, d[n+500]=d[n-i+500]+1, D[n]=D[n+i]+1});\n return out;\n }\n};\n```... | 1 | You are given a string `s` representing a list of words. Each letter in the word has one or more options.
* If there is one option, the letter is represented as is.
* If there is more than one option, then curly braces delimit the options. For example, `"{a,b,c} "` represents options `[ "a ", "b ", "c "]`.
For ex... | null |
Solution with Stack in Python3 | recover-a-tree-from-preorder-traversal | 0 | 1 | # Intuition\nHere we have:\n- a string `traversal`, that denotes to **Preorder Traversal** of a Binary Tree\n- it has nodes as integers and **dashes**, that represent a **depth** of a node\n- our goal is to **recreate** a Binary Tree\n\nAn algorithm implies to **parse** a `traversal` string.\nAt each step we define a *... | 2 | 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`.
... | null |
Solution with Stack in Python3 | recover-a-tree-from-preorder-traversal | 0 | 1 | # Intuition\nHere we have:\n- a string `traversal`, that denotes to **Preorder Traversal** of a Binary Tree\n- it has nodes as integers and **dashes**, that represent a **depth** of a node\n- our goal is to **recreate** a Binary Tree\n\nAn algorithm implies to **parse** a `traversal` string.\nAt each step we define a *... | 2 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
[Python] Minimal Code without Stack or Recursion, The Best | recover-a-tree-from-preorder-traversal | 0 | 1 | # Approach\nNote that the empty tree is supported as well.\n\nThe Best!\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n root = None\n for val in traversal.split(\'-\... | 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`.
... | null |
[Python] Minimal Code without Stack or Recursion, The Best | recover-a-tree-from-preorder-traversal | 0 | 1 | # Approach\nNote that the empty tree is supported as well.\n\nThe Best!\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n root = None\n for val in traversal.split(\'-\... | 1 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
Python Hard | recover-a-tree-from-preorder-traversal | 0 | 1 | ```\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 recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n mostRecent = {}\n ... | 0 | 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`.
... | null |
Python Hard | recover-a-tree-from-preorder-traversal | 0 | 1 | ```\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 recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n mostRecent = {}\n ... | 0 | You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample.
Calculate the following statistics:
* `minimum`: The minimum element in the sample.
* `maximum`: The max... | Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together. |
✔️ [Python3] 2-LINERS (*´▽`*), Explained | two-city-scheduling | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is simple: sort the input list by cost difference and then choose the first half of the persons in the sorted array to go to the city `a` and the rest of the persons to the city `b`.\n\nTime: **O(nlogn)** -... | 13 | 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... | null |
✔️ [Python3] 2-LINERS (*´▽`*), Explained | two-city-scheduling | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is simple: sort the input list by cost difference and then choose the first half of the persons in the sorted array to go to the city `a` and the rest of the persons to the city `b`.\n\nTime: **O(nlogn)** -... | 13 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
O(nlogn) time | O(n) space | solution explained | two-city-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to send half people to city A and half to B with minimum cost.\n\nUse the greedy approach. Sort the costs based on the cost difference between the cities. The lower the cost difference, the higher the priority to be sent to city A... | 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... | null |
O(nlogn) time | O(n) space | solution explained | two-city-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to send half people to city A and half to B with minimum cost.\n\nUse the greedy approach. Sort the costs based on the cost difference between the cities. The lower the cost difference, the higher the priority to be sent to city A... | 2 | _(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length ... | null |
Python 1-line sorting based solution | matrix-cells-in-distance-order | 0 | 1 | ```\ndef allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n return sorted([(i, j) for i in range(R) for j in range(C)], key=lambda p: abs(p[0] - r0) + abs(p[1] - c0))\n```\n\nThe same code, more readable:\n```\ndef allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[in... | 88 | 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 ... | null |
Python 1-line sorting based solution | matrix-cells-in-distance-order | 0 | 1 | ```\ndef allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n return sorted([(i, j) for i in range(R) for j in range(C)], key=lambda p: abs(p[0] - r0) + abs(p[1] - c0))\n```\n\nThe same code, more readable:\n```\ndef allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[in... | 88 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
python3 Solution | matrix-cells-in-distance-order | 0 | 1 | \n```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n res=[]\n for r in range(rows):\n for c in range(cols):\n res.append([r,c])\n \n res.sort(key=lambda x:abs(x[0]-rCenter)+ abs(x[1]-... | 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 ... | null |
python3 Solution | matrix-cells-in-distance-order | 0 | 1 | \n```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n res=[]\n for r in range(rows):\n for c in range(cols):\n res.append([r,c])\n \n res.sort(key=lambda x:abs(x[0]-rCenter)+ abs(x[1]-... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Using helper function & sort | matrix-cells-in-distance-order | 0 | 1 | ```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n # create a r, c matrix given the rows & cols\n # each element represents a list [r, c] where r is the row & c the col\n # find find the distances of all cells from the cente... | 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 ... | null |
Using helper function & sort | matrix-cells-in-distance-order | 0 | 1 | ```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n # create a r, c matrix given the rows & cols\n # each element represents a list [r, c] where r is the row & c the col\n # find find the distances of all cells from the cente... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Python3 || One-liner based on list comprehesion &sorted() || beats 95.3% runtime & 85.6% mem usage | matrix-cells-in-distance-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given 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 ... | null |
Python3 || One-liner based on list comprehesion &sorted() || beats 95.3% runtime & 85.6% mem usage | matrix-cells-in-distance-order | 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 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Simple & Easy Solution by Python 3 | matrix-cells-in-distance-order | 0 | 1 | ```\nclass Solution:\n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n cells = [[i, j] for i in range(R) for j in range(C)]\n return sorted(cells, key=lambda p: abs(p[0] - r0) + abs(p[1] - c0))\n``` | 6 | 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 ... | null |
Simple & Easy Solution by Python 3 | matrix-cells-in-distance-order | 0 | 1 | ```\nclass Solution:\n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n cells = [[i, j] for i in range(R) for j in range(C)]\n return sorted(cells, key=lambda p: abs(p[0] - r0) + abs(p[1] - c0))\n``` | 6 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Python3 - Nasty 1 liner | matrix-cells-in-distance-order | 0 | 1 | \n# Complexity\n- Time complexity:\nO(nlogn) \n\n- Space complexity:\no(n)\n\n# Code\n```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n\n return sorted(\n [[r, c] for r in range(0, rows, 1) for c in range(0, cols, 1)],\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 ... | null |
Python3 - Nasty 1 liner | matrix-cells-in-distance-order | 0 | 1 | \n# Complexity\n- Time complexity:\nO(nlogn) \n\n- Space complexity:\no(n)\n\n# Code\n```\nclass Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n\n return sorted(\n [[r, c] for r in range(0, rows, 1) for c in range(0, cols, 1)],\n ... | 1 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Easy solution ||python3 | matrix-cells-in-distance-order | 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 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 ... | null |
Easy solution ||python3 | matrix-cells-in-distance-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Logic Build with the question - python | matrix-cells-in-distance-order | 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 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 ... | null |
Logic Build with the question - python | matrix-cells-in-distance-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them u... | null |
Python 3 || 7 lines, sliding ptrs || T/M: 83% / 56% | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | ```\nclass Solution:\n def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:\n\n nums = list(accumulate(nums, initial = 0))\n mx1 = mx2 = mx3 = 0\n \n for sm0,sm1,sm2,sm3 in zip(nums, \n nums[firstLen:],\n ... | 6 | 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-overlap... | null |
Python 3 || 7 lines, sliding ptrs || T/M: 83% / 56% | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | ```\nclass Solution:\n def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:\n\n nums = list(accumulate(nums, initial = 0))\n mx1 = mx2 = mx3 = 0\n \n for sm0,sm1,sm2,sm3 in zip(nums, \n nums[firstLen:],\n ... | 6 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
[Python3] Linear Solution | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | # Approach\n1D Dynamic Programming\n- `dp_first[i]` represents the maximum sum of `firstLen` subarray using the first `i` elements in `nums`.\n- `dp_second[i]` represents the maximum sum of `secondLen` subarray using the first `i` elements in `nums`.\n- `dp[i]` represents the maximum sum of elements in two non-overlapp... | 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-overlap... | null |
[Python3] Linear Solution | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | # Approach\n1D Dynamic Programming\n- `dp_first[i]` represents the maximum sum of `firstLen` subarray using the first `i` elements in `nums`.\n- `dp_second[i]` represents the maximum sum of `secondLen` subarray using the first `i` elements in `nums`.\n- `dp[i]` represents the maximum sum of elements in two non-overlapp... | 1 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
PYTHON SOL || VERY SIMPLE || EXPLAINED || SLIDING WINDOW || | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | \n# EXPLANATION\n```\nFor every firstLen subarray find the maximum sum secondLen size subarray\n\nSay we have arr = [1,2,3,4,5,6,7,8,9,10] firstLen = 3 , secondLen = 4\n\nWe took the subarray with firstLen : [5,6,7]\nNow the secondLen subarray with max sum can be in\n1. [1,2,3,4]\n2. [8,9,10]\n\n\n\n```\n\n# CODE\n```\... | 5 | 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-overlap... | null |
PYTHON SOL || VERY SIMPLE || EXPLAINED || SLIDING WINDOW || | maximum-sum-of-two-non-overlapping-subarrays | 0 | 1 | \n# EXPLANATION\n```\nFor every firstLen subarray find the maximum sum secondLen size subarray\n\nSay we have arr = [1,2,3,4,5,6,7,8,9,10] firstLen = 3 , secondLen = 4\n\nWe took the subarray with firstLen : [5,6,7]\nNow the secondLen subarray with max sum can be in\n1. [1,2,3,4]\n2. [8,9,10]\n\n\n\n```\n\n# CODE\n```\... | 5 | Under the grammar given below, strings can represent a set of lowercase words. Let `R(expr)` denote the set of words the expression represents.
The grammar can best be understood through simple examples:
* Single letters represent a singleton set containing that word.
* `R( "a ") = { "a "}`
* `R( "w ") ... | We can use prefix sums to calculate any subarray sum quickly.
For each L length subarray, find the best possible M length subarray that occurs before and after it. |
Python by search in Trie [w/ Visualization] | stream-of-characters | 0 | 1 | Python by search in Trie\n\n---\n\n**Hint**:\n\nBecause [description](https://leetcode.com/problems/stream-of-characters/) asks us to search from tail, the **last k characters** queried, where k >= 1,\nwe build a trie and search word in **reversed order** to satisfy the requirement.\n\n---\n\n**Visualization**\n\n![ima... | 34 | 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 suf... | null |
🤌 A very different Trie solution that is O(len(words)), beats 93.1%. With explanation. 🤏 | stream-of-characters | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUnlike the editorial solurion, I don\'t reverse the strings.\nInstead, for the query step, I store the list of non-leaf nodes in the trie that can continue search to find a match. Since the stream comes char by char, I only need to iterat... | 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 suf... | null |
Python no trie | stream-of-characters | 0 | 1 | ```\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n self.dic = {}\n for word in words:\n if word[-1] not in self.dic:\n self.dic[word[-1]] = [word[:-1]]\n else:\n self.dic[word[-1]].append(word[:-1])\n \n self.string = ... | 7 | 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 suf... | null |
Simple TRIE solution (query in reverse idea) - beats 86% of the submitted solutions in terms of time | stream-of-characters | 0 | 1 | \n\n# Code\n```\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.isWord = False\n \nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n self.trie = TrieNode()\n self.stream = []\n\n for word in words:\n node = self.trie\n f... | 0 | 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 suf... | null |
Pythonic space-friendly solution | stream-of-characters | 0 | 1 | low memory impact by dint of python\'s "copy by reference" for dicts - hence our list of dicts does not require cloning\n```\nclass StreamChecker:\n\n def __init__(self, words: List[str]):\n self.bank = {}\n for word in words:\n d = self.bank\n for c in word:\n d.se... | 0 | 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 suf... | null |
Python3 Trie: Quick to understand solution / excellent readability & code quality | stream-of-characters | 0 | 1 | ```\n# W = # of words\n# L = avg. # of characters in a word\n# Time Complexity:\n# - Initialization: \n# - O(W\xD7L)\n# - Query: \n# - O(N) per call\n# Space Complexity:\n# - Trie: \n# - O(W\xD7L)\n# - Query: \n# - O(N) per call\nclass TrieNode:\n def __init__(self):\n... | 0 | 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 suf... | null |
Short Python3 solution; beats 98.92% RT, 70.04% M | stream-of-characters | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nI used the standard trie approach, which stores the words in reverse.\n\n# Complexity\n- Time complexity: $O(\\sum_{w\\in{\\tt words}} {\\rm len}(w))$ to build the trie and $O(\\max_{w\\in{\\tt words}} {\\rm len}(w))$ to query a letter\n<!-- Add your ... | 0 | 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 suf... | null |
Clean Python, beats 100% | moving-stones-until-consecutive | 0 | 1 | Good code should focus on readability instead of being as short as possible.\n\n```\nclass Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n x, y, z = sorted([a, b, c])\n if x + 1 == y == z - 1:\n min_steps = 0\n elif y - x > 2 and z - y > 2:\n mi... | 30 | 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 s... | null |
Just IF/Else Only | moving-stones-until-consecutive | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There 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 s... | null |
Python3 | DP approach | moving-stones-until-consecutive | 0 | 1 | # Intuition\nThis problem can be broken down into distinct subtasks whose solutions always remain the same. That is, for some unique configuration of states $(i,j,k)$, the answer for the least and most number of moves to reach the desired configuration of $(v,v+1,v+2)$ will be the aggregated minimum and aggregated maxi... | 0 | 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 s... | null |
Simple python3 solution | 3 cases | moving-stones-until-consecutive | 0 | 1 | # Complexity\n- Time complexity: $$O(1)$$\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``` python3 []\nclass Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a, b, c = sorte... | 0 | 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 s... | null |
Basic Approach Beats 88% | moving-stones-until-consecutive | 0 | 1 | # Approach\nYou need to just study the different types of cases that are mentioned in the below code :).\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a,b,c=sorted([a,b,c])\n d,e=... | 0 | 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 s... | null |
Python easy to understand beats 91.77% | moving-stones-until-consecutive | 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. -->\nminimum move:\n1.if no any gap between stones, return 0\n \u25CF\u25CF\u25CF\n2.if there have only a gap between 2 stones, return 1 \n \u25CF\u25C9\u25CF--\u25CB\n... | 0 | 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 s... | null |
Solution | moving-stones-until-consecutive | 1 | 1 | ```C++ []\nclass Solution {\n public:\n vector<int> numMovesStones(int a, int b, int c) {\n vector<int> nums = {a, b, c};\n\n sort(begin(nums), end(nums));\n\n if (nums[2] - nums[0] == 2)\n return {0, 0};\n return {min(nums[1] - nums[0], nums[2] - nums[1]) <= 2 ? 1 : 2,\n nums[2] - nums[0] ... | 0 | 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 s... | null |
| Python3 - 4 Lines | ✔ | moving-stones-until-consecutive | 0 | 1 | Python3 Solution\n\n# Code\n```\nclass Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a,b,c=sorted([a,b,c])\n if b-a==1 and c-b==1: return [0,b-(a+1)+c-(b+1)]\n elif b-a==1 or c-b==1 or c-a==1 or b-a==2 or c-b==2 or c-a==2: return [1,b-(a+1)+c-(b+1)]\n else: ... | 0 | 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 s... | null |
Python - easy space reduction with 3 rules | moving-stones-until-consecutive | 0 | 1 | # Intuition\nProblem is about reduction of spaces within range.\nTake spaces in between middle item and edge items, those spaces are area you can move within. Max steps is just sum of those.\nMin steps is reduced to 3 cases:\n1. If both zero then number of moves is 0.\n2. if just one is zero or one then there is one st... | 0 | 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 s... | null |
Clean Python | 6 lines | High Speed | O(n) time, O(1) space | Beats 96.9% | moving-stones-until-consecutive | 0 | 1 | \n# Code\n```\nclass Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n x, y, z = sorted([a, b, c])\n if x + 1 == y == z - 1: min_steps = 0\n elif y - x > 2 and z - y > 2: min_steps = 2\n else: min_steps = 1\n max_steps = z - x - 2\n return [min_ste... | 0 | 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 s... | null |
BFS | Beats 99% | Easy to Understand | coloring-a-border | 0 | 1 | Question is poorly articulated so I\'ll try to explain a bit.\nAdjacency - Two squares are adjacent id they are in one of the four (up, down, left, right) directions of each other.\nConnected Component - A connected component is a set of squares which are adjacent to at least one of the squares in the connected compone... | 2 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Detailed Explanation With Pictures | coloring-a-border | 0 | 1 | ` Suppose given `\n\n\n``` \nAll the neighbour(4 directions) of grid[1][3] including neighbours of the neighbours of \ngrid[1][3]\n```\n, the natural inclination is to solve this probl... | 2 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
80% TC and 76% Sc easy python solution | coloring-a-border | 0 | 1 | ```\ndef colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n\tm, n = len(grid), len(grid[0])\n\tdir = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\tdef calc(i, j, c):\n\t\tif not(0<=i<m and 0<=j<n): return 1\n\t\treturn grid[i][j] != c and grid[i][j] != -1\n\t\t\n\tdef dfs(i, j):\n\t\... | 1 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Simple python3 solution | DFS | coloring-a-border | 0 | 1 | # Complexity\n- Time complexity: $$O(m \\cdot n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m \\cdot n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, colo... | 0 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Python3: Simple DFS with a Stack, and a List of Border Cells | coloring-a-border | 0 | 1 | # Intuition\n\nTo find the border we can start with `(r, c)` and use DFS or BFS to find all cells on the border. We can record them in a `list`.\n\nThen for each cell in the border list we switch the color to `color`.\n\n# Approach\n\nSee the code docs for details. Briefly:\n* I used DFS without recursion (stack, not q... | 0 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.