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
powerful-integers
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> powerfulIntegers(int x, int y, int bound) {\n vector<int>powx;\n vector<int>powy;\n powx.push_back(1);\n powy.push_back(1);\n if(x!=1){\n int pow=x;\n while(pow<bound){\n powx.push_back(pow);\n pow*=x;\n }\n }\n if(y!=1){\n int pow=y;\n while(pow<bound){\n powy.push_back(pow);\n pow*=y;\n }\n }\n set<int>s;\n for(auto i : powx){\n for(auto j : powy){\n if(i+j<=bound)s.insert(i+j);\n }\n }\n vector<int>ans(s.begin(),s.end());\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n\n def getset(num):\n if num == 1:\n return [1]\n cur = 1\n toret = []\n while cur < bound:\n toret.append(cur)\n cur *= num\n return toret\n\n xlist = getset(x)\n\n ylist = getset(y)\n print(xlist)\n print(ylist)\n ans = set()\n for num in xlist:\n for other in ylist:\n if num + other <= bound:\n ans.add(num + other)\n else:\n break\n return ans\n```\n\n```Java []\nclass Solution {\n public List<Integer> powerfulIntegers(int x, int y, int bound) {\n Set<Integer> ans = new HashSet<>();\n for (int xi = 1; xi < bound; xi *= x) {\n for (int yj = 1; xi + yj <= bound; yj *= y) {\n ans.add(xi + yj);\n if (y == 1) break;\n }\n if (x == 1) break;\n }\n return new ArrayList<Integer>(ans);\n }\n}\n```\n
1
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
970. Powerful Integers
powerful-integers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# class Solution:\n# def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n# l = []\n# for i in range(0,y +1):\n# for j in range(0,y+1):\n# l.append(x ** i+y **j)\n# s = sorted(list(set(sorted(l))))\n# rl = [d for d in s if d <= bound]\n# return rl\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n res , i , j = set() , 0 , 0\n tempx , tempy= x**i , y**j\n while tempx<bound:\n while tempx + tempy <= bound:\n res.add(tempx+tempy)\n j+=1\n tempy = y**j\n if y==1: break\n i+=1\n tempx = x**i\n j = 0\n tempy = y**j\n if x==1: break\n return list(res)\n```
0
Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`. An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`. You may return the answer in **any order**. In your answer, each value should occur **at most once**. **Example 1:** **Input:** x = 2, y = 3, bound = 10 **Output:** \[2,3,4,5,7,9,10\] **Explanation:** 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32 **Example 2:** **Input:** x = 3, y = 5, bound = 15 **Output:** \[2,4,6,8,10,14\] **Constraints:** * `1 <= x, y <= 100` * `0 <= bound <= 106`
null
970. Powerful Integers
powerful-integers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# class Solution:\n# def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n# l = []\n# for i in range(0,y +1):\n# for j in range(0,y+1):\n# l.append(x ** i+y **j)\n# s = sorted(list(set(sorted(l))))\n# rl = [d for d in s if d <= bound]\n# return rl\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n res , i , j = set() , 0 , 0\n tempx , tempy= x**i , y**j\n while tempx<bound:\n while tempx + tempy <= bound:\n res.add(tempx+tempy)\n j+=1\n tempy = y**j\n if y==1: break\n i+=1\n tempx = x**i\n j = 0\n tempy = y**j\n if x==1: break\n return list(res)\n```
0
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
[Python3] Brutal Force
powerful-integers
0
1
# Code\n```\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n x_max = 0\n while x!=1 and x**x_max < bound:\n x_max+=1\n \n y_max = 0\n while y!=1 and y**y_max < bound:\n y_max+=1\n \n hs = set()\n for i in range(x_max+1):\n for j in range(y_max+1):\n cand = x**i + y**j\n if cand <= bound:\n hs.add(cand)\n\n return list(hs)\n```
0
Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`. An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`. You may return the answer in **any order**. In your answer, each value should occur **at most once**. **Example 1:** **Input:** x = 2, y = 3, bound = 10 **Output:** \[2,3,4,5,7,9,10\] **Explanation:** 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32 **Example 2:** **Input:** x = 3, y = 5, bound = 15 **Output:** \[2,4,6,8,10,14\] **Constraints:** * `1 <= x, y <= 100` * `0 <= bound <= 106`
null
[Python3] Brutal Force
powerful-integers
0
1
# Code\n```\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n x_max = 0\n while x!=1 and x**x_max < bound:\n x_max+=1\n \n y_max = 0\n while y!=1 and y**y_max < bound:\n y_max+=1\n \n hs = set()\n for i in range(x_max+1):\n for j in range(y_max+1):\n cand = x**i + y**j\n if cand <= bound:\n hs.add(cand)\n\n return list(hs)\n```
0
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
[35ms] Use min heap to find minimum sum 1 by 1
powerful-integers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nincrease i and j by 1 to find minimum sum till over-bound\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. use a min-heap q to store sum and i,j with tuple (v, i, j)\n2. use a seen set to store (i, j) avoiding re-visit\n3. break until q empty or over-bound\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n import heapq\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n q = [(2, 0, 0)]\n seen = set()\n ans = []\n while q:\n val, i, j = heapq.heappop(q)\n if val > bound:\n break\n if not ans or val != ans[-1]:\n ans.append(val)\n\n v1 = x**i + y**(j+1)\n if y != 1 and (i, j+1) not in seen:\n heapq.heappush(q, (v1, i, j+1))\n seen.add((i, j+1))\n\n v2 = x**(i+1) + y**j\n if x != 1 and (i+1, j) not in seen:\n heapq.heappush(q, (v2, i+1, j))\n seen.add((i+1, j))\n return ans\n```
0
Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`. An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`. You may return the answer in **any order**. In your answer, each value should occur **at most once**. **Example 1:** **Input:** x = 2, y = 3, bound = 10 **Output:** \[2,3,4,5,7,9,10\] **Explanation:** 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32 **Example 2:** **Input:** x = 3, y = 5, bound = 15 **Output:** \[2,4,6,8,10,14\] **Constraints:** * `1 <= x, y <= 100` * `0 <= bound <= 106`
null
[35ms] Use min heap to find minimum sum 1 by 1
powerful-integers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nincrease i and j by 1 to find minimum sum till over-bound\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. use a min-heap q to store sum and i,j with tuple (v, i, j)\n2. use a seen set to store (i, j) avoiding re-visit\n3. break until q empty or over-bound\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n import heapq\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n q = [(2, 0, 0)]\n seen = set()\n ans = []\n while q:\n val, i, j = heapq.heappop(q)\n if val > bound:\n break\n if not ans or val != ans[-1]:\n ans.append(val)\n\n v1 = x**i + y**(j+1)\n if y != 1 and (i, j+1) not in seen:\n heapq.heappush(q, (v1, i, j+1))\n seen.add((i, j+1))\n\n v2 = x**(i+1) + y**j\n if x != 1 and (i+1, j) not in seen:\n heapq.heappush(q, (v2, i+1, j))\n seen.add((i+1, j))\n return ans\n```
0
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Solution
flip-binary-tree-to-match-preorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){\n if(root == NULL || ind == voyage.size()){\n ind--;\n return true;\n }\n if(root->val != voyage[ind]){\n ans.clear();\n ans.push_back(-1);\n return false;\n }\n if(root->left && root->left->val != voyage[ind+1]){\n\t\t\tTreeNode *temp = root->left;\n\t\t\troot->left = root->right;\n\t\t\troot->right = temp;\n\t\t\t\n\t\t\tans.push_back(root->val);\n }\n return helper(++ind, root->left, voyage, ans) &&\n helper(++ind, root->right, voyage, ans);\n }\n vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {\n int ind = 0;\n vector<int> ans;\n helper(ind, root, voyage, ans);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n \n if not root:\n return False\n \n self.ans = []\n self.idx = 0\n \n def recurse(node):\n if not node:\n return True\n \n if node.val != voyage[self.idx]:\n return False\n \n self.idx += 1\n if node.left and (node.left.val != voyage[self.idx]):\n if node.right:\n self.ans.append(node.val)\n return recurse(node.right) and recurse(node.left)\n \n else:\n return recurse(node.left) and recurse(node.right)\n \n if recurse(root):\n return self.ans\n return [-1]\n```\n\n```Java []\nclass Solution {\n int vix = 0;\n List<Integer> ans = new ArrayList<>();\n private void dfs(TreeNode node, int[] V) {\n if (node == null || (ans.size() != 0 && ans.get(0) == -1)) return;\n if (node.val != V[vix++])\n ans = new ArrayList<Integer>(Arrays.asList(-1));\n else if (node.left != null && node.left.val != V[vix]) {\n ans.add(node.val);\n dfs(node.right, V);\n dfs(node.left, V);\n } else {\n dfs(node.left, V);\n dfs(node.right, V);\n }\n }\n public List<Integer> flipMatchVoyage(TreeNode root, int[] V) {\n dfs(root, V);\n return ans;\n }\n}\n```\n
1
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Solution
flip-binary-tree-to-match-preorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){\n if(root == NULL || ind == voyage.size()){\n ind--;\n return true;\n }\n if(root->val != voyage[ind]){\n ans.clear();\n ans.push_back(-1);\n return false;\n }\n if(root->left && root->left->val != voyage[ind+1]){\n\t\t\tTreeNode *temp = root->left;\n\t\t\troot->left = root->right;\n\t\t\troot->right = temp;\n\t\t\t\n\t\t\tans.push_back(root->val);\n }\n return helper(++ind, root->left, voyage, ans) &&\n helper(++ind, root->right, voyage, ans);\n }\n vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {\n int ind = 0;\n vector<int> ans;\n helper(ind, root, voyage, ans);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n \n if not root:\n return False\n \n self.ans = []\n self.idx = 0\n \n def recurse(node):\n if not node:\n return True\n \n if node.val != voyage[self.idx]:\n return False\n \n self.idx += 1\n if node.left and (node.left.val != voyage[self.idx]):\n if node.right:\n self.ans.append(node.val)\n return recurse(node.right) and recurse(node.left)\n \n else:\n return recurse(node.left) and recurse(node.right)\n \n if recurse(root):\n return self.ans\n return [-1]\n```\n\n```Java []\nclass Solution {\n int vix = 0;\n List<Integer> ans = new ArrayList<>();\n private void dfs(TreeNode node, int[] V) {\n if (node == null || (ans.size() != 0 && ans.get(0) == -1)) return;\n if (node.val != V[vix++])\n ans = new ArrayList<Integer>(Arrays.asList(-1));\n else if (node.left != null && node.left.val != V[vix]) {\n ans.add(node.val);\n dfs(node.right, V);\n dfs(node.left, V);\n } else {\n dfs(node.left, V);\n dfs(node.right, V);\n }\n }\n public List<Integer> flipMatchVoyage(TreeNode root, int[] V) {\n dfs(root, V);\n return ans;\n }\n}\n```\n
1
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Python3 Clear Solution with stack | Pre-Order Traversal
flip-binary-tree-to-match-preorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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 flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n ans = []\n st = collections.deque()\n # 12345\n # root.val\n # stack\n st.append(root)\n i = 0\n\n while st and i < len(voyage):\n #print(st)\n node = st.pop()\n if not node:\n continue\n #print(node.val)\n if voyage[i] != node.val:\n return [-1]\n \n if node.left and node.left.val != voyage[i+1]:\n st.append(node.left)\n st.append(node.right)\n ans.append(node.val)\n elif not node.left and node.right and node.right.val != voyage[i+1]:\n # not node.left\n st.append(node.right)\n ans.append(node.val)\n else:\n st.append(node.right)\n st.append(node.left)\n \n i += 1\n \n #st.append(node.right)\n #st.append(node.left)\n\n return ans\n\n\n```
0
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Python3 Clear Solution with stack | Pre-Order Traversal
flip-binary-tree-to-match-preorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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 flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n ans = []\n st = collections.deque()\n # 12345\n # root.val\n # stack\n st.append(root)\n i = 0\n\n while st and i < len(voyage):\n #print(st)\n node = st.pop()\n if not node:\n continue\n #print(node.val)\n if voyage[i] != node.val:\n return [-1]\n \n if node.left and node.left.val != voyage[i+1]:\n st.append(node.left)\n st.append(node.right)\n ans.append(node.val)\n elif not node.left and node.right and node.right.val != voyage[i+1]:\n # not node.left\n st.append(node.right)\n ans.append(node.val)\n else:\n st.append(node.right)\n st.append(node.left)\n \n i += 1\n \n #st.append(node.right)\n #st.append(node.left)\n\n return ans\n\n\n```
0
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Simple Python DFS Explained | Beats 97 %
flip-binary-tree-to-match-preorder-traversal
0
1
# Intuition\nProrder Traversal -> mid , left, right\nWe are given that any point of time we can flip the binary tree. This rises three cases\n`1. flip is not required`\n`2. flip is required -> add the root node of the subtree in ans`\n`3. even with and without flipping cant match the pattern return -1`\n\n***So how to check if flip is required or not?***\n\nMatch the current node val to current voyage pointer val if they are equal increment the pointer\nnow check if the **left subtree == new voyage pointer val**\nif it is -> no flip required thus call left subtree first then rightsubtree\nif they are not equal -> flip maybe required then call right subtree\nif even after flipping value doesnt match thus it cant meet the voyage order return -1.\n\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 flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n ans = []\n p = 0\n flag = False\n def dfs(node):\n nonlocal ans, p, flag\n if not node:\n return ans\n if node.val != voyage[p]: #even after flip/ no flip value doesnt match thus order cant be followed\n flag = True\n return\n p += 1 # if value matched increment curr pointer\n if node.left and node.left.val != voyage[p]: # flip required\n ans.append(node.val)\n dfs(node.right)\n dfs(node.left)\n else: # flip not required\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n if flag:\n return [-1]\n return ans\n\n \n```
0
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Simple Python DFS Explained | Beats 97 %
flip-binary-tree-to-match-preorder-traversal
0
1
# Intuition\nProrder Traversal -> mid , left, right\nWe are given that any point of time we can flip the binary tree. This rises three cases\n`1. flip is not required`\n`2. flip is required -> add the root node of the subtree in ans`\n`3. even with and without flipping cant match the pattern return -1`\n\n***So how to check if flip is required or not?***\n\nMatch the current node val to current voyage pointer val if they are equal increment the pointer\nnow check if the **left subtree == new voyage pointer val**\nif it is -> no flip required thus call left subtree first then rightsubtree\nif they are not equal -> flip maybe required then call right subtree\nif even after flipping value doesnt match thus it cant meet the voyage order return -1.\n\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 flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n ans = []\n p = 0\n flag = False\n def dfs(node):\n nonlocal ans, p, flag\n if not node:\n return ans\n if node.val != voyage[p]: #even after flip/ no flip value doesnt match thus order cant be followed\n flag = True\n return\n p += 1 # if value matched increment curr pointer\n if node.left and node.left.val != voyage[p]: # flip required\n ans.append(node.val)\n dfs(node.right)\n dfs(node.left)\n else: # flip not required\n dfs(node.left)\n dfs(node.right)\n dfs(root)\n if flag:\n return [-1]\n return ans\n\n \n```
0
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Use DFS
flip-binary-tree-to-match-preorder-traversal
0
1
```\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.flips = []\n self.index = 0\n\n def dfs(root):\n if root:\n if root.val != voyage[self.index]:\n self.flips = [-1]\n return\n\n self.index+=1\n if root.left and root.left.val != voyage[self.index]:\n self.flips.append(root.val)\n dfs(root.right)\n dfs(root.left)\n else:\n dfs(root.left)\n dfs(root.right)\n dfs(root)\n if len(self.flips) and self.flips[0] == -1:\n return [-1]\n return self.flips\n```
0
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Use DFS
flip-binary-tree-to-match-preorder-traversal
0
1
```\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.flips = []\n self.index = 0\n\n def dfs(root):\n if root:\n if root.val != voyage[self.index]:\n self.flips = [-1]\n return\n\n self.index+=1\n if root.left and root.left.val != voyage[self.index]:\n self.flips.append(root.val)\n dfs(root.right)\n dfs(root.left)\n else:\n dfs(root.left)\n dfs(root.right)\n dfs(root)\n if len(self.flips) and self.flips[0] == -1:\n return [-1]\n return self.flips\n```
0
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Python3 🐍 concise solution beats 99%
flip-binary-tree-to-match-preorder-traversal
0
1
\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 traverse(self,node,index,n):\n res = []\n if not node: \n index[0] -= 1\n return True,[]\n \n # when we reach the end of voyage but still node is present\n if node and index[0] == n : return False,[]\n \n #print(\'Here node = \',node.val, \'Index = \',index[0] , \'voyage val is\',self.voyage[index[0]])\n \n # if node.val is not same as voyage[index] in preorder traverse\n if node.val != self.voyage[index[0]] : return False,[]\n \n if not node.left and not node.right : return True , []\n \n # for traversing first check if node.left is voyage[index+1] or node.right or None\n old = index[0]\n \n # try left and right\n index[0] = index[0] + 1\n a,l1 = self.traverse(node.left,index,n)\n index[0] = index[0] + 1\n b,l2 = self.traverse(node.right,index,n)\n #print(\'node =\',node.val,\' left1 =\',a,\' and right1 =\',b)\n if a and b :\n res = []\n for i in l1: res.append(i)\n for i in l2: res.append(i)\n return True , res\n \n #try right and left\n index[0] = old\n index[0] = index[0] + 1\n a,l1 = self.traverse(node.right,index,n)\n index[0] = index[0] + 1\n b,l2 = self.traverse(node.left,index,n) \n #print(\'node =\',node.val,\' left2 =\',b,\' and right2 =\',a)\n if a and b :\n res = []\n res.append(node.val)\n for i in l1: res.append(i)\n for i in l2: res.append(i)\n return True , res\n \n return False,[]\n \n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.voyage = voyage\n ans , lst = self.traverse(root,[0],len(voyage))\n if ans == False : return [-1]\n return lst\n```
0
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Python3 🐍 concise solution beats 99%
flip-binary-tree-to-match-preorder-traversal
0
1
\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 traverse(self,node,index,n):\n res = []\n if not node: \n index[0] -= 1\n return True,[]\n \n # when we reach the end of voyage but still node is present\n if node and index[0] == n : return False,[]\n \n #print(\'Here node = \',node.val, \'Index = \',index[0] , \'voyage val is\',self.voyage[index[0]])\n \n # if node.val is not same as voyage[index] in preorder traverse\n if node.val != self.voyage[index[0]] : return False,[]\n \n if not node.left and not node.right : return True , []\n \n # for traversing first check if node.left is voyage[index+1] or node.right or None\n old = index[0]\n \n # try left and right\n index[0] = index[0] + 1\n a,l1 = self.traverse(node.left,index,n)\n index[0] = index[0] + 1\n b,l2 = self.traverse(node.right,index,n)\n #print(\'node =\',node.val,\' left1 =\',a,\' and right1 =\',b)\n if a and b :\n res = []\n for i in l1: res.append(i)\n for i in l2: res.append(i)\n return True , res\n \n #try right and left\n index[0] = old\n index[0] = index[0] + 1\n a,l1 = self.traverse(node.right,index,n)\n index[0] = index[0] + 1\n b,l2 = self.traverse(node.left,index,n) \n #print(\'node =\',node.val,\' left2 =\',b,\' and right2 =\',a)\n if a and b :\n res = []\n res.append(node.val)\n for i in l1: res.append(i)\n for i in l2: res.append(i)\n return True , res\n \n return False,[]\n \n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.voyage = voyage\n ans , lst = self.traverse(root,[0],len(voyage))\n if ans == False : return [-1]\n return lst\n```
0
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Solution
equal-rational-numbers
1
1
```C++ []\nclass Solution {\n public:\n bool isRationalEqual(string S, string T) {\n return abs(valueOf(S) - valueOf(T)) < 1e-9;\n }\n private:\n vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n double valueOf(const string& s) {\n if (s.find(\'(\') == string::npos)\n return stod(s);\n\n double integer_nonRepeating = stod(s.substr(0, s.find_first_of(\'(\')));\n int nonRepeatingLength = s.find_first_of(\'(\') - s.find_first_of(\'.\') - 1;\n int repeating =\n stoi(s.substr(s.find_first_of(\'(\') + 1, s.find_first_of(\')\')));\n int repeatingLength = s.find_first_of(\')\') - s.find_first_of(\'(\') - 1;\n\n return integer_nonRepeating +\n repeating * pow(0.1, nonRepeatingLength) * ratios[repeatingLength];\n }\n};\n```\n\n```Python3 []\nfrom fractions import Fraction\n\nclass Solution:\n def isRationalEqual(self, S, T):\n def f(s):\n i = s.find(\'(\')\n if i >= 0:\n s = s[:i] + s[i + 1:-1] * 20\n return float(s[:20])\n return f(S) == f(T)\n```\n\n```Java []\nclass Solution {\n public boolean isRationalEqual(String s, String t) {\n return Math.abs(valueOf(s) - valueOf(t)) < 1e-9;\n }\n private static double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n private double valueOf(final String s) {\n if (!s.contains("("))\n return Double.valueOf(s);\n\n final int leftParenIndex = s.indexOf(\'(\');\n final int rightParenIndex = s.indexOf(\')\');\n final int dotIndex = s.indexOf(\'.\');\n\n final double nonRepeating = Double.valueOf(s.substring(0, leftParenIndex));\n final int nonRepeatingLength = leftParenIndex - dotIndex - 1;\n\n final int repeating = Integer.parseInt(s.substring(leftParenIndex + 1, rightParenIndex));\n final int repeatingLength = rightParenIndex - leftParenIndex - 1;\n return nonRepeating + repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength];\n }\n}\n```\n
2
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Solution
equal-rational-numbers
1
1
```C++ []\nclass Solution {\n public:\n bool isRationalEqual(string S, string T) {\n return abs(valueOf(S) - valueOf(T)) < 1e-9;\n }\n private:\n vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n double valueOf(const string& s) {\n if (s.find(\'(\') == string::npos)\n return stod(s);\n\n double integer_nonRepeating = stod(s.substr(0, s.find_first_of(\'(\')));\n int nonRepeatingLength = s.find_first_of(\'(\') - s.find_first_of(\'.\') - 1;\n int repeating =\n stoi(s.substr(s.find_first_of(\'(\') + 1, s.find_first_of(\')\')));\n int repeatingLength = s.find_first_of(\')\') - s.find_first_of(\'(\') - 1;\n\n return integer_nonRepeating +\n repeating * pow(0.1, nonRepeatingLength) * ratios[repeatingLength];\n }\n};\n```\n\n```Python3 []\nfrom fractions import Fraction\n\nclass Solution:\n def isRationalEqual(self, S, T):\n def f(s):\n i = s.find(\'(\')\n if i >= 0:\n s = s[:i] + s[i + 1:-1] * 20\n return float(s[:20])\n return f(S) == f(T)\n```\n\n```Java []\nclass Solution {\n public boolean isRationalEqual(String s, String t) {\n return Math.abs(valueOf(s) - valueOf(t)) < 1e-9;\n }\n private static double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n private double valueOf(final String s) {\n if (!s.contains("("))\n return Double.valueOf(s);\n\n final int leftParenIndex = s.indexOf(\'(\');\n final int rightParenIndex = s.indexOf(\')\');\n final int dotIndex = s.indexOf(\'.\');\n\n final double nonRepeating = Double.valueOf(s.substring(0, leftParenIndex));\n final int nonRepeatingLength = leftParenIndex - dotIndex - 1;\n\n final int repeating = Integer.parseInt(s.substring(leftParenIndex + 1, rightParenIndex));\n final int repeatingLength = rightParenIndex - leftParenIndex - 1;\n return nonRepeating + repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength];\n }\n}\n```\n
2
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
[Python3] Solution with explanation
equal-rational-numbers
0
1
The main idea is to represent strings as **float** numbers, and then **rounding** down and comparing with each other.\nFirst we **separate** the periodic part of the fraction, then **remove** the brackets from the string. Finally, we add the periodic part to the end of the string several times (8) in order to avoid errors when **rounding down** up to 8 decimal places, taking into account the conditions of the problem.\n\nFor example:\n"8.123(4567)" -> 8.123456745674567456745674567456745674567 -> 8.12345675\n"8.123(4566)" -> 8.123456645664566456645664566456645664566 -> 8.12345665\n\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n def convert(string):\n if \'(\' in string:\n rep_part = string[string.index(\'(\') + 1:string.index(\')\')]\n string = string.replace(\'(\', \'\').replace(\')\', \'\')\n string += rep_part * 8\n\n return string\n \n def round_down(num, decimals):\n return math.floor(float(num) * 10 ** decimals + 0.5) / 10 ** decimals\n \n return round_down(convert(s), 8) == round_down(convert(t), 8)\n```\nConvert function could be written with slicing in more short/elegant way, like in [lee215](https://leetcode.com/problems/equal-rational-numbers/discuss/214203/JavaC%2B%2BPython-Easy-Cheat)\'s solution
2
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
[Python3] Solution with explanation
equal-rational-numbers
0
1
The main idea is to represent strings as **float** numbers, and then **rounding** down and comparing with each other.\nFirst we **separate** the periodic part of the fraction, then **remove** the brackets from the string. Finally, we add the periodic part to the end of the string several times (8) in order to avoid errors when **rounding down** up to 8 decimal places, taking into account the conditions of the problem.\n\nFor example:\n"8.123(4567)" -> 8.123456745674567456745674567456745674567 -> 8.12345675\n"8.123(4566)" -> 8.123456645664566456645664566456645664566 -> 8.12345665\n\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n def convert(string):\n if \'(\' in string:\n rep_part = string[string.index(\'(\') + 1:string.index(\')\')]\n string = string.replace(\'(\', \'\').replace(\')\', \'\')\n string += rep_part * 8\n\n return string\n \n def round_down(num, decimals):\n return math.floor(float(num) * 10 ** decimals + 0.5) / 10 ** decimals\n \n return round_down(convert(s), 8) == round_down(convert(t), 8)\n```\nConvert function could be written with slicing in more short/elegant way, like in [lee215](https://leetcode.com/problems/equal-rational-numbers/discuss/214203/JavaC%2B%2BPython-Easy-Cheat)\'s solution
2
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Mainly to do with string parsing and special cases
equal-rational-numbers
0
1
# Intuition\nSeems like we just need to parse the strings and handle the special cases -- particularly the one mentioned in the description about .(9) converging to 1.\n\n# Approach\nDivide and conquer, and do it all with string manipulation. First parse out the constituent integer, non-repeating decimal, and repeating decimal parts. Then check if there are trailing zeroes that need to be chopped off. Then check if there are trailing repeating 9\'s that converge. Then pad out the shorter non-repeating part until it\'s the length of the longer non-repeating + repeating, and check if equal. Then check if the repeating parts are cycles of each other.\n\n# Complexity\n- Time complexity: $$O(n)$$ where $$n$$ is the length of the input strings\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ where $$n$$ is the length of the input strings\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def printParts(self, prefix, parts):\n print("{}: {} . {} ({})".format(prefix, parts[0], parts[1], parts[2]))\n\n def getPartsAsStrings(self, s) -> (str, str, str):\n integer_part_s = s.split(\'.\')[0]\n decimal_part_s = \'\'\n repeating_part_s = \'\'\n if len(s.split(\'.\')) > 1:\n decimal_part_s = s.split(\'.\')[1]\n if len(decimal_part_s.split(\'(\')) > 1:\n repeating_part_s = decimal_part_s.split(\'(\')[1][:-1]\n decimal_part_s = decimal_part_s.split(\'(\')[0]\n return (integer_part_s, decimal_part_s, repeating_part_s)\n\n def chopZeroes(self, parts) -> (str, str, str):\n parts = list(parts)\n if parts[2] != \'0\' and parts[2] != \'\':\n return tuple(parts)\n parts[2] = \'\'\n parts[1] = parts[1].rstrip(\'0\')\n return tuple(parts)\n\n def convergeNines(self, parts) -> (str, str, str):\n parts_list = list(parts)\n if len(parts[2]) == 0:\n return parts\n for c in parts[2]:\n if c != \'9\':\n return parts\n parts_list[2] = \'\'\n if len(parts_list[1]) > 0:\n while len(parts_list[1]) > 0 and parts_list[1][-1] == \'9\':\n parts_list[1] = parts_list[1][:-1]\n #self.printParts(\'during convergeNines\', parts_list)\n if len(parts_list[1]) > 0:\n parts_list[1] = parts_list[1][:-1] + str(int(parts_list[1][-1]) + 1)\n else:\n parts_list[0] = str(int(parts_list[0]) + 1)\n return tuple(parts_list)\n\n def padDecimalToLen(self, decimal_part: str, repeating_part: str, to_len: int) -> str:\n while len(decimal_part) < to_len:\n len_to_take = min(len(repeating_part), to_len - len(decimal_part))\n decimal_part += repeating_part[:len_to_take]\n return decimal_part\n\n def decimalPartsAreEquivalent(self, parts_s, parts_t) -> bool:\n parts_s = list(parts_s)\n parts_t = list(parts_t)\n if len(parts_s[1]) > len(parts_t[1]) and len(parts_t[2]) > 0:\n parts_t[1] = self.padDecimalToLen(parts_t[1], parts_t[2], len(parts_s[1]) + len(parts_s[2]))\n parts_s[1] += parts_s[2]\n elif len(parts_t[1]) > len(parts_s[1]) and len(parts_s[2]) > 0:\n parts_s[1] = self.padDecimalToLen(parts_s[1], parts_s[2], len(parts_t[1]) + len(parts_t[2]))\n parts_t[1] += parts_t[2]\n return parts_s[1] == parts_t[1]\n\n def areEquivalentCycles(self, s: str, t: str) -> bool:\n if s == \'\' or t == \'\':\n return s == t\n modified_s = s\n while len(modified_s) < (len(t) * 2):\n len_to_take = min(len(modified_s), (len(t) * 2) - len(modified_s))\n modified_s = modified_s + modified_s[:len_to_take]\n if t not in modified_s:\n return False\n modified_t = t\n while len(modified_t) < (len(s) * 2):\n len_to_take = min(len(modified_t), (len(s) * 2) - len(modified_t))\n modified_t = modified_t + modified_t[:len_to_take]\n if s not in modified_t:\n return False\n return True\n\n def isRationalEqual(self, s: str, t: str) -> bool:\n parts_s = self.getPartsAsStrings(s)\n parts_t = self.getPartsAsStrings(t)\n\n # special case -- repeating part is 0, chop it off and any trailing zeroes on the decimal\n # part\n parts_s = self.chopZeroes(parts_s)\n parts_t = self.chopZeroes(parts_t)\n\n #print("after chopZeroes") ; self.printParts(\'s\', parts_s) ; self.printParts(\'t\', parts_t)\n\n # special case -- repeating 9, converges to the next higher integer\n parts_s = self.convergeNines(parts_s)\n parts_t = self.convergeNines(parts_t)\n\n #print("after convergeNines") ; self.printParts(\'s\', parts_s) ; self.printParts(\'t\', parts_t)\n\n return parts_s[0] == parts_t[0] and self.decimalPartsAreEquivalent(parts_s, parts_t) and self.areEquivalentCycles(parts_s[2], parts_t[2])\n\n```
0
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Mainly to do with string parsing and special cases
equal-rational-numbers
0
1
# Intuition\nSeems like we just need to parse the strings and handle the special cases -- particularly the one mentioned in the description about .(9) converging to 1.\n\n# Approach\nDivide and conquer, and do it all with string manipulation. First parse out the constituent integer, non-repeating decimal, and repeating decimal parts. Then check if there are trailing zeroes that need to be chopped off. Then check if there are trailing repeating 9\'s that converge. Then pad out the shorter non-repeating part until it\'s the length of the longer non-repeating + repeating, and check if equal. Then check if the repeating parts are cycles of each other.\n\n# Complexity\n- Time complexity: $$O(n)$$ where $$n$$ is the length of the input strings\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ where $$n$$ is the length of the input strings\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def printParts(self, prefix, parts):\n print("{}: {} . {} ({})".format(prefix, parts[0], parts[1], parts[2]))\n\n def getPartsAsStrings(self, s) -> (str, str, str):\n integer_part_s = s.split(\'.\')[0]\n decimal_part_s = \'\'\n repeating_part_s = \'\'\n if len(s.split(\'.\')) > 1:\n decimal_part_s = s.split(\'.\')[1]\n if len(decimal_part_s.split(\'(\')) > 1:\n repeating_part_s = decimal_part_s.split(\'(\')[1][:-1]\n decimal_part_s = decimal_part_s.split(\'(\')[0]\n return (integer_part_s, decimal_part_s, repeating_part_s)\n\n def chopZeroes(self, parts) -> (str, str, str):\n parts = list(parts)\n if parts[2] != \'0\' and parts[2] != \'\':\n return tuple(parts)\n parts[2] = \'\'\n parts[1] = parts[1].rstrip(\'0\')\n return tuple(parts)\n\n def convergeNines(self, parts) -> (str, str, str):\n parts_list = list(parts)\n if len(parts[2]) == 0:\n return parts\n for c in parts[2]:\n if c != \'9\':\n return parts\n parts_list[2] = \'\'\n if len(parts_list[1]) > 0:\n while len(parts_list[1]) > 0 and parts_list[1][-1] == \'9\':\n parts_list[1] = parts_list[1][:-1]\n #self.printParts(\'during convergeNines\', parts_list)\n if len(parts_list[1]) > 0:\n parts_list[1] = parts_list[1][:-1] + str(int(parts_list[1][-1]) + 1)\n else:\n parts_list[0] = str(int(parts_list[0]) + 1)\n return tuple(parts_list)\n\n def padDecimalToLen(self, decimal_part: str, repeating_part: str, to_len: int) -> str:\n while len(decimal_part) < to_len:\n len_to_take = min(len(repeating_part), to_len - len(decimal_part))\n decimal_part += repeating_part[:len_to_take]\n return decimal_part\n\n def decimalPartsAreEquivalent(self, parts_s, parts_t) -> bool:\n parts_s = list(parts_s)\n parts_t = list(parts_t)\n if len(parts_s[1]) > len(parts_t[1]) and len(parts_t[2]) > 0:\n parts_t[1] = self.padDecimalToLen(parts_t[1], parts_t[2], len(parts_s[1]) + len(parts_s[2]))\n parts_s[1] += parts_s[2]\n elif len(parts_t[1]) > len(parts_s[1]) and len(parts_s[2]) > 0:\n parts_s[1] = self.padDecimalToLen(parts_s[1], parts_s[2], len(parts_t[1]) + len(parts_t[2]))\n parts_t[1] += parts_t[2]\n return parts_s[1] == parts_t[1]\n\n def areEquivalentCycles(self, s: str, t: str) -> bool:\n if s == \'\' or t == \'\':\n return s == t\n modified_s = s\n while len(modified_s) < (len(t) * 2):\n len_to_take = min(len(modified_s), (len(t) * 2) - len(modified_s))\n modified_s = modified_s + modified_s[:len_to_take]\n if t not in modified_s:\n return False\n modified_t = t\n while len(modified_t) < (len(s) * 2):\n len_to_take = min(len(modified_t), (len(s) * 2) - len(modified_t))\n modified_t = modified_t + modified_t[:len_to_take]\n if s not in modified_t:\n return False\n return True\n\n def isRationalEqual(self, s: str, t: str) -> bool:\n parts_s = self.getPartsAsStrings(s)\n parts_t = self.getPartsAsStrings(t)\n\n # special case -- repeating part is 0, chop it off and any trailing zeroes on the decimal\n # part\n parts_s = self.chopZeroes(parts_s)\n parts_t = self.chopZeroes(parts_t)\n\n #print("after chopZeroes") ; self.printParts(\'s\', parts_s) ; self.printParts(\'t\', parts_t)\n\n # special case -- repeating 9, converges to the next higher integer\n parts_s = self.convergeNines(parts_s)\n parts_t = self.convergeNines(parts_t)\n\n #print("after convergeNines") ; self.printParts(\'s\', parts_s) ; self.printParts(\'t\', parts_t)\n\n return parts_s[0] == parts_t[0] and self.decimalPartsAreEquivalent(parts_s, parts_t) and self.areEquivalentCycles(parts_s[2], parts_t[2])\n\n```
0
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Python3 🐍 concise solution beats 99%
equal-rational-numbers
0
1
# Code\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n \n def fn(s):\n """Return normalized string."""\n if "." not in s: return s # edge case - xxx \n xxx, frac = s.split(\'.\')\n if not frac: return xxx # edge case - xxx.\n if \'(\' in frac: \n nonrep, rep = frac.split(\'(\')\n rep = rep.rstrip(\')\')\n while nonrep and rep and nonrep[-1] == rep[-1]: # normalize repeating part \n nonrep = nonrep[:-1]\n rep = rep[-1] + rep[:-1]\n \n if len(rep) > 1 and len(set(rep)) == 1: rep = rep[0] # edge case (11)\n if rep[:2] == rep[2:]: rep = rep[:2] # edge case (1212)\n \n if rep == "0": rep = "" # edge case - (0)\n if rep == "9": # edge case - (9)\n rep = ""\n if nonrep: nonrep = nonrep[:-1] + str(int(nonrep[-1]) + 1)\n else: xxx = str(int(xxx) + 1)\n frac = ""\n if rep: frac = f"({rep})"\n if nonrep: frac = nonrep + frac\n if \'(\' not in frac: # remove trailing 0\'s\n while frac and frac[-1] == \'0\': frac = frac[:-1]\n return xxx + "." + frac if frac else xxx\n \n return fn(s) == fn(t)\n```
0
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Python3 🐍 concise solution beats 99%
equal-rational-numbers
0
1
# Code\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n \n def fn(s):\n """Return normalized string."""\n if "." not in s: return s # edge case - xxx \n xxx, frac = s.split(\'.\')\n if not frac: return xxx # edge case - xxx.\n if \'(\' in frac: \n nonrep, rep = frac.split(\'(\')\n rep = rep.rstrip(\')\')\n while nonrep and rep and nonrep[-1] == rep[-1]: # normalize repeating part \n nonrep = nonrep[:-1]\n rep = rep[-1] + rep[:-1]\n \n if len(rep) > 1 and len(set(rep)) == 1: rep = rep[0] # edge case (11)\n if rep[:2] == rep[2:]: rep = rep[:2] # edge case (1212)\n \n if rep == "0": rep = "" # edge case - (0)\n if rep == "9": # edge case - (9)\n rep = ""\n if nonrep: nonrep = nonrep[:-1] + str(int(nonrep[-1]) + 1)\n else: xxx = str(int(xxx) + 1)\n frac = ""\n if rep: frac = f"({rep})"\n if nonrep: frac = nonrep + frac\n if \'(\' not in frac: # remove trailing 0\'s\n while frac and frac[-1] == \'0\': frac = frac[:-1]\n return xxx + "." + frac if frac else xxx\n \n return fn(s) == fn(t)\n```
0
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Fraction Expansion using Stack python
equal-rational-numbers
0
1
I just expanded the fraction then truncated it and compared the float value of each. \n\n```py\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n repeat = 1000\n \n res = []\n \n for word in (s, t):\n stack = []\n for char in word:\n if char == ")":\n nums = ""\n char = ""\n \n while char != "(" and stack:\n nums += char\n char = stack.pop(-1)\n \n stack.append( nums[::-1] * repeat )\n else:\n stack.append(char)\n \n res.append(("".join(stack))[:100])\n \n return float(res[0]) == float(res[1])\n \n\n ```
0
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Fraction Expansion using Stack python
equal-rational-numbers
0
1
I just expanded the fraction then truncated it and compared the float value of each. \n\n```py\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n repeat = 1000\n \n res = []\n \n for word in (s, t):\n stack = []\n for char in word:\n if char == ")":\n nums = ""\n char = ""\n \n while char != "(" and stack:\n nums += char\n char = stack.pop(-1)\n \n stack.append( nums[::-1] * repeat )\n else:\n stack.append(char)\n \n res.append(("".join(stack))[:100])\n \n return float(res[0]) == float(res[1])\n \n\n ```
0
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Python 3 (beats ~99%) (six lines)
equal-rational-numbers
0
1
```\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n L, A = [len(S), len(T)], [S,T]\n for i,p in enumerate([S,T]):\n if \'(\' in p:\n I = p.index(\'(\')\n A[i] = p[0:I] + 7*p[I+1:L[i]-1]\n return abs(float(A[0])-float(A[1])) < 1E-7\n\t\t\n\t\t\n- Junaid Mansuri
1
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Python 3 (beats ~99%) (six lines)
equal-rational-numbers
0
1
```\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n L, A = [len(S), len(T)], [S,T]\n for i,p in enumerate([S,T]):\n if \'(\' in p:\n I = p.index(\'(\')\n A[i] = p[0:I] + 7*p[I+1:L[i]-1]\n return abs(float(A[0])-float(A[1])) < 1E-7\n\t\t\n\t\t\n- Junaid Mansuri
1
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Python solution with extra class
equal-rational-numbers
0
1
```\nclass frac:\n def __init__(self, num, denom):\n self.num = num\n self.denom = denom\n\n def __add__(self, other):\n a = self.num * other.denom + other.num * self.denom\n b = self.denom * other.denom\n gcd = self.hcf(a, b)\n\n self.num = a // gcd\n self.denom = b // gcd\n return self\n\n def __eq__(self, other):\n return (self.num == other.num) and (self.denom == other.denom)\n\n def hcf(self, x, y):\n while y:\n x, y = y, x % y\n return x\n\n\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n def geo_sum(num: str) -> frac:\n if "(" in num:\n parts = num.split(".")\n\n rp = parts[-1].replace(")", "")\n rp = rp.split("(")\n\n parts.pop()\n parts.extend(rp)\n\n n = len(parts[1])\n m = len(parts[2])\n\n if parts[1] == "":\n parts[1] = "0"\n\n p = (\n frac(int(parts[0]), 1)\n + frac(int(parts[1]), 10**n)\n + frac(int(parts[2]), 10 ** (n + m) - 10**n)\n )\n return p\n\n elif "." in num:\n parts = num.split(".")\n n = len(parts[1])\n if parts[1] == "":\n parts[1] = "0"\n return frac(int(parts[0]), 1) + frac(int(parts[1]), 10**n)\n else:\n return frac(int(num), 1)\n\n return geo_sum(s) == geo_sum(t)\n```
0
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways: * * For example, `12`, `0`, and `123`. * `**<.>**` * For example, `0.5`, `1.`, `2.12`, and `123.0001`. * `**<.>****<(>****<)>**` * For example, `0.1(6)`, `1.(9)`, `123.00(1212)`. The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: * `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`. **Example 1:** **Input:** s = "0.(52) ", t = "0.5(25) " **Output:** true **Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number. **Example 2:** **Input:** s = "0.1666(6) ", t = "0.166(66) " **Output:** true **Example 3:** **Input:** s = "0.9(9) ", t = "1. " **Output:** true **Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\] "1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ". **Constraints:** * Each part consists only of digits. * The does not have leading zeros (except for the zero itself). * `1 <= .length <= 4` * `0 <= .length <= 4` * `1 <= .length <= 4`
null
Python solution with extra class
equal-rational-numbers
0
1
```\nclass frac:\n def __init__(self, num, denom):\n self.num = num\n self.denom = denom\n\n def __add__(self, other):\n a = self.num * other.denom + other.num * self.denom\n b = self.denom * other.denom\n gcd = self.hcf(a, b)\n\n self.num = a // gcd\n self.denom = b // gcd\n return self\n\n def __eq__(self, other):\n return (self.num == other.num) and (self.denom == other.denom)\n\n def hcf(self, x, y):\n while y:\n x, y = y, x % y\n return x\n\n\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n def geo_sum(num: str) -> frac:\n if "(" in num:\n parts = num.split(".")\n\n rp = parts[-1].replace(")", "")\n rp = rp.split("(")\n\n parts.pop()\n parts.extend(rp)\n\n n = len(parts[1])\n m = len(parts[2])\n\n if parts[1] == "":\n parts[1] = "0"\n\n p = (\n frac(int(parts[0]), 1)\n + frac(int(parts[1]), 10**n)\n + frac(int(parts[2]), 10 ** (n + m) - 10**n)\n )\n return p\n\n elif "." in num:\n parts = num.split(".")\n n = len(parts[1])\n if parts[1] == "":\n parts[1] = "0"\n return frac(int(parts[0]), 1) + frac(int(parts[1]), 10**n)\n else:\n return frac(int(num), 1)\n\n return geo_sum(s) == geo_sum(t)\n```
0
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Easy to read Python min heap solution ( beat 99% python solutions )
k-closest-points-to-origin
0
1
We keep a min heap of size K.\nFor each item, we insert an item to our heap.\nIf inserting an item makes heap size larger than k, then we immediately pop an item after inserting ( `heappushpop` ).\n\nRuntime: \nInserting an item to a heap of size k take `O(logK)` time.\nAnd we do this for each item points.\nSo runtime is `O(N * logK)` where N is the length of `points`.\n\nSpace: O(K) for our heap.\n```\nimport heapq\n\nclass Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n \n heap = []\n \n for (x, y) in points:\n dist = -(x*x + y*y)\n if len(heap) == K:\n heapq.heappushpop(heap, (dist, x, y))\n else:\n heapq.heappush(heap, (dist, x, y))\n \n return [(x,y) for (dist,x, y) in heap]\n```\n\nI found it interesting that my solution ran much faster than "Divide And Conquer" solution under "Solution" tab which is supposed to run in O(N). \nMine ran at 316ms while D&C solution ran at 536 ms.\n\nI am guessing that the D&C solution ran much slower than mine because it used recursions which would involved creating callstacks.
332
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). **Example 1:** **Input:** points = \[\[1,3\],\[-2,2\]\], k = 1 **Output:** \[\[-2,2\]\] **Explanation:** The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\]. **Example 2:** **Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2 **Output:** \[\[3,3\],\[-2,4\]\] **Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted. **Constraints:** * `1 <= k <= points.length <= 104` * `-104 < xi, yi < 104`
null
Easy to read Python min heap solution ( beat 99% python solutions )
k-closest-points-to-origin
0
1
We keep a min heap of size K.\nFor each item, we insert an item to our heap.\nIf inserting an item makes heap size larger than k, then we immediately pop an item after inserting ( `heappushpop` ).\n\nRuntime: \nInserting an item to a heap of size k take `O(logK)` time.\nAnd we do this for each item points.\nSo runtime is `O(N * logK)` where N is the length of `points`.\n\nSpace: O(K) for our heap.\n```\nimport heapq\n\nclass Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n \n heap = []\n \n for (x, y) in points:\n dist = -(x*x + y*y)\n if len(heap) == K:\n heapq.heappushpop(heap, (dist, x, y))\n else:\n heapq.heappush(heap, (dist, x, y))\n \n return [(x,y) for (dist,x, y) in heap]\n```\n\nI found it interesting that my solution ran much faster than "Divide And Conquer" solution under "Solution" tab which is supposed to run in O(N). \nMine ran at 316ms while D&C solution ran at 536 ms.\n\nI am guessing that the D&C solution ran much slower than mine because it used recursions which would involved creating callstacks.
332
You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them. Return _the maximum score of a pair of sightseeing spots_. **Example 1:** **Input:** values = \[8,1,5,2,6\] **Output:** 11 **Explanation:** i = 0, j = 2, values\[i\] + values\[j\] + i - j = 8 + 5 + 0 - 2 = 11 **Example 2:** **Input:** values = \[1,2\] **Output:** 2 **Constraints:** * `2 <= values.length <= 5 * 104` * `1 <= values[i] <= 1000`
null
Easy to Understand Well Commented Python Code
k-closest-points-to-origin
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We are calculating the distance of every point from orgin using the\ndistance formula.\n2. Sorting the values on the basis of their distance from Orign in ascending order using lambda function.\n3. Finally getting the k closest point from the orign \n\n\n\n# Code\n```\nclass Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n my_dict = []\n # Calulating Distance using Distance Fromula\n for i in points:\n y = (i[0]**2+i[1]**2)**0.5\n y = [i,y]\n my_dict.append(y)\n # Sorting the values on the basis of their distance from Orign in ascending order\n my_dict.sort(key = lambda x:x[1])\n x = my_dict[0][1]\n j = 0\n z = []\n # Getting K closest point from Orign\n while j<k:\n z.append(my_dict[j][0])\n j+=1\n return z\n\n\n \n \n```
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). **Example 1:** **Input:** points = \[\[1,3\],\[-2,2\]\], k = 1 **Output:** \[\[-2,2\]\] **Explanation:** The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\]. **Example 2:** **Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2 **Output:** \[\[3,3\],\[-2,4\]\] **Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted. **Constraints:** * `1 <= k <= points.length <= 104` * `-104 < xi, yi < 104`
null
Easy to Understand Well Commented Python Code
k-closest-points-to-origin
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We are calculating the distance of every point from orgin using the\ndistance formula.\n2. Sorting the values on the basis of their distance from Orign in ascending order using lambda function.\n3. Finally getting the k closest point from the orign \n\n\n\n# Code\n```\nclass Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n my_dict = []\n # Calulating Distance using Distance Fromula\n for i in points:\n y = (i[0]**2+i[1]**2)**0.5\n y = [i,y]\n my_dict.append(y)\n # Sorting the values on the basis of their distance from Orign in ascending order\n my_dict.sort(key = lambda x:x[1])\n x = my_dict[0][1]\n j = 0\n z = []\n # Getting K closest point from Orign\n while j<k:\n z.append(my_dict[j][0])\n j+=1\n return z\n\n\n \n \n```
1
You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them. The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them. Return _the maximum score of a pair of sightseeing spots_. **Example 1:** **Input:** values = \[8,1,5,2,6\] **Output:** 11 **Explanation:** i = 0, j = 2, values\[i\] + values\[j\] + i - j = 8 + 5 + 0 - 2 = 11 **Example 2:** **Input:** values = \[1,2\] **Output:** 2 **Constraints:** * `2 <= values.length <= 5 * 104` * `1 <= values[i] <= 1000`
null
[Python] O(N) 1 Liner solution, Prefix sum
subarray-sums-divisible-by-k
0
1
# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import Counter\nfrom itertools import accumulate\n\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n return sum(r * (r-1) // 2 for _, r in Counter(map(lambda x: x % k, accumulate([0] + nums))).items())\n\n```\n\n\\\n\\\nmore comprehensible version:\n```\nfrom collections import Counter\nfrom itertools import accumulate\n\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n remainders = Counter(map(lambda x: x % k, accumulate(nums))) \n ans = 0\n for r in remainders:\n # combinations of prefixes have same remainer mod k\n ans += remainders[r] * (remainders[r]-1) // 2\n ans += remainders[0]\n return ans\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python | Prefix Mod Sum | O(n)
subarray-sums-divisible-by-k
0
1
# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n cur = 0\n counter = Counter()\n for num in nums:\n cur = (cur + num) % k\n counter[cur] += 1\n res = 0\n for e in counter:\n res += counter[e]*(counter[e]-1)//2\n return res + counter[0] \n \n \n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python Simple Solution using Dictionary
subarray-sums-divisible-by-k
0
1
```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n cur, count, d = 0, 0, defaultdict(int, {0:1})\n for i in nums:\n cur += i \n rem = cur % k\n count += d[rem]\n d[rem]+=1\n return count\n \n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Faster than 99%
subarray-sums-divisible-by-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt suffices to compute all partial sums starting at 0 and see how many have the same remainder modulo k.\nIf l partial sums have the same remainder modulo k, this corresponds to l(l-1)/2 subarrays whose sum is divisible by k.\n\n# Approach\nSome improvements can make this faster, such as computing all partial sums modulo k and thus avoiding large numbers. This and other small changes decreased the running time from 296 to 274 ms on my third attempt and also lowered the memory needed.\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n dct=defaultdict(int)\n dct[0]=1\n s=0\n for n in nums:\n s=(s+n)%k\n dct[s]+=1\n return sum(v*v-v for v in dct.values())>>1\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python faster than 99.8%, linear, combinations without repetition
subarray-sums-divisible-by-k
0
1
# Intuition\nIt is based on a prefix sums solutions. The intuition bases on the fact two arrays which are divisible by $$k$$ can only differ by elements that sum up to a number also divisible by $$k$$.\n\n##### Example\nGiven an array $$[4,5,0,-2,-3,1]$$ and $$k=5$$ we know that the whole array is divisible by $$k$$. We can work our way back from here to remove subarrays that tally to a number divisible by $$k$$ too.\n\nIf we take out first and last element we get a subarray divisble by $$k$$ -\n$$[5,0,-2,-3]$$, because $$4+1\\ mod\\ 5=0$$.\n\nNext subbarray will be the one without element $$5$$, following that we can take out $$0$$ and so on.\n\nThis leads to another interesting observation. Assuming we have an array which elements sum to a value $$i=sum(array)\\ mod\\ k$$ it is enough to remove elements that sum to $$mod\\ k$$ in order to have a subarray divisible by $$k$$.\n\n#### Example\nGiven an array $$[4,5,0,-2,-3]$$ and $$k=5$$ we know that $$sum(array)\\ mod\\ k=4$$. If we remove any number of elements summing to $$mod\\ k\\ =4$$ the new subarray is divisible by $$k$$.\n\n# Approach\n1. Group array by $$mod\\ k$$ values.\n2. Calculate combinations without repetition for each group. This is important to note that we are looking for 2 elements combinations so the formula $$({n\\over2})=n!\\div(n-k)!*k!$$ simplifies to $$n*(n-1)\\div2$$.\n3. Since elements divisible by $$k$$ can form a subbaray of 1 element we have to add $$mod[0]$$\n\n# Complexity\n- Time complexity:\n$$O(n+k)$$\n$$O(n)$$ for a single pass to fill out counter array\n$$O(k)$$ for a pass to calculate combinations and another pass over $$mod$$ to tally it.\n\n- Space complexity:\n$$O(k)$$ for a counter array $$mod$$\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n mod = [0] * k\n mod[0] = 1\n running_mod = 0\n for num in nums:\n running_mod = (num + running_mod) % k\n mod[running_mod] += 1\n\n return sum([n*(n-1)//2 for n in mod])\n\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python (Prefix sums + Hashmap) 0(N)
subarray-sums-divisible-by-k
0
1
# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n ans=0\n d=defaultdict(lambda:0)\n nums=list(accumulate(nums))\n for i in range(len(nums)):\n nums[i]=((k+nums[i]%k) if nums[i]<0 else (nums[i]%k))%k\n d[0]+=1\n for i in nums:ans+=d[i];d[i]+=1\n return ans\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Easy python solution
subarray-sums-divisible-by-k
0
1
\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n count = 0\n s = 0\n sum_map = {}\n for i in nums:\n s+=i \n s= s%k\n if s in sum_map:\n sum_map[s]+=1\n else:\n sum_map[s] = 1\n\n for i in sum_map:\n su = sum_map[i]\n if i==0:\n count = count + (su*(su -1))//2 + su\n else:\n count += (su*(su -1))//2\n return count\n\n\n\n \n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python3 One Pass Solution
subarray-sums-divisible-by-k
0
1
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n pref_sums = [0] * k\n count = 0\n zero_pos = 0\n for num in nums:\n zero_pos = (zero_pos - num) % k\n pref_sums[(num + zero_pos) % k] += 1\n count += pref_sums[zero_pos]\n\n return count\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python Easy solution || Beats 90% || Time complex O(n)
subarray-sums-divisible-by-k
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(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n modGroup, curSum = [0]*k, 0\n for num in nums:\n curSum += num\n modGroup[curSum % k] += 1\n result = modGroup[0]\n for mod in modGroup:\n result += (mod*(mod-1))//2\n return result\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Brute Force to Optimised intuition .
subarray-sums-divisible-by-k
0
1
# Intuition\n**Bruteforce to Optimization** \n\n- The na\xEFve bruteforce solution would be - for all possible subarray start and end indexes, calculate the sum. So, the algorithm becomes O(n3).\n- We can optimize this using the prefix sum idea. SubarraySum(i,j)=PrefixSum(j)\u2212PrefixSum(i\u22121) This reduces the time complexity to O(n2)\n\nNow, for this problem,\n- PrefixSum(j)\u2212PrefixSum(i\u22121)=0 [modulo k]\n=>PrefixSum(j)=PrefixSum(i\u22121) [modulo k]\n\nSo, we can get rid of the loop and count the frequency of the current prefix sum to solve the problem. The final time complexity would be O(n).\nThe only corner case would be negative modulos.\n\n\n# Approach\n- For each index i, count all previous prefix sums in the array which has modulo same as of current prefix sum (at idx i) and add it to result.\n- Use HashTable to store the counts of prefix sum modulo.\n- Also, for a -ve number num, num%k<0, we have to change it to +ve mod because modulo of a number can lie in the range of 0 to k-1 only.\n- Let, num = -2, k=3 then res=(-2)%3=-2, for changing it to +ve mod add k to res.\n- Changing to +ve mod, -2+3 = 1, So, res=(-2)%3=1.\n\n - Note how prefixMod calculation is simplified, as remainders modulo k > 0 are always positive in Python.\n - Calculating prefix sums is a standard procedure implemented by itertools.accumulate, so one may as well write this:\n\n# Complexity\nComplexity: O(n) time and O(k) space\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: list[int], k: int) -> int:\n result = 0\n\n modGroups = [0] * k\n modGroups[0] = 1\n\n for prefixSum in itertools.accumulate(nums):\n result += modGroups[prefixSum % k]\n modGroups[prefixSum % k] += 1\n\n return result\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
prefixSum || Easiest ||
subarray-sums-divisible-by-k
0
1
\n\n# Code\n```\nimport math\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n freq_ar=[0]*k\n freq_ar[0]=1\n sum=0\n count=0\n for no in range(len(nums)):\n sum+=nums[no]\n remainder=sum%k\n if remainder<0:\n remainder+=k\n count+=freq_ar[remainder]\n freq_ar[remainder]+=1\n return count\n\n \n \n \n\n\n\n\n\n\'\'\'\nTo solve this, we will follow these steps \u2212\n\nmake one map m and set m[0] as 1\ntemp := 0, ans := 0, and n := size of array a\nfor i in range 0 to n \u2013 1\ntemp := temp + a[i]\nx := (temp mod k + k) mod k\nans := ans + m[x]\nincrease m[x] by 1\nreturn ans\n\'\'\'\n\n\n \n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
My Python Solution
subarray-sums-divisible-by-k
0
1
\n\n# What is prefix sum?\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- What is prefix sum?\n\nprefix sum also called cumulative sum, is an array with the same size as the original array, where the ith element represents the sum of the elements in the origianl array up to the ith position.\ne.g., arr = [1,2,3,4,5], prefixSum = [1,3,6,10,15]\nprefix sum will allow us to get the sum of a contiguous subarray in O(1), e.g., get the sum of elements from i=1 to i=3, we do prefixSum[3] - prefix[0].\nNote that the solution in this post doesn\'t explicitly using a prefix sum array, but it is better to think about the process of getting the remainder in the prefix sum way.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Frequency\nWhat is frequency table?\n\nA frequency table lists a set of values and how often each one appears.\nFrequency table will allow us to get the number of the occurances of some value while scanning an array in O(1), frequency can be stored using a list or a hashmap.\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int: # frequency table to store the frequency of the remainder\n remainderFrq = defaultdict(int)\n remainderFrq[0] = 1\n \n res = prefixSum = 0\n for n in nums:\n prefixSum += n\n remainder = prefixSum % k\n res += remainderFrq[remainder]\n remainderFrq[remainder] += 1\n return res\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Python Easy Solution
subarray-sums-divisible-by-k
0
1
\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n # frequency table to store the frequency of the remainder\n remainderFrq = defaultdict(int)\n # Empty sub array will have a sum of 0 and remainder of 0, thus the frequency of 0 is 1 before we go into the array\n remainderFrq[0] = 1\n \n res = prefixSum = 0\n for n in nums:\n # Adding n to the prefixSum, so we have the prefixSum up to the ith position.\n prefixSum += n\n # Get the remainder of the current prefixSum.\n remainder = prefixSum % k\n # We need to increase the result before update the frequency table.\n # Because we are counting how many previous prefixSum have the same remainder.\n res += remainderFrq[remainder]\n # Update the frequency table.\n remainderFrq[remainder] += 1\n return res\n```
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Solution
odd-even-jump
1
1
```C++ []\nconst int FAIL_LO=-1, FAIL_HI=1e5+1;\nint dp[2][20001];\nclass Solution {\npublic:\n int oddEvenJumps(vector<int>& arr) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n=arr.size(), ans=1;\n map<int, int> sts;\n map<int, int>::iterator it;\n sts[arr[n-1]]=n-1;\n dp[0][n-1]=dp[1][n-1]=true;\n sts[FAIL_LO]=sts[FAIL_HI]=n;\n dp[0][n]=dp[1][n]=false; \n for(int i=n-2; i>=0; --i) {\n it=sts.lower_bound(arr[i]);\n ans+=dp[1][i]=dp[0][it->second];\n dp[0][i]= it->first==arr[i] ? dp[1][it->second] : dp[1][(--it)->second];\n sts[arr[i]]=i;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def oddEvenJumps(self, A: \'List[int]\') -> \'int\':\n\n sorted_indexes = sorted(range(len(A)), key = lambda i: A[i])\n \n oddnext = self.makeStack(sorted_indexes)\n\n sorted_indexes.sort(key = lambda i: A[i], reverse = True)\n\n evennext = self.makeStack(sorted_indexes)\n\n odd = [False] * len(A)\n even = [False] * len(A)\n\n odd[len(A)-1] = even[len(A)-1] = True\n\n for i in range(len(A)-2, -1, -1):\n\n if oddnext[i] is not None:\n odd[i] = even[oddnext[i]]\n\n if evennext[i] is not None:\n even[i] = odd[evennext[i]]\n\n return sum(odd)\n \n def makeStack(self, sorted_indexes):\n result = [None] * len(sorted_indexes)\n stack = []\n for i in sorted_indexes:\n while stack and i > stack[-1]:\n result[stack.pop()] = i\n stack.append(i)\n del stack\n return result\n```\n\n```Java []\nclass Solution {\n public int oddEvenJumps(int[] arr) {\n int[] count = new int[100001];\n boolean[][] res = new boolean[2][arr.length];\n res[0][arr.length - 1] = true;\n res[1][arr.length - 1] = true;\n count[arr[arr.length - 1]] = arr.length;\n int min = arr[arr.length - 1], max = arr[arr.length - 1];\n int result = 1;\n for(int i = arr.length - 2; i >= 0; i--) {\n int nextSmallIndex = findNextSmall(count, min, max, arr[i]);\n int nextLargeIndex = findNextLarge(count, min, max, arr[i]);\n if(nextSmallIndex == -1) {\n res[0][i] = false;\n } else {\n res[0][i] = res[1][nextSmallIndex];\n }\n if(nextLargeIndex == -1) {\n res[1][i] = false;\n } else {\n res[1][i] = res[0][nextLargeIndex];\n }\n count[arr[i]] = i + 1;\n min = Math.min(min, arr[i]);\n max = Math.max(max, arr[i]);\n if(res[0][i]) {\n result++;\n }\n }\n return result;\n }\n int findNextSmall(int[] count, int min, int max, int val) {\n\n for(int i=val; i <= max; i++) {\n if(count[i] != 0) {\n return count[i]-1;\n }\n }\n return -1;\n }\n int findNextLarge(int[] count, int min, int max, int val) {\n\n for(int i=val; i >= min; i--) {\n if(count[i] != 0) {\n return count[i]-1;\n }\n }\n return -1;\n }\n}\n```\n
438
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You may jump forward from index `i` to index `j` (with `i < j`) in the following way: * During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * It may be the case that for some index `i`, there are no legal jumps. A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). Return _the number of **good** starting indices_. **Example 1:** **Input:** arr = \[10,13,12,14,15\] **Output:** 2 **Explanation:** From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. **Example 2:** **Input:** arr = \[2,3,1,1,4\] **Output:** 3 **Explanation:** From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. **Example 3:** **Input:** arr = \[5,1,3,4,2\] **Output:** 3 **Explanation:** We can reach the end from starting indices 1, 2, and 4. **Constraints:** * `1 <= arr.length <= 2 * 104` * `0 <= arr[i] < 105`
null
Solution
odd-even-jump
1
1
```C++ []\nconst int FAIL_LO=-1, FAIL_HI=1e5+1;\nint dp[2][20001];\nclass Solution {\npublic:\n int oddEvenJumps(vector<int>& arr) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n=arr.size(), ans=1;\n map<int, int> sts;\n map<int, int>::iterator it;\n sts[arr[n-1]]=n-1;\n dp[0][n-1]=dp[1][n-1]=true;\n sts[FAIL_LO]=sts[FAIL_HI]=n;\n dp[0][n]=dp[1][n]=false; \n for(int i=n-2; i>=0; --i) {\n it=sts.lower_bound(arr[i]);\n ans+=dp[1][i]=dp[0][it->second];\n dp[0][i]= it->first==arr[i] ? dp[1][it->second] : dp[1][(--it)->second];\n sts[arr[i]]=i;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def oddEvenJumps(self, A: \'List[int]\') -> \'int\':\n\n sorted_indexes = sorted(range(len(A)), key = lambda i: A[i])\n \n oddnext = self.makeStack(sorted_indexes)\n\n sorted_indexes.sort(key = lambda i: A[i], reverse = True)\n\n evennext = self.makeStack(sorted_indexes)\n\n odd = [False] * len(A)\n even = [False] * len(A)\n\n odd[len(A)-1] = even[len(A)-1] = True\n\n for i in range(len(A)-2, -1, -1):\n\n if oddnext[i] is not None:\n odd[i] = even[oddnext[i]]\n\n if evennext[i] is not None:\n even[i] = odd[evennext[i]]\n\n return sum(odd)\n \n def makeStack(self, sorted_indexes):\n result = [None] * len(sorted_indexes)\n stack = []\n for i in sorted_indexes:\n while stack and i > stack[-1]:\n result[stack.pop()] = i\n stack.append(i)\n del stack\n return result\n```\n\n```Java []\nclass Solution {\n public int oddEvenJumps(int[] arr) {\n int[] count = new int[100001];\n boolean[][] res = new boolean[2][arr.length];\n res[0][arr.length - 1] = true;\n res[1][arr.length - 1] = true;\n count[arr[arr.length - 1]] = arr.length;\n int min = arr[arr.length - 1], max = arr[arr.length - 1];\n int result = 1;\n for(int i = arr.length - 2; i >= 0; i--) {\n int nextSmallIndex = findNextSmall(count, min, max, arr[i]);\n int nextLargeIndex = findNextLarge(count, min, max, arr[i]);\n if(nextSmallIndex == -1) {\n res[0][i] = false;\n } else {\n res[0][i] = res[1][nextSmallIndex];\n }\n if(nextLargeIndex == -1) {\n res[1][i] = false;\n } else {\n res[1][i] = res[0][nextLargeIndex];\n }\n count[arr[i]] = i + 1;\n min = Math.min(min, arr[i]);\n max = Math.max(max, arr[i]);\n if(res[0][i]) {\n result++;\n }\n }\n return result;\n }\n int findNextSmall(int[] count, int min, int max, int val) {\n\n for(int i=val; i <= max; i++) {\n if(count[i] != 0) {\n return count[i]-1;\n }\n }\n return -1;\n }\n int findNextLarge(int[] count, int min, int max, int val) {\n\n for(int i=val; i >= min; i--) {\n if(count[i] != 0) {\n return count[i]-1;\n }\n }\n return -1;\n }\n}\n```\n
438
Given an integer `n`, return _a binary string representing its representation in base_ `-2`. **Note** that the returned string should not have leading zeros unless the string is `"0 "`. **Example 1:** **Input:** n = 2 **Output:** "110 " **Explantion:** (-2)2 + (-2)1 = 2 **Example 2:** **Input:** n = 3 **Output:** "111 " **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 **Example 3:** **Input:** n = 4 **Output:** "100 " **Explantion:** (-2)2 = 4 **Constraints:** * `0 <= n <= 109`
null
Monotonic Stacks and Size Ordering Of Indices
odd-even-jump
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can build the correctly ordered sorted indices of the array based on increasing and decreasing size for the odd and even styled jumps by sorting based on their actual values for the index keys. This lets us generate abstracted versions of the sorted indices that we may wish to consider in our problem. \n\nSimilarly, in both cases, the use of a monotonic stack along with its order of casts off can be used to generate a resulting order of indices that may be utilized in reference to other indices. This allows us to map our possible jumps for both the even and odd cases. \n\nWith this, we can then sum up our odd jumps that are successful by using the associated mappings, since we know we have an odd case at base to consider (array has size of 1 as default, so odd will hold advantage over even in evaluation by at most 1) \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo do so : \nStart by getting the size of A \nGet sorted indices of all indices in A in increasing order based on the values in A for the those indices (get the range of values of size A in order of the values in A in increasing fashion) \n\nBuild a next odd position array as follows \n- by passing in the sorted indices for the increasing order \n- set up a resulting stack of [None] for size of the sorted indices \n- set up a monotonic stack with nothing in it \n- loop over your sorted indices by index \n - while you have a monotonic stack of indices priorly and the index at the top of the stack is strictly less than our current index \n - set the resulting stack at the popped stack position to current index (we can go from there to here) \n - append the current index to the stack \n- when done, your resulting list now has the indices of where you can get to based on wehre you are currently located in regards to the original array \n\nSort your indices, now in decreasing order \nBuild a next even position array following same form as above with your newly sorted indices. This is due to our need to go one way then the other as indicated in the problem description. \n\nSet up an even and odd index based can reach end result as Falses for size of A. \n\nMark the end position as True for each of these. \n\nFor index in range length of array - 2 and going backwards by 1 til -1 \n- if we have a possible jump in odd next \n - set odd at index to the value of even at odd next at index \n - this makes it so we do not get ahead of ourselves for what we can reach \n- Similarly for even next \n\nAt end, sum up the odd to account for off by 1 as end of list and list size is always 1. \n\n# Complexity\n- Time complexity : O(N log N) for sort \n - Takes O(N log N) to sort once \n - Takes O(N) to build using stack \n - Do this twice for evens and odds \n - Takes O(N) to go over indices again \n - Takes O(N) to sum up total \n\n- Space complexity : O(N) \n - You store the indices\n - You do it not once, not twice, but 5 times total \n - Still O(N) \n\n# Code\n```\nclass Solution :\n def oddEvenJumps(self, A : \'List[int]\') -> \'int\' :\n # start with something easy -> get the size of the array \n AL = len(A)\n # sorted indices are the sorted range of length A with key = lambda index using A[index]\n # basically, build the indices of the range of A, then sort according to the items in A \n # this generates the list of indices in sorted form without soting A \n sorted_indexes = sorted(range(AL), key = lambda index: A[index])\n # make a stack using the sorted indexes \n oddnext = self.makeStack(sorted_indexes)\n # sort the sorted indexes in reverse based on sizing in A. Cannot simply flip due to \n # a few weird edge cases where ordering in odd numbered lists would mess this up \n sorted_indexes.sort(key = lambda index : A[index], reverse = True)\n # build your next even numbered stack \n evennext = self.makeStack(sorted_indexes)\n # indices of jumps being good or bad for start \n # all are bad to start and prove worth \n odd = [False] * AL\n even = [False] * AL\n # except for the final index as that means you make it \n odd[AL-1] = even[AL-1] = True\n # loop over indices backwards from step one back \n for index in range(AL - 2, -1, -1) :\n # if next odd index is not None -> we have somewhere to jump to \n if oddnext[index] is not None :\n # and so our odd jump at this index should be our even jump at this next odd index \n # thus referencing that we made a jump from elsewhere to here \n odd[index] = even[oddnext[index]]\n # similarly on the reverse case \n if evennext[index] is not None:\n even[index] = odd[evennext[index]]\n # return sum of odd as we need the off by one format \n # this is due to the problem constraints being arrays of length 1 -> N \n # the 1 throws this to the odd case in this instance \n return sum(odd)\n \n def makeStack(self, sorted_indexes) :\n # set up result and a stack \n result = [None] * len(sorted_indexes)\n stack = []\n # loop over sorted indexes accordingly \n for index in sorted_indexes:\n # maintain stack as a monotonic stack of indexes\n while stack and index > stack[-1] :\n # and in doing so, track the unpacked indices as referring to index \n # this creates the necessary mapping for the problem relating odd and even \n # jumps to the next smallest such index \n result[stack.pop()] = index\n # append the new index to the stack when done with monotonic processing \n stack.append(index)\n # not truly needed but frees space\n del stack\n # return result when done \n return result\n```
1
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You may jump forward from index `i` to index `j` (with `i < j`) in the following way: * During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * It may be the case that for some index `i`, there are no legal jumps. A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). Return _the number of **good** starting indices_. **Example 1:** **Input:** arr = \[10,13,12,14,15\] **Output:** 2 **Explanation:** From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. **Example 2:** **Input:** arr = \[2,3,1,1,4\] **Output:** 3 **Explanation:** From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. **Example 3:** **Input:** arr = \[5,1,3,4,2\] **Output:** 3 **Explanation:** We can reach the end from starting indices 1, 2, and 4. **Constraints:** * `1 <= arr.length <= 2 * 104` * `0 <= arr[i] < 105`
null
Monotonic Stacks and Size Ordering Of Indices
odd-even-jump
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can build the correctly ordered sorted indices of the array based on increasing and decreasing size for the odd and even styled jumps by sorting based on their actual values for the index keys. This lets us generate abstracted versions of the sorted indices that we may wish to consider in our problem. \n\nSimilarly, in both cases, the use of a monotonic stack along with its order of casts off can be used to generate a resulting order of indices that may be utilized in reference to other indices. This allows us to map our possible jumps for both the even and odd cases. \n\nWith this, we can then sum up our odd jumps that are successful by using the associated mappings, since we know we have an odd case at base to consider (array has size of 1 as default, so odd will hold advantage over even in evaluation by at most 1) \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo do so : \nStart by getting the size of A \nGet sorted indices of all indices in A in increasing order based on the values in A for the those indices (get the range of values of size A in order of the values in A in increasing fashion) \n\nBuild a next odd position array as follows \n- by passing in the sorted indices for the increasing order \n- set up a resulting stack of [None] for size of the sorted indices \n- set up a monotonic stack with nothing in it \n- loop over your sorted indices by index \n - while you have a monotonic stack of indices priorly and the index at the top of the stack is strictly less than our current index \n - set the resulting stack at the popped stack position to current index (we can go from there to here) \n - append the current index to the stack \n- when done, your resulting list now has the indices of where you can get to based on wehre you are currently located in regards to the original array \n\nSort your indices, now in decreasing order \nBuild a next even position array following same form as above with your newly sorted indices. This is due to our need to go one way then the other as indicated in the problem description. \n\nSet up an even and odd index based can reach end result as Falses for size of A. \n\nMark the end position as True for each of these. \n\nFor index in range length of array - 2 and going backwards by 1 til -1 \n- if we have a possible jump in odd next \n - set odd at index to the value of even at odd next at index \n - this makes it so we do not get ahead of ourselves for what we can reach \n- Similarly for even next \n\nAt end, sum up the odd to account for off by 1 as end of list and list size is always 1. \n\n# Complexity\n- Time complexity : O(N log N) for sort \n - Takes O(N log N) to sort once \n - Takes O(N) to build using stack \n - Do this twice for evens and odds \n - Takes O(N) to go over indices again \n - Takes O(N) to sum up total \n\n- Space complexity : O(N) \n - You store the indices\n - You do it not once, not twice, but 5 times total \n - Still O(N) \n\n# Code\n```\nclass Solution :\n def oddEvenJumps(self, A : \'List[int]\') -> \'int\' :\n # start with something easy -> get the size of the array \n AL = len(A)\n # sorted indices are the sorted range of length A with key = lambda index using A[index]\n # basically, build the indices of the range of A, then sort according to the items in A \n # this generates the list of indices in sorted form without soting A \n sorted_indexes = sorted(range(AL), key = lambda index: A[index])\n # make a stack using the sorted indexes \n oddnext = self.makeStack(sorted_indexes)\n # sort the sorted indexes in reverse based on sizing in A. Cannot simply flip due to \n # a few weird edge cases where ordering in odd numbered lists would mess this up \n sorted_indexes.sort(key = lambda index : A[index], reverse = True)\n # build your next even numbered stack \n evennext = self.makeStack(sorted_indexes)\n # indices of jumps being good or bad for start \n # all are bad to start and prove worth \n odd = [False] * AL\n even = [False] * AL\n # except for the final index as that means you make it \n odd[AL-1] = even[AL-1] = True\n # loop over indices backwards from step one back \n for index in range(AL - 2, -1, -1) :\n # if next odd index is not None -> we have somewhere to jump to \n if oddnext[index] is not None :\n # and so our odd jump at this index should be our even jump at this next odd index \n # thus referencing that we made a jump from elsewhere to here \n odd[index] = even[oddnext[index]]\n # similarly on the reverse case \n if evennext[index] is not None:\n even[index] = odd[evennext[index]]\n # return sum of odd as we need the off by one format \n # this is due to the problem constraints being arrays of length 1 -> N \n # the 1 throws this to the odd case in this instance \n return sum(odd)\n \n def makeStack(self, sorted_indexes) :\n # set up result and a stack \n result = [None] * len(sorted_indexes)\n stack = []\n # loop over sorted indexes accordingly \n for index in sorted_indexes:\n # maintain stack as a monotonic stack of indexes\n while stack and index > stack[-1] :\n # and in doing so, track the unpacked indices as referring to index \n # this creates the necessary mapping for the problem relating odd and even \n # jumps to the next smallest such index \n result[stack.pop()] = index\n # append the new index to the stack when done with monotonic processing \n stack.append(index)\n # not truly needed but frees space\n del stack\n # return result when done \n return result\n```
1
Given an integer `n`, return _a binary string representing its representation in base_ `-2`. **Note** that the returned string should not have leading zeros unless the string is `"0 "`. **Example 1:** **Input:** n = 2 **Output:** "110 " **Explantion:** (-2)2 + (-2)1 = 2 **Example 2:** **Input:** n = 3 **Output:** "111 " **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 **Example 3:** **Input:** n = 4 **Output:** "100 " **Explantion:** (-2)2 = 4 **Constraints:** * `0 <= n <= 109`
null
Python O(nlogn) bottom-up DP easy to understand 260ms
odd-even-jump
0
1
```\nclass Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n \n\t\t# find next index of current index that is the least larger/smaller\n def getNextIndex(sortedIdx):\n stack = []\n result = [None] * len(sortedIdx)\n \n for i in sortedIdx:\n while stack and i > stack[-1]:\n result[stack.pop()] = i\n stack.append(i)\n return result\n \n sortedIdx = sorted(range(len(A)), key= lambda x: A[x])\n oddIndexes = getNextIndex(sortedIdx)\n sortedIdx.sort(key=lambda x: -A[x])\n evenIndexes = getNextIndex(sortedIdx)\n \n\t\t# [odd, even], the 0th jump is even\n dp = [[0,1] for _ in range(len(A))]\n \n for i in range(len(A)):\n if oddIndexes[i] is not None:\n dp[oddIndexes[i]][0] += dp[i][1]\n if evenIndexes[i] is not None:\n dp[evenIndexes[i]][1] += dp[i][0]\n\t\t\t\t\n return dp[-1][0] + dp[-1][1]\n```
13
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You may jump forward from index `i` to index `j` (with `i < j`) in the following way: * During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * It may be the case that for some index `i`, there are no legal jumps. A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). Return _the number of **good** starting indices_. **Example 1:** **Input:** arr = \[10,13,12,14,15\] **Output:** 2 **Explanation:** From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. **Example 2:** **Input:** arr = \[2,3,1,1,4\] **Output:** 3 **Explanation:** From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. **Example 3:** **Input:** arr = \[5,1,3,4,2\] **Output:** 3 **Explanation:** We can reach the end from starting indices 1, 2, and 4. **Constraints:** * `1 <= arr.length <= 2 * 104` * `0 <= arr[i] < 105`
null
Python O(nlogn) bottom-up DP easy to understand 260ms
odd-even-jump
0
1
```\nclass Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n \n\t\t# find next index of current index that is the least larger/smaller\n def getNextIndex(sortedIdx):\n stack = []\n result = [None] * len(sortedIdx)\n \n for i in sortedIdx:\n while stack and i > stack[-1]:\n result[stack.pop()] = i\n stack.append(i)\n return result\n \n sortedIdx = sorted(range(len(A)), key= lambda x: A[x])\n oddIndexes = getNextIndex(sortedIdx)\n sortedIdx.sort(key=lambda x: -A[x])\n evenIndexes = getNextIndex(sortedIdx)\n \n\t\t# [odd, even], the 0th jump is even\n dp = [[0,1] for _ in range(len(A))]\n \n for i in range(len(A)):\n if oddIndexes[i] is not None:\n dp[oddIndexes[i]][0] += dp[i][1]\n if evenIndexes[i] is not None:\n dp[evenIndexes[i]][1] += dp[i][0]\n\t\t\t\t\n return dp[-1][0] + dp[-1][1]\n```
13
Given an integer `n`, return _a binary string representing its representation in base_ `-2`. **Note** that the returned string should not have leading zeros unless the string is `"0 "`. **Example 1:** **Input:** n = 2 **Output:** "110 " **Explantion:** (-2)2 + (-2)1 = 2 **Example 2:** **Input:** n = 3 **Output:** "111 " **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 **Example 3:** **Input:** n = 4 **Output:** "100 " **Explantion:** (-2)2 = 4 **Constraints:** * `0 <= n <= 109`
null
[Python3] dp
odd-even-jump
0
1
\n```\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n large = [-1] * len(arr)\n small = [-1] * len(arr)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (x[1], x[0])): \n while stack and stack[-1] < i: large[stack.pop()] = i \n stack.append(i)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (-x[1], x[0])): \n while stack and stack[-1] < i: small[stack.pop()] = i\n stack.append(i)\n \n odd = [0] * len(arr)\n even = [0] * len(arr)\n odd[-1] = even[-1] = 1\n for i in reversed(range(len(arr))): \n if 0 <= large[i]: odd[i] = even[large[i]]\n if 0 <= small[i]: even[i] = odd[small[i]]\n return sum(odd)\n```
4
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You may jump forward from index `i` to index `j` (with `i < j`) in the following way: * During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`. * It may be the case that for some index `i`, there are no legal jumps. A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once). Return _the number of **good** starting indices_. **Example 1:** **Input:** arr = \[10,13,12,14,15\] **Output:** 2 **Explanation:** From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more. From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more. From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end. From starting index i = 4, we have reached the end already. In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of jumps. **Example 2:** **Input:** arr = \[2,3,1,1,4\] **Output:** 3 **Explanation:** From starting index i = 0, we make jumps to i = 1, i = 2, i = 3: During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\]. During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3 During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\]. We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good. In a similar manner, we can deduce that: From starting index i = 1, we jump to i = 4, so we reach the end. From starting index i = 2, we jump to i = 3, and then we can't jump anymore. From starting index i = 3, we jump to i = 4, so we reach the end. From starting index i = 4, we are already at the end. In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some number of jumps. **Example 3:** **Input:** arr = \[5,1,3,4,2\] **Output:** 3 **Explanation:** We can reach the end from starting indices 1, 2, and 4. **Constraints:** * `1 <= arr.length <= 2 * 104` * `0 <= arr[i] < 105`
null
[Python3] dp
odd-even-jump
0
1
\n```\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n large = [-1] * len(arr)\n small = [-1] * len(arr)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (x[1], x[0])): \n while stack and stack[-1] < i: large[stack.pop()] = i \n stack.append(i)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (-x[1], x[0])): \n while stack and stack[-1] < i: small[stack.pop()] = i\n stack.append(i)\n \n odd = [0] * len(arr)\n even = [0] * len(arr)\n odd[-1] = even[-1] = 1\n for i in reversed(range(len(arr))): \n if 0 <= large[i]: odd[i] = even[large[i]]\n if 0 <= small[i]: even[i] = odd[small[i]]\n return sum(odd)\n```
4
Given an integer `n`, return _a binary string representing its representation in base_ `-2`. **Note** that the returned string should not have leading zeros unless the string is `"0 "`. **Example 1:** **Input:** n = 2 **Output:** "110 " **Explantion:** (-2)2 + (-2)1 = 2 **Example 2:** **Input:** n = 3 **Output:** "111 " **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 **Example 3:** **Input:** n = 4 **Output:** "100 " **Explantion:** (-2)2 = 4 **Constraints:** * `0 <= n <= 109`
null
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator]
squares-of-a-sorted-array
0
1
This question is a cool one in that there is lots of different approaches, each with its own pros and cons. And then there\'s also different ways of implementing them, depending on whether you are after raw performance or beautiful code.\n\nSomething slightly irritating is that leetcode isn\'t testing with big enough test cases to push the time complexity of the O(n-log-n) approaches below the O(n) ones. It goes to show, sometimes what "wins" at the notoriously inaccurate Leetcode time/ space percentiles isn\'t always the best in practice, or even in an interview.\n\n# Approach #1: Using built in sort.\nThere are a few similar approaches we can take here, each with its own subtle differences. All are of an ```O(n-log-n)``` time complexity due to using the inbuilt sort, although they differ in their space complexity.\n\n## a) Overwriting input:\n\n```\n def sortedSquares(self, A: List[int]) -> List[int]:\n for i in range(len(A)):\n A[i] *= A[i]\n A.sort()\n return A\n```\n\nThis approach uses ```O(1)``` memory beyond the input array, and is truely **in-place**. *However*, it is not always a good idea to overwrite inputs. Remember that because we passed it by reference, the original is actually lost. Often functions like this are a part of an API, and in a lot of cases, nobody wants an API that clobbers their input.\n\nI think it\'s best to ask your interviewer if they want something done **in-place** or not. It is a common misconception that we should *always* be trying to do things in-place, overwriting the inputs.\n\n## b) Making a new array, not in place, O(n) auxillary space.\n\n```\ndef sortedSquares(self, A: List[int]) -> List[int]:\n return sorted([v**2 for v in A])\n```\n\nAhhhh, our good \'ol clever Python one-liner. There is a suble space inefficiency in it though. For a brief moment, we\'re using 3n memory, not 2n. The one line has 2 not-in-place operations in it; the list comprehension creates a new list, and so does sorted. The list comprehension list is promptly garbage collected upon function return, *but* because it was briefly there, the max memory usage was ultimately 3n. With lots of memory, this is totally fine, and the pythonic nature of it makes it a great solution. But we do need to be aware of it.\n\n## c) Making a new array, not in place, O(1) auxillary space.\n\nMaking a new array, in place.\n\n```\ndef sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [v**2 for v in A]\n\t\treturn_array.sort() # This is in place!\n\t\treturn return_array\n```\n\nSo, is this ```O(1)``` space or ```O(n)``` space? Arguments can be made either way, sometimes people say to count the output data stucture in the calculation, and sometimes they don\'t. If we\'re talking about *auxillary* space, we generally don\'t count the output data structure, which would make it ```O(1)```. I think this is a more accurate way of putting it -- we are trying to measure what the algorithm itself is using, not just what the inevitable size of the output is. But it\'s important to be clear in interviews what you are and aren\'t counting.\n\n## Overall thoughts on these approaches\nYou won\'t be coding any of these approaches in an interview (in my own very, very limited experience though!). By all means your interviewer will want to hear that you could do it this way, but there is 3 big problems if they are the only approaches you can come up with.\n1) We shouldn\'t need to use an O(n-log-n) sort operation on data that for the most part is already sorted. There\'s something not right with that. If this is the approach the interviewer wanted, they wouldn\'t have given you the numbers in a sorted list in the first place.\n2) Following on from that, there are O(n) solutions.\n3) Why would they be asking you to code something so trivial? Let\'s be honest. They want to see you writing some meaty code. \n\nThe remaining approaches exploit the existing sorting. If we were to go down the list squaring each number, we\'d have a "v" sorted list, in that the squares of the negatives decrease, and then the squares of the positives increase, i.e.\n```[-4, -2, -1, 0, 1, 2, 3, 5] -> [16, 4, 1, 0, 1, 4, 9, 25]```\n\nWe can get this into a sorted list in ```O(n)``` time.\n# Approach 2: Raw pointers\nIn terms of performance, you can\'t beat this (well, if leetcode actually tested on massive test cases...). It\'s O(n) time, and O(1) auxillary space.\n\n```\nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [0] * len(A)\n write_pointer = len(A) - 1\n left_read_pointer = 0\n right_read_pointer = len(A) - 1\n left_square = A[left_read_pointer] ** 2\n right_square = A[right_read_pointer] ** 2\n while write_pointer >= 0:\n if left_square > right_square:\n return_array[write_pointer] = left_square\n left_read_pointer += 1\n left_square = A[left_read_pointer] ** 2\n else:\n return_array[write_pointer] = right_square\n right_read_pointer -= 1\n right_square = A[right_read_pointer] ** 2\n write_pointer -= 1\n return return_array\n```\n\n# Approach 3: Using a deque \nThis approach is the first of the trading-off-some-raw-performance-for-beauty=and-elegance approaches. It remains as ```O(n)``` *time complexity* like approach 2, but the heavy-weight nature of it will slow it down by a constant amount. If this doesn\'t matter though (and in a lot of cases it doesn\'t), then the elegance will reduce the risk of bugs and lead to more readable and maintable code. It is also important to note that it does use ```O(n)``` *auxillary space*.\n\n```\n def sortedSquares(self, A: List[int]) -> List[int]:\n number_deque = collections.deque(A)\n reverse_sorted_squares = []\n while number_deque:\n left_square = number_deque[0] ** 2\n right_square = number_deque[-1] ** 2\n if left_square > right_square:\n reverse_sorted_squares.append(left_square)\n number_deque.popleft()\n else:\n reverse_sorted_squares.append(right_square)\n number_deque.pop()\n return reverse_sorted_squares[::-1]\n```\n\n# Approach 4: The iterator pattern\nThis is one of my favourites. While it suffers from the same constant time slowdown as the previous approach, its auxillary space usage remains at ```O(1)```. The iterator pattern is a great way of splitting up code into more testable units. It seperates the problem of getting the squares in a sorted order from the problem of writing them into an array.\n\nThere are 2 subapproaches. One that returns the squares in reversed order, and one that puts them around the right way. The latter is more complex to code, but it means that the code dealing with the writing doesn\'t have to reverse them, and it is still a time complexity of ```O(n)``` and an auxillary space usage of ```O(1)```.\n\n## a) Iterator returning from largest -> smallest\n\n```\nclass SquaresIterator(object):\n def __init__(self, sorted_array):\n self.sorted_array = sorted_array\n self.left_pointer = 0\n self.right_pointer = len(sorted_array) - 1\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.left_pointer > self.right_pointer:\n raise StopIteration\n left_square = self.sorted_array[self.left_pointer] ** 2\n right_square = self.sorted_array[self.right_pointer] ** 2\n if left_square > right_square:\n self.left_pointer += 1\n return left_square\n else:\n self.right_pointer -= 1\n return right_square\n \n\nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [0] * len(A)\n write_pointer = len(A) - 1\n for square in SquaresIterator(A):\n return_array[write_pointer] = square\n write_pointer -= 1\n return return_array\n```\n\n## b) Iterator returning from smallest -> largest\n\nThis one uses a binary search to set the left and right pointers in the middle of the array to begin with. This way, the items are returned in the correct order. We don\'t even need explicit write code here!\n\n```\nclass SquaresIterator(object):\n \n def __init__(self, sorted_array):\n self.sorted_array = sorted_array\n self.left_pointer, self.right_pointer = self._get_pointers()\n \n def __iter__(self):\n return self\n \n def __next__(self):\n \n # If there\'s no values remaining.\n if self.left_pointer < 0 and self.right_pointer >= len(self.sorted_array):\n raise StopIteration\n \n # If there\'s no values remaining on the left end.\n if self.left_pointer < 0:\n self.right_pointer += 1\n return self.sorted_array[self.right_pointer - 1] ** 2\n \n # If there\'s no values remaining on the right end.\n if self.right_pointer >= len(self.sorted_array):\n self.left_pointer -= 1\n return self.sorted_array[self.left_pointer + 1] ** 2\n \n # If there\'s values remaining on both ends.\n left_square = self.sorted_array[self.left_pointer] ** 2\n right_square = self.sorted_array[self.right_pointer] ** 2\n if left_square < right_square:\n self.left_pointer -= 1\n return left_square\n else:\n self.right_pointer += 1\n return right_square\n \n \n def _get_pointers(self):\n low = 0\n high = len(self.sorted_array)\n while high - low > 1:\n mid = low + (high - low) // 2\n if self.sorted_array[mid] > 0:\n high = mid\n else:\n low = mid\n return low, high\n \n \nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return list(SquaresIterator(A))\n```\n\n# Approach 5: Generators\nWhy are we using iterators for such a simple task? We can use a generator function instead!\n\nAgain, it\'s O(n) time with O(1) auxillary space.\n\n```\nclass Solution:\n \n def generate_sorted_squares(self, nums):\n \n # Start by doing our binary search to find where\n # to place the pointers.\n left = 0\n right = len(nums)\n while right - left > 1:\n mid = left + (right - left) // 2\n if nums[mid] > 0:\n right = mid\n else:\n left = mid\n \n # And now the main generator loop. The condition is the negation\n # of the StopIteration condition for the iterator approach.\n while left >= 0 or right < len(nums):\n if left < 0:\n right += 1\n yield nums[right - 1] ** 2\n elif right >= len(nums):\n left -= 1\n yield nums[left + 1] ** 2\n else:\n left_square = nums[left] ** 2\n right_square = nums[right] ** 2\n if left_square < right_square:\n left -= 1\n yield left_square\n else:\n right += 1\n yield right_square\n \n \n def sortedSquares(self, A: List[int]) -> List[int]:\n return list(self.generate_sorted_squares(A))\n```\n\n# In conclusion\nI\'m sure there are many more approaches. Another would be to combine the 2 pointer technique with the binary search. \n\nI\'m interested in thoughts people have on which is best in an interview!
552
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator]
squares-of-a-sorted-array
0
1
This question is a cool one in that there is lots of different approaches, each with its own pros and cons. And then there\'s also different ways of implementing them, depending on whether you are after raw performance or beautiful code.\n\nSomething slightly irritating is that leetcode isn\'t testing with big enough test cases to push the time complexity of the O(n-log-n) approaches below the O(n) ones. It goes to show, sometimes what "wins" at the notoriously inaccurate Leetcode time/ space percentiles isn\'t always the best in practice, or even in an interview.\n\n# Approach #1: Using built in sort.\nThere are a few similar approaches we can take here, each with its own subtle differences. All are of an ```O(n-log-n)``` time complexity due to using the inbuilt sort, although they differ in their space complexity.\n\n## a) Overwriting input:\n\n```\n def sortedSquares(self, A: List[int]) -> List[int]:\n for i in range(len(A)):\n A[i] *= A[i]\n A.sort()\n return A\n```\n\nThis approach uses ```O(1)``` memory beyond the input array, and is truely **in-place**. *However*, it is not always a good idea to overwrite inputs. Remember that because we passed it by reference, the original is actually lost. Often functions like this are a part of an API, and in a lot of cases, nobody wants an API that clobbers their input.\n\nI think it\'s best to ask your interviewer if they want something done **in-place** or not. It is a common misconception that we should *always* be trying to do things in-place, overwriting the inputs.\n\n## b) Making a new array, not in place, O(n) auxillary space.\n\n```\ndef sortedSquares(self, A: List[int]) -> List[int]:\n return sorted([v**2 for v in A])\n```\n\nAhhhh, our good \'ol clever Python one-liner. There is a suble space inefficiency in it though. For a brief moment, we\'re using 3n memory, not 2n. The one line has 2 not-in-place operations in it; the list comprehension creates a new list, and so does sorted. The list comprehension list is promptly garbage collected upon function return, *but* because it was briefly there, the max memory usage was ultimately 3n. With lots of memory, this is totally fine, and the pythonic nature of it makes it a great solution. But we do need to be aware of it.\n\n## c) Making a new array, not in place, O(1) auxillary space.\n\nMaking a new array, in place.\n\n```\ndef sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [v**2 for v in A]\n\t\treturn_array.sort() # This is in place!\n\t\treturn return_array\n```\n\nSo, is this ```O(1)``` space or ```O(n)``` space? Arguments can be made either way, sometimes people say to count the output data stucture in the calculation, and sometimes they don\'t. If we\'re talking about *auxillary* space, we generally don\'t count the output data structure, which would make it ```O(1)```. I think this is a more accurate way of putting it -- we are trying to measure what the algorithm itself is using, not just what the inevitable size of the output is. But it\'s important to be clear in interviews what you are and aren\'t counting.\n\n## Overall thoughts on these approaches\nYou won\'t be coding any of these approaches in an interview (in my own very, very limited experience though!). By all means your interviewer will want to hear that you could do it this way, but there is 3 big problems if they are the only approaches you can come up with.\n1) We shouldn\'t need to use an O(n-log-n) sort operation on data that for the most part is already sorted. There\'s something not right with that. If this is the approach the interviewer wanted, they wouldn\'t have given you the numbers in a sorted list in the first place.\n2) Following on from that, there are O(n) solutions.\n3) Why would they be asking you to code something so trivial? Let\'s be honest. They want to see you writing some meaty code. \n\nThe remaining approaches exploit the existing sorting. If we were to go down the list squaring each number, we\'d have a "v" sorted list, in that the squares of the negatives decrease, and then the squares of the positives increase, i.e.\n```[-4, -2, -1, 0, 1, 2, 3, 5] -> [16, 4, 1, 0, 1, 4, 9, 25]```\n\nWe can get this into a sorted list in ```O(n)``` time.\n# Approach 2: Raw pointers\nIn terms of performance, you can\'t beat this (well, if leetcode actually tested on massive test cases...). It\'s O(n) time, and O(1) auxillary space.\n\n```\nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [0] * len(A)\n write_pointer = len(A) - 1\n left_read_pointer = 0\n right_read_pointer = len(A) - 1\n left_square = A[left_read_pointer] ** 2\n right_square = A[right_read_pointer] ** 2\n while write_pointer >= 0:\n if left_square > right_square:\n return_array[write_pointer] = left_square\n left_read_pointer += 1\n left_square = A[left_read_pointer] ** 2\n else:\n return_array[write_pointer] = right_square\n right_read_pointer -= 1\n right_square = A[right_read_pointer] ** 2\n write_pointer -= 1\n return return_array\n```\n\n# Approach 3: Using a deque \nThis approach is the first of the trading-off-some-raw-performance-for-beauty=and-elegance approaches. It remains as ```O(n)``` *time complexity* like approach 2, but the heavy-weight nature of it will slow it down by a constant amount. If this doesn\'t matter though (and in a lot of cases it doesn\'t), then the elegance will reduce the risk of bugs and lead to more readable and maintable code. It is also important to note that it does use ```O(n)``` *auxillary space*.\n\n```\n def sortedSquares(self, A: List[int]) -> List[int]:\n number_deque = collections.deque(A)\n reverse_sorted_squares = []\n while number_deque:\n left_square = number_deque[0] ** 2\n right_square = number_deque[-1] ** 2\n if left_square > right_square:\n reverse_sorted_squares.append(left_square)\n number_deque.popleft()\n else:\n reverse_sorted_squares.append(right_square)\n number_deque.pop()\n return reverse_sorted_squares[::-1]\n```\n\n# Approach 4: The iterator pattern\nThis is one of my favourites. While it suffers from the same constant time slowdown as the previous approach, its auxillary space usage remains at ```O(1)```. The iterator pattern is a great way of splitting up code into more testable units. It seperates the problem of getting the squares in a sorted order from the problem of writing them into an array.\n\nThere are 2 subapproaches. One that returns the squares in reversed order, and one that puts them around the right way. The latter is more complex to code, but it means that the code dealing with the writing doesn\'t have to reverse them, and it is still a time complexity of ```O(n)``` and an auxillary space usage of ```O(1)```.\n\n## a) Iterator returning from largest -> smallest\n\n```\nclass SquaresIterator(object):\n def __init__(self, sorted_array):\n self.sorted_array = sorted_array\n self.left_pointer = 0\n self.right_pointer = len(sorted_array) - 1\n \n def __iter__(self):\n return self\n \n def __next__(self):\n if self.left_pointer > self.right_pointer:\n raise StopIteration\n left_square = self.sorted_array[self.left_pointer] ** 2\n right_square = self.sorted_array[self.right_pointer] ** 2\n if left_square > right_square:\n self.left_pointer += 1\n return left_square\n else:\n self.right_pointer -= 1\n return right_square\n \n\nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [0] * len(A)\n write_pointer = len(A) - 1\n for square in SquaresIterator(A):\n return_array[write_pointer] = square\n write_pointer -= 1\n return return_array\n```\n\n## b) Iterator returning from smallest -> largest\n\nThis one uses a binary search to set the left and right pointers in the middle of the array to begin with. This way, the items are returned in the correct order. We don\'t even need explicit write code here!\n\n```\nclass SquaresIterator(object):\n \n def __init__(self, sorted_array):\n self.sorted_array = sorted_array\n self.left_pointer, self.right_pointer = self._get_pointers()\n \n def __iter__(self):\n return self\n \n def __next__(self):\n \n # If there\'s no values remaining.\n if self.left_pointer < 0 and self.right_pointer >= len(self.sorted_array):\n raise StopIteration\n \n # If there\'s no values remaining on the left end.\n if self.left_pointer < 0:\n self.right_pointer += 1\n return self.sorted_array[self.right_pointer - 1] ** 2\n \n # If there\'s no values remaining on the right end.\n if self.right_pointer >= len(self.sorted_array):\n self.left_pointer -= 1\n return self.sorted_array[self.left_pointer + 1] ** 2\n \n # If there\'s values remaining on both ends.\n left_square = self.sorted_array[self.left_pointer] ** 2\n right_square = self.sorted_array[self.right_pointer] ** 2\n if left_square < right_square:\n self.left_pointer -= 1\n return left_square\n else:\n self.right_pointer += 1\n return right_square\n \n \n def _get_pointers(self):\n low = 0\n high = len(self.sorted_array)\n while high - low > 1:\n mid = low + (high - low) // 2\n if self.sorted_array[mid] > 0:\n high = mid\n else:\n low = mid\n return low, high\n \n \nclass Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return list(SquaresIterator(A))\n```\n\n# Approach 5: Generators\nWhy are we using iterators for such a simple task? We can use a generator function instead!\n\nAgain, it\'s O(n) time with O(1) auxillary space.\n\n```\nclass Solution:\n \n def generate_sorted_squares(self, nums):\n \n # Start by doing our binary search to find where\n # to place the pointers.\n left = 0\n right = len(nums)\n while right - left > 1:\n mid = left + (right - left) // 2\n if nums[mid] > 0:\n right = mid\n else:\n left = mid\n \n # And now the main generator loop. The condition is the negation\n # of the StopIteration condition for the iterator approach.\n while left >= 0 or right < len(nums):\n if left < 0:\n right += 1\n yield nums[right - 1] ** 2\n elif right >= len(nums):\n left -= 1\n yield nums[left + 1] ** 2\n else:\n left_square = nums[left] ** 2\n right_square = nums[right] ** 2\n if left_square < right_square:\n left -= 1\n yield left_square\n else:\n right += 1\n yield right_square\n \n \n def sortedSquares(self, A: List[int]) -> List[int]:\n return list(self.generate_sorted_squares(A))\n```\n\n# In conclusion\nI\'m sure there are many more approaches. Another would be to combine the 2 pointer technique with the binary search. \n\nI\'m interested in thoughts people have on which is best in an interview!
552
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Python3 solution (runtime is faster than 94.92%, memory is less than 49.24%)
squares-of-a-sorted-array
0
1
Hi everyone. In my solution I used lambda functions because I wanted to make the solution shorter.\nSurprisingly, after a successfull run, it became faster than the most submitted.\nHere you are.\n```\n def sortedSquares(self, nums: List[int]) -> List[int]:\n sq_nums = list(map(lambda n: n**2, nums))\n sq_nums.sort()\n return sq_nums\n```\n
2
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
Python3 solution (runtime is faster than 94.92%, memory is less than 49.24%)
squares-of-a-sorted-array
0
1
Hi everyone. In my solution I used lambda functions because I wanted to make the solution shorter.\nSurprisingly, after a successfull run, it became faster than the most submitted.\nHere you are.\n```\n def sortedSquares(self, nums: List[int]) -> List[int]:\n sq_nums = list(map(lambda n: n**2, nums))\n sq_nums.sort()\n return sq_nums\n```\n
2
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
with out loops Square of a sorted array
squares-of-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n def M(a):\n return a**2\n\n\n x = list(map(M,nums))\n x.sort()\n return x\n```
1
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
with out loops Square of a sorted array
squares-of-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n def M(a):\n return a**2\n\n\n x = list(map(M,nums))\n x.sort()\n return x\n```
1
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Python | one line of code | and Two pointers
squares-of-a-sorted-array
0
1
**One line of code**\n\n\tclass Solution:\n\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\treturn sorted(list(map(lambda x:x**2,nums)))\n\t\t\t\n\t\t\t\nusing Two pointer\n\n\t\tclass Solution:\n\t\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\t\tl,r=0,len(nums)-1\n\t\t\t\toutput=[]\n\t\t\t\twhile l<=r:\n\t\t\t\t\tif abs(nums[r])>abs(nums[l]):\n\t\t\t\t\t\toutput.append(nums[r]**2)\n\t\t\t\t\t\tr-=1\n\t\t\t\t\telse:\n\t\t\t\t\t\toutput.append(nums[l]**2)\n\t\t\t\t\t\tl+=1\n\t\t\t\treturn output[::-1]\n\n
1
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
Python | one line of code | and Two pointers
squares-of-a-sorted-array
0
1
**One line of code**\n\n\tclass Solution:\n\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\treturn sorted(list(map(lambda x:x**2,nums)))\n\t\t\t\n\t\t\t\nusing Two pointer\n\n\t\tclass Solution:\n\t\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\t\tl,r=0,len(nums)-1\n\t\t\t\toutput=[]\n\t\t\t\twhile l<=r:\n\t\t\t\t\tif abs(nums[r])>abs(nums[l]):\n\t\t\t\t\t\toutput.append(nums[r]**2)\n\t\t\t\t\t\tr-=1\n\t\t\t\t\telse:\n\t\t\t\t\t\toutput.append(nums[l]**2)\n\t\t\t\t\t\tl+=1\n\t\t\t\treturn output[::-1]\n\n
1
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
[Python] - Two Pointer - Clean & Simple - O(n) Solution
squares-of-a-sorted-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nHere, We are having many solutions but here i am showing you just 2. \n1. We are having a **Two Pointer** approach which should work well.\n - Here we had one pointer $$i$$ at $$start$$ index, second pointer $$j$$ at $$end$$ index , a list $$ans$$ of size n, and a $$k$$ pointer to update value in $$ans$$ list.\n - Then, we start comapring absolute value in nums where pointers are pointing.\n - ` if abs(nums[l]) > nums[r]:`\n - So, we update value at $$k$$ position in ans with ` nums[l] * nums[l]`.\n - ` else:`\n - Update value at $$k$$ position in ans with ` nums[r] * nums[r]`.\n2. **List Comprehension + Sorting:** \n - Here, we are making a list with square of nums using list comprehension and making it sort and directly returning it.\n\n# Code\n## 1. Two Pointer Approach :\n\n### Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n # Two Pointer Approach\n n = len(nums)\n l, r = 0, n - 1\n k = n - 1\n ans = [0] * n\n while k >= 0:\n if abs(nums[l]) > nums[r]:\n ans[k] = nums[l] * nums[l]\n l += 1\n else:\n ans[k] = nums[r] * nums[r]\n r -= 1\n k -= 1\n return ans\n\n```\n## 2. List Comprehension + Sorting :\n\n### Complexity\n- Time complexity: $$O(nlogn)$$\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```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n # One Liner\n return sorted([num * num for num in nums])\n \n```\n- Here I personally felt **List Comprehension + Sorting** isn\'t fast but this approach give me fast runtime in submission.\n- So, don\'t know what\'s wrong with leetcode runtime checking algorithm.\n- If anyone have suggestion please comment it.\n- If you found it helpful please upvote, it helps to create such a more content.
20
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
[Python] - Two Pointer - Clean & Simple - O(n) Solution
squares-of-a-sorted-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nHere, We are having many solutions but here i am showing you just 2. \n1. We are having a **Two Pointer** approach which should work well.\n - Here we had one pointer $$i$$ at $$start$$ index, second pointer $$j$$ at $$end$$ index , a list $$ans$$ of size n, and a $$k$$ pointer to update value in $$ans$$ list.\n - Then, we start comapring absolute value in nums where pointers are pointing.\n - ` if abs(nums[l]) > nums[r]:`\n - So, we update value at $$k$$ position in ans with ` nums[l] * nums[l]`.\n - ` else:`\n - Update value at $$k$$ position in ans with ` nums[r] * nums[r]`.\n2. **List Comprehension + Sorting:** \n - Here, we are making a list with square of nums using list comprehension and making it sort and directly returning it.\n\n# Code\n## 1. Two Pointer Approach :\n\n### Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n # Two Pointer Approach\n n = len(nums)\n l, r = 0, n - 1\n k = n - 1\n ans = [0] * n\n while k >= 0:\n if abs(nums[l]) > nums[r]:\n ans[k] = nums[l] * nums[l]\n l += 1\n else:\n ans[k] = nums[r] * nums[r]\n r -= 1\n k -= 1\n return ans\n\n```\n## 2. List Comprehension + Sorting :\n\n### Complexity\n- Time complexity: $$O(nlogn)$$\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```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n # One Liner\n return sorted([num * num for num in nums])\n \n```\n- Here I personally felt **List Comprehension + Sorting** isn\'t fast but this approach give me fast runtime in submission.\n- So, don\'t know what\'s wrong with leetcode runtime checking algorithm.\n- If anyone have suggestion please comment it.\n- If you found it helpful please upvote, it helps to create such a more content.
20
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Very simple 1 liner
squares-of-a-sorted-array
0
1
\n# Code\n```\nclass Solution:\n\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\treturn sorted(list(map(lambda x:x**2,nums)))\t\n```\n# Line by line \n\n```py\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)):\n nums[i] = nums[i]**2\n return sorted(nums)\n```
1
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
Very simple 1 liner
squares-of-a-sorted-array
0
1
\n# Code\n```\nclass Solution:\n\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\treturn sorted(list(map(lambda x:x**2,nums)))\t\n```\n# Line by line \n\n```py\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)):\n nums[i] = nums[i]**2\n return sorted(nums)\n```
1
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Python || 96% beats || easy solution.....
squares-of-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n for i in range(len(nums)):\n nums[i]=nums[i]*nums[i]\n nums.sort()\n return nums \n```
2
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
Python || 96% beats || easy solution.....
squares-of-a-sorted-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \n for i in range(len(nums)):\n nums[i]=nums[i]*nums[i]\n nums.sort()\n return nums \n```
2
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Solution
longest-turbulent-subarray
1
1
```C++ []\nclass Solution {\npublic:\nSolution(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n }\n int maxTurbulenceSize(vector<int>& arr) {\n int flag=0,n=arr.size(),res=0,i=0,j=1;\n if(arr.size()==1)\n return n;\n if(n==2&&arr[i]==arr[j])\n return 1;\n else if(arr[i]==arr[j])\n {\n i++;j++;\n }\n while(j<n)\n {\n if(arr[j-1]>arr[j]&&flag!=1)\n flag=1;\n else if(arr[j-1]<arr[j]&&flag!=2)\n flag=2;\n else if(arr[j-1]==arr[j])\n {\n i=j;\n flag=0;\n }\n else\n i=j-1;\n res=max(res,j-i+1);\n j++;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n\n max_size = 1\n\n last = arr[0]\n\n curr_size = 1\n \n last_op = 0 # 0 == eq, 1 == gt, 2 == lt\n\n for n in arr[1:]:\n if n > last:\n if last_op != 2:\n curr_size = 2\n else:\n curr_size += 1\n last_op = 1\n elif n < last:\n if last_op != 1:\n curr_size = 2\n else:\n curr_size += 1\n last_op = 2\n else:\n curr_size = 1\n last_op = 0\n \n last = n\n\n if curr_size > max_size:\n max_size = curr_size\n\n return max_size\n```\n\n```Java []\nclass Solution {\n public static int maxTurbulenceSize(int[] arr) {\n int k = 1;\n int max = 1;\n char prev = \'p\';\n char current = \'p\';\n for (int i = 0; i < arr.length - 1; i++) {\n if (arr[i] < arr[i + 1]) {\n current = \'<\';\n } else if(arr[i] > arr[i + 1]) {\n current = \'>\';\n }\n else{prev = \'=\';\n if (k > max){max = k;}\n k = 1;\n continue;\n }\n if (current != prev) {\n k++;\n }\n else{\n if (k > max){max = k;}\n k = 2;\n }\n prev = current;\n }\n if (k > max){max = k;}\n if(k==arr.length){\n max=k;\n }\n return max;\n }\n}\n```\n
1
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
Solution
longest-turbulent-subarray
1
1
```C++ []\nclass Solution {\npublic:\nSolution(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n }\n int maxTurbulenceSize(vector<int>& arr) {\n int flag=0,n=arr.size(),res=0,i=0,j=1;\n if(arr.size()==1)\n return n;\n if(n==2&&arr[i]==arr[j])\n return 1;\n else if(arr[i]==arr[j])\n {\n i++;j++;\n }\n while(j<n)\n {\n if(arr[j-1]>arr[j]&&flag!=1)\n flag=1;\n else if(arr[j-1]<arr[j]&&flag!=2)\n flag=2;\n else if(arr[j-1]==arr[j])\n {\n i=j;\n flag=0;\n }\n else\n i=j-1;\n res=max(res,j-i+1);\n j++;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n\n max_size = 1\n\n last = arr[0]\n\n curr_size = 1\n \n last_op = 0 # 0 == eq, 1 == gt, 2 == lt\n\n for n in arr[1:]:\n if n > last:\n if last_op != 2:\n curr_size = 2\n else:\n curr_size += 1\n last_op = 1\n elif n < last:\n if last_op != 1:\n curr_size = 2\n else:\n curr_size += 1\n last_op = 2\n else:\n curr_size = 1\n last_op = 0\n \n last = n\n\n if curr_size > max_size:\n max_size = curr_size\n\n return max_size\n```\n\n```Java []\nclass Solution {\n public static int maxTurbulenceSize(int[] arr) {\n int k = 1;\n int max = 1;\n char prev = \'p\';\n char current = \'p\';\n for (int i = 0; i < arr.length - 1; i++) {\n if (arr[i] < arr[i + 1]) {\n current = \'<\';\n } else if(arr[i] > arr[i + 1]) {\n current = \'>\';\n }\n else{prev = \'=\';\n if (k > max){max = k;}\n k = 1;\n continue;\n }\n if (current != prev) {\n k++;\n }\n else{\n if (k > max){max = k;}\n k = 2;\n }\n prev = current;\n }\n if (k > max){max = k;}\n if(k==arr.length){\n max=k;\n }\n return max;\n }\n}\n```\n
1
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
XOR with DP bottom up with optimization; DP Beginner friendly;
longest-turbulent-subarray
0
1
\n# Approach 1: Bottom up, Linear Space\n<!-- Describe your approach to solving the problem. -->\n\nMy intuition when i see turbuelnce subarry is that \n```\n> < > < > < > <\n```\nFor a simple array [a, b, c] to be a turbulent array, we could have\n```\nSituation1: a > b < c\nSituation2: a < b > c\n``` \nThe signs are fliping with every single time and it exisits a concise way to represent the state. If a, b ,c are distinct numbers (no duplicate) then the array `[a,b,c]` is turbulent is equivalent to the following statement\n```\n(a > b) XOR (b > c)\n```\n\nThen, Similar to bottom-up solution for maximum subarray, we just need to define a `DP[i]` function that means the maximum turbulent subarray ending on `array[i]` (must include element `array[i]`). Then we do one pass solution while calculating `DP[i]` based on the state info stored in XOR.\n\n## Algorithm\n- construct `DP[i]`\n- initialize `DP[0]` and `DP[1]`\n- iterate throught the `array[2:]`\n - case when `array[i]` = `array[i-1]`, it means the maximun turbulent subarray ending on `array[i]` is 1. Example: array = [2,1,3,3], DP[3] = 1.\n - case when XOR returns `True`, it means we increment by one\n - else, it means XOR returns `False`, it means we reset to 2.\n- return maximum in the `DP` array\n\n## Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$ to store previous maximum turbulent subarray length \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n # DP[i]: length of maximum turbulent subarray ending on arr[i]\n # bottomUp constant space Solution\n\n if len(arr) == 1: return 1\n # initialize DP, at first two elements\n DP = [None for _ in range(len(arr))]\n DP[0] = 1 \n if arr[0] == arr[1]:\n DP[1] = 1\n else:\n DP[1] = 2\n\n # bollean flag\n flag = arr[1] > arr[0]\n\n for i in range(2,len(arr)):\n # edge case when equal, we reset to 1\n if arr[i] == arr[i-1]:\n DP[i] = 1\n continue\n\n if flag ^ (arr[i] > arr[i-1]):\n # successfully update\n DP[i] = DP[i-1] + 1\n\n # update flag\n flag = arr[i] > arr[i-1]\n else:\n # update fails, rest to maximum turbulent subarray length ending on arr[i], which is 2.\n DP[i] = 2\n\n return max(DP)\n```\n\n# Approach 2: Bottom up, Constant space\n\nWe don\'t need to store the whole array and just need to track and update the maximum length of turbulent subarray for return. We do the following:\n\n```python\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n # bottom up, constant space\n # current_length: current maximum turbulent ending on\n\n if len(arr) == 1: return 1\n\n # initialize DP, at first two elements\n if arr[1] == arr[0]:\n current_length = 1\n else:\n current_length = 2\n\n maximum_length = current_length\n\n # bollean flag\n flag = arr[1] > arr[0]\n\n for i in range(2,len(arr)):\n # edge case when equal, we reset to 1\n if arr[i] == arr[i-1]:\n current_length = 1\n maximum_length = max(maximum_length,current_length)\n continue\n\n if flag ^ (arr[i] > arr[i-1]):\n # turbulent, so increment current length\n current_length += 1\n # update flag\n flag = arr[i] > arr[i-1]\n else:\n # rest current_length to 2, which only has two elements [0,1,2] --> [1,2] \n current_length = 2\n \n maximum_length = max(maximum_length,current_length)\n\n return maximum_length\n```\n\n# Summary\n\nThe problem is very similar to maximum subarry and this solution provides:\n- a solution framework similar to the editoral of the maximum subarray \n- the trick using `XOR` to represent state.\n
3
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
XOR with DP bottom up with optimization; DP Beginner friendly;
longest-turbulent-subarray
0
1
\n# Approach 1: Bottom up, Linear Space\n<!-- Describe your approach to solving the problem. -->\n\nMy intuition when i see turbuelnce subarry is that \n```\n> < > < > < > <\n```\nFor a simple array [a, b, c] to be a turbulent array, we could have\n```\nSituation1: a > b < c\nSituation2: a < b > c\n``` \nThe signs are fliping with every single time and it exisits a concise way to represent the state. If a, b ,c are distinct numbers (no duplicate) then the array `[a,b,c]` is turbulent is equivalent to the following statement\n```\n(a > b) XOR (b > c)\n```\n\nThen, Similar to bottom-up solution for maximum subarray, we just need to define a `DP[i]` function that means the maximum turbulent subarray ending on `array[i]` (must include element `array[i]`). Then we do one pass solution while calculating `DP[i]` based on the state info stored in XOR.\n\n## Algorithm\n- construct `DP[i]`\n- initialize `DP[0]` and `DP[1]`\n- iterate throught the `array[2:]`\n - case when `array[i]` = `array[i-1]`, it means the maximun turbulent subarray ending on `array[i]` is 1. Example: array = [2,1,3,3], DP[3] = 1.\n - case when XOR returns `True`, it means we increment by one\n - else, it means XOR returns `False`, it means we reset to 2.\n- return maximum in the `DP` array\n\n## Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$ to store previous maximum turbulent subarray length \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n # DP[i]: length of maximum turbulent subarray ending on arr[i]\n # bottomUp constant space Solution\n\n if len(arr) == 1: return 1\n # initialize DP, at first two elements\n DP = [None for _ in range(len(arr))]\n DP[0] = 1 \n if arr[0] == arr[1]:\n DP[1] = 1\n else:\n DP[1] = 2\n\n # bollean flag\n flag = arr[1] > arr[0]\n\n for i in range(2,len(arr)):\n # edge case when equal, we reset to 1\n if arr[i] == arr[i-1]:\n DP[i] = 1\n continue\n\n if flag ^ (arr[i] > arr[i-1]):\n # successfully update\n DP[i] = DP[i-1] + 1\n\n # update flag\n flag = arr[i] > arr[i-1]\n else:\n # update fails, rest to maximum turbulent subarray length ending on arr[i], which is 2.\n DP[i] = 2\n\n return max(DP)\n```\n\n# Approach 2: Bottom up, Constant space\n\nWe don\'t need to store the whole array and just need to track and update the maximum length of turbulent subarray for return. We do the following:\n\n```python\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n # bottom up, constant space\n # current_length: current maximum turbulent ending on\n\n if len(arr) == 1: return 1\n\n # initialize DP, at first two elements\n if arr[1] == arr[0]:\n current_length = 1\n else:\n current_length = 2\n\n maximum_length = current_length\n\n # bollean flag\n flag = arr[1] > arr[0]\n\n for i in range(2,len(arr)):\n # edge case when equal, we reset to 1\n if arr[i] == arr[i-1]:\n current_length = 1\n maximum_length = max(maximum_length,current_length)\n continue\n\n if flag ^ (arr[i] > arr[i-1]):\n # turbulent, so increment current length\n current_length += 1\n # update flag\n flag = arr[i] > arr[i-1]\n else:\n # rest current_length to 2, which only has two elements [0,1,2] --> [1,2] \n current_length = 2\n \n maximum_length = max(maximum_length,current_length)\n\n return maximum_length\n```\n\n# Summary\n\nThe problem is very similar to maximum subarry and this solution provides:\n- a solution framework similar to the editoral of the maximum subarray \n- the trick using `XOR` to represent state.\n
3
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Function Iterator
longest-turbulent-subarray
0
1
\n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n count = 1\n maxi = 1\n comp = cycle([gt, lt])\n for a, b in pairwise(arr):\n if next(comp)(a, b):\n count += 1\n else:\n maxi = max(maxi, count)\n count = 2 - (a == b)\n next(comp)\n \n return max(maxi, count)\n```
1
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
Function Iterator
longest-turbulent-subarray
0
1
\n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n count = 1\n maxi = 1\n comp = cycle([gt, lt])\n for a, b in pairwise(arr):\n if next(comp)(a, b):\n count += 1\n else:\n maxi = max(maxi, count)\n count = 2 - (a == b)\n next(comp)\n \n return max(maxi, count)\n```
1
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Python | Even easier explanation, O(n) time, O(1) space
longest-turbulent-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery non-empty subarray has a starting length of 1. If we \'flop\' a subarray, or we\'ve destroyed our streak, we should restart the count at 1. \n\nThere are only 2 states that we need to keep track of (exluding the result, of course): whether the next element should be ```up``` or ```down``` compared to its previous element. I used \'up\' and \'down\' because I thought of turbulent waves; they\'re analogous to \'greater\' and \'lesser.\'\n\nSuppose we\'re in a current subarray streak, and to continue this streak, the next element must be greater (```up```) than the current. So, we look at the ```up``` variable and increment it if the trend is continued. We then set ```down``` to ```up++``` and reset ```up``` to 1. At the next index, we\'ll be looking for a value that\'s ```down``` to continue our trend. \n\nWhy do we reset ```up``` to 1 right after learning ```n > n - 1``` in the previous example? If the following item breaks the streak (i.e, it\'s greater than the current element when it should have been less), then we have the previous 1-streak available to us (stored in ```up```), making the new streak 2. \n\nHere\'s a quick run-through of Example 1: ```[9,4,2,10,7,8,8,1,9]```\n```\nup = 1, down = 1, res = 1\nIndex 1: 4 < 9 (previous element)\nup = down + 1 = 1 + 1 = 2; down = 1; res = 2\n\nIndex 2: 2 < 4\nup = down + 1 = 1 + 1 = 2; down = 1; res = 2\n\nIndex 3: 10 > 2\ndown = up + 1 = 2 + 1 = 3; up = 1; res = 3\n\nIndex 4: 7 < 10\nup = down + 1 = 3 + 1 = 4; down = 1; res = 4\n\nIndex 5: 8 > 7\ndown = up + 1 = 4 + 1 = 5; up = 1; res = 5\n\nIndex 6: 8 == 8 (special case)\ndown = 1; up = 1; res = 5\n\nIndex 7: 1 < 8\nup = down + 1 = 1 + 1 = 2; down = 1; res = 5 (2 < 5)\n\nIndex 8: 9 > 1\ndown = up + 1 = 2 + 1 = 3; up = 1; res = 5 (3 < 5)\n\nAnswer: 5\n\n```\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou may have noticed that there are 3 cases: \n\n```\n1. current element > previous element\n2. current element < previous element\n3. current element == previous element\n```\n\nThese are represented by the conditionals in the answer. Item 3(current == previous) is the \'reset\' case, the special \'streak-breaking\' case. When the element is not strictly greater or lesser than the previous element, the streak ends. Because they\'re equal, both ```up``` and ```down``` streaks are erased and set to the base case.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n down = up = res = 1\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n down = up + 1\n up = 1\n elif arr[i] < arr[i - 1]:\n up = down + 1\n down = 1\n else:\n down = 1\n up = 1\n res = max(res, up, down)\n return res\n\n```
2
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
Python | Even easier explanation, O(n) time, O(1) space
longest-turbulent-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery non-empty subarray has a starting length of 1. If we \'flop\' a subarray, or we\'ve destroyed our streak, we should restart the count at 1. \n\nThere are only 2 states that we need to keep track of (exluding the result, of course): whether the next element should be ```up``` or ```down``` compared to its previous element. I used \'up\' and \'down\' because I thought of turbulent waves; they\'re analogous to \'greater\' and \'lesser.\'\n\nSuppose we\'re in a current subarray streak, and to continue this streak, the next element must be greater (```up```) than the current. So, we look at the ```up``` variable and increment it if the trend is continued. We then set ```down``` to ```up++``` and reset ```up``` to 1. At the next index, we\'ll be looking for a value that\'s ```down``` to continue our trend. \n\nWhy do we reset ```up``` to 1 right after learning ```n > n - 1``` in the previous example? If the following item breaks the streak (i.e, it\'s greater than the current element when it should have been less), then we have the previous 1-streak available to us (stored in ```up```), making the new streak 2. \n\nHere\'s a quick run-through of Example 1: ```[9,4,2,10,7,8,8,1,9]```\n```\nup = 1, down = 1, res = 1\nIndex 1: 4 < 9 (previous element)\nup = down + 1 = 1 + 1 = 2; down = 1; res = 2\n\nIndex 2: 2 < 4\nup = down + 1 = 1 + 1 = 2; down = 1; res = 2\n\nIndex 3: 10 > 2\ndown = up + 1 = 2 + 1 = 3; up = 1; res = 3\n\nIndex 4: 7 < 10\nup = down + 1 = 3 + 1 = 4; down = 1; res = 4\n\nIndex 5: 8 > 7\ndown = up + 1 = 4 + 1 = 5; up = 1; res = 5\n\nIndex 6: 8 == 8 (special case)\ndown = 1; up = 1; res = 5\n\nIndex 7: 1 < 8\nup = down + 1 = 1 + 1 = 2; down = 1; res = 5 (2 < 5)\n\nIndex 8: 9 > 1\ndown = up + 1 = 2 + 1 = 3; up = 1; res = 5 (3 < 5)\n\nAnswer: 5\n\n```\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou may have noticed that there are 3 cases: \n\n```\n1. current element > previous element\n2. current element < previous element\n3. current element == previous element\n```\n\nThese are represented by the conditionals in the answer. Item 3(current == previous) is the \'reset\' case, the special \'streak-breaking\' case. When the element is not strictly greater or lesser than the previous element, the streak ends. Because they\'re equal, both ```up``` and ```down``` streaks are erased and set to the base case.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n down = up = res = 1\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n down = up + 1\n up = 1\n elif arr[i] < arr[i - 1]:\n up = down + 1\n down = 1\n else:\n down = 1\n up = 1\n res = max(res, up, down)\n return res\n\n```
2
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
python3 sliding window
longest-turbulent-subarray
0
1
```\ndef maxTurbulenceSize(self, arr):\n n = len(arr)\n l, r = 0, 0\n ans = 1\n if n == 1:\n\t\t\treturn 1\n while r < n:\n while l < n - 1 and arr[l] == arr[l+1]: # to handle duplicates\n l += 1\n while r < n - 1 and (arr[r-1] > arr[r] < arr[r+1] or arr[r-1] < arr[r] > arr[r+1]):\n r += 1\n ans=max(ans, r - l + 1)\n l = r\n r += 1\n return ans\n\t\t\nTime Complexity - O(N)\nSpace Complexity - O(1)
9
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
python3 sliding window
longest-turbulent-subarray
0
1
```\ndef maxTurbulenceSize(self, arr):\n n = len(arr)\n l, r = 0, 0\n ans = 1\n if n == 1:\n\t\t\treturn 1\n while r < n:\n while l < n - 1 and arr[l] == arr[l+1]: # to handle duplicates\n l += 1\n while r < n - 1 and (arr[r-1] > arr[r] < arr[r+1] or arr[r-1] < arr[r] > arr[r+1]):\n r += 1\n ans=max(ans, r - l + 1)\n l = r\n r += 1\n return ans\n\t\t\nTime Complexity - O(N)\nSpace Complexity - O(1)
9
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Python T/C : 97% S/C: O(1)
longest-turbulent-subarray
0
1
```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n l, r ,output, n =0, 0, 0, len(arr)\n if n==1:\n return 1\n while r < n:\n while r<n-1 and (arr[r-1]>arr[r]<arr[r+1] or arr[r-1]<arr[r]>arr[r+1]):\n r+=1\n while l < r and arr[l]==arr[l+1]:\n l+=1\n output = max(output,r-l+1)\n \n l=r\n r+=1\n\t\treturn output\n\n```
2
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if: * For `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is odd, and * `arr[k] < arr[k + 1]` when `k` is even. * Or, for `i <= k < j`: * `arr[k] > arr[k + 1]` when `k` is even, and * `arr[k] < arr[k + 1]` when `k` is odd. **Example 1:** **Input:** arr = \[9,4,2,10,7,8,8,1,9\] **Output:** 5 **Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\] **Example 2:** **Input:** arr = \[4,8,12,16\] **Output:** 2 **Example 3:** **Input:** arr = \[100\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 4 * 104` * `0 <= arr[i] <= 109`
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
Python T/C : 97% S/C: O(1)
longest-turbulent-subarray
0
1
```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n l, r ,output, n =0, 0, 0, len(arr)\n if n==1:\n return 1\n while r < n:\n while r<n-1 and (arr[r-1]>arr[r]<arr[r+1] or arr[r-1]<arr[r]>arr[r+1]):\n r+=1\n while l < r and arr[l]==arr[l+1]:\n l+=1\n output = max(output,r-l+1)\n \n l=r\n r+=1\n\t\treturn output\n\n```
2
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Solution
distribute-coins-in-binary-tree
1
1
```C++ []\nclass Solution {\npublic:\n int balance(TreeNode* node,int &moves){\n if(node==NULL) return 0;\n int l=balance(node->left,moves),r=balance(node->right,moves);\n moves+=abs(l)+abs(r);\n return node->val+l+r-1;\n }\n int distributeCoins(TreeNode* root) {\n int ans=0;\n balance(root,ans);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distributeCoins(self, root: Optional[TreeNode]) -> int:\n def pot(root):\n if root == None:\n return ([0,0]) \n else:\n lb, lm = pot(root.left)\n rb, rm = pot(root.right)\n balance = lb + rb + root.val - 1\n move = lm + rm + abs(balance)\n return ([balance,move])\n return pot(root)[1] \n```\n\n```Java []\nclass Solution {\n int ans;\n public int distributeCoins(TreeNode root) {\n ans = 0;\n dfs(root);\n return ans;\n }\n public int dfs(TreeNode root){\n if (root == null) return 0;\n int coin = dfs(root.left) + dfs(root.right) + root.val - 1;\n ans += Math.abs(coin);\n return coin;\n }\n}\n```\n
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Solution
distribute-coins-in-binary-tree
1
1
```C++ []\nclass Solution {\npublic:\n int balance(TreeNode* node,int &moves){\n if(node==NULL) return 0;\n int l=balance(node->left,moves),r=balance(node->right,moves);\n moves+=abs(l)+abs(r);\n return node->val+l+r-1;\n }\n int distributeCoins(TreeNode* root) {\n int ans=0;\n balance(root,ans);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distributeCoins(self, root: Optional[TreeNode]) -> int:\n def pot(root):\n if root == None:\n return ([0,0]) \n else:\n lb, lm = pot(root.left)\n rb, rm = pot(root.right)\n balance = lb + rb + root.val - 1\n move = lm + rm + abs(balance)\n return ([balance,move])\n return pot(root)[1] \n```\n\n```Java []\nclass Solution {\n int ans;\n public int distributeCoins(TreeNode root) {\n ans = 0;\n dfs(root);\n return ans;\n }\n public int dfs(TreeNode root){\n if (root == null) return 0;\n int coin = dfs(root.left) + dfs(root.right) + root.val - 1;\n ans += Math.abs(coin);\n return coin;\n }\n}\n```\n
1
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Single post-order traversal. O(N)
distribute-coins-in-binary-tree
0
1
# Intuition\nSince to re-distribute coins evenly, we need to first check distribution of left and right children, the idea is to traverse the tree in DFS fashion like this: Left Child -> Right Child -> Parent Node aka post-order traversal\n\n# Approach\n1. If a child has 0 coins, move 1 coin through the parent to the child, update the parent value to account for the move (decrease by 1)\n2. If a child has 1 + k coins, move k coins through the parent, update the parent value to account for the move (increase by k)\n2.1 If a child has 1 coin, it means k == 0 and neither parent value nor total count are updated\n\n# Complexity\n- Time complexity:\n$$O(n)$$ since we need to traverse all nodes\n\n- Space complexity:\n$$O(\\log{n})$$ for storing the call stack, in case of a balanced tree. $$O(n)$$ if the tree is not balanced\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 distributeCoins(self, root: Optional[TreeNode]) -> int:\n cnt = 0\n def dfs(root):\n nonlocal cnt\n left = dfs(root.left) if root.left else 0\n right = dfs(root.right) if root.right else 0\n root.val += left + right\n cnt += abs(left) + abs(right)\n return root.val - 1\n \n dfs(root)\n\n return cnt \n```
2
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Single post-order traversal. O(N)
distribute-coins-in-binary-tree
0
1
# Intuition\nSince to re-distribute coins evenly, we need to first check distribution of left and right children, the idea is to traverse the tree in DFS fashion like this: Left Child -> Right Child -> Parent Node aka post-order traversal\n\n# Approach\n1. If a child has 0 coins, move 1 coin through the parent to the child, update the parent value to account for the move (decrease by 1)\n2. If a child has 1 + k coins, move k coins through the parent, update the parent value to account for the move (increase by k)\n2.1 If a child has 1 coin, it means k == 0 and neither parent value nor total count are updated\n\n# Complexity\n- Time complexity:\n$$O(n)$$ since we need to traverse all nodes\n\n- Space complexity:\n$$O(\\log{n})$$ for storing the call stack, in case of a balanced tree. $$O(n)$$ if the tree is not balanced\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 distributeCoins(self, root: Optional[TreeNode]) -> int:\n cnt = 0\n def dfs(root):\n nonlocal cnt\n left = dfs(root.left) if root.left else 0\n right = dfs(root.right) if root.right else 0\n root.val += left + right\n cnt += abs(left) + abs(right)\n return root.val - 1\n \n dfs(root)\n\n return cnt \n```
2
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Solution with Backtracking on Python3 / TypeScript
unique-paths-iii
0
1
# Intuition\nHere\'s the brief explanation of the problem:\n- there\'s a `grid`\n- the cells of this grid has it\'s own notation (`-1` for obstacle, `0` for free cell, `1` is robot **starting** point, `2` is **ending** point)\n- the goal is to find **HOW many** distinct ways are exist to visit **all cells** from **start to end**\n\nThere\'re some ways to get all possible combinations of visited cells.\nOne of them is **Backtracking approach**.\n\nConsider this example:\n```\ngrid = [\n [1,0,0], \n [0,0,2]\n]\n\n# The robot can move in four directions.\n# How many distinct ways are exist to visit all cells from 1 to 2?\n# (0, 0) => (1, 0) => (1, 1) => (0, 1) => (0, 2) => (1, 2)\n\n# This path is THE ONLY VALID one. \n# There\'re no suitable paths for the condition above.\n```\n\n# Approach\n1. define `seen` set to store a current path\n2. define `l` as the count of **cells** in grid\n3. define `isValid` function to check if the robot still inside a grid\n4. define `bt` function, that accepts `row` and `col` as a current cell\n5. check if `seen` has all of the possible `0` cells, and return `1`, since this path is a **valid one**\n6. let the robot move in four directions from `dirs`\n7. check if the robot inside of a grid and that it isn\'t trying to visit a cell, **that was visited before**\n8. add this cell `(x, y)` to the `seen` and continue **backtracking**\n9. return `result` as a count of possible ways from a particular `(x, y)`\n10. define `start` as a starting point and after iterating over grid, find this point\n11. don\'t forget to **decrement count of obstacles from valid cells** as `l -= 1`\n12. return `bt(start[0], start[1])`\n\n# Complexity\n- Time complexity: **O(4^(n*m)**, since we\'re going to visit all of the cells in grid **in four directions**\n\n- Space complexity: **O(n*m)**, to store `(row, col)`\n\n# Code in Python3\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n seen = set()\n n, m = len(grid), len(grid[0])\n l = n * m\n dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n\n def isValid(i, j):\n return 0 <= i < n and 0 <= j < m\n\n def bt(row, col):\n if len(seen) == l and grid[row][col] == 2:\n return 1\n\n result = 0\n\n for dx, dy in dirs:\n x, y = row + dx, col + dy\n key = (x, y)\n\n if isValid(x, y) and key not in seen and grid[row][col] != -1:\n seen.add(key)\n result += bt(x, y)\n seen.remove(key)\n\n return result\n\n start = None\n\n for i in range(n):\n for j in range(m):\n match grid[i][j]:\n case 1:\n start = [i, j]\n seen.add((i, j))\n\n case -1:\n l -=1\n\n return bt(start[0], start[1])\n```\n# Code in TypeScript\n```\nfunction uniquePathsIII(grid: number[][]): number {\n const seen = new Set();\n const [n, m] = [grid.length, grid[0].length];\n let l = n * m;\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];\n\n const keify = (i: number, j: number) => `${i}-${j}`;\n\n const isValid = (i: number, j: number) => 0 <= i && i < n && 0 <= j && j < m;\n\n const bt = (row: number, col: number) => {\n if (seen.size === l && grid[row][col] === 2) return 1\n\n let result = 0\n\n for (const [dx, dy] of dirs) {\n const [x, y] = [row + dx, col + dy];\n const key = keify(x, y);\n\n if (isValid(x, y) && !seen.has(key) && grid[row][col] !== -1) {\n seen.add(key);\n result += bt(x, y);\n seen.delete(key);\n }\n }\n\n return result\n };\n\n let start = [];\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n switch (grid[i][j]) {\n case 1: {\n start = [i, j];\n seen.add(keify(i, j));\n break;\n }\n\n case -1: {\n l--;\n break\n }\n }\n }\n }\n\n return bt(start[0], start[1]);\n}\n```
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Solution with Backtracking on Python3 / TypeScript
unique-paths-iii
0
1
# Intuition\nHere\'s the brief explanation of the problem:\n- there\'s a `grid`\n- the cells of this grid has it\'s own notation (`-1` for obstacle, `0` for free cell, `1` is robot **starting** point, `2` is **ending** point)\n- the goal is to find **HOW many** distinct ways are exist to visit **all cells** from **start to end**\n\nThere\'re some ways to get all possible combinations of visited cells.\nOne of them is **Backtracking approach**.\n\nConsider this example:\n```\ngrid = [\n [1,0,0], \n [0,0,2]\n]\n\n# The robot can move in four directions.\n# How many distinct ways are exist to visit all cells from 1 to 2?\n# (0, 0) => (1, 0) => (1, 1) => (0, 1) => (0, 2) => (1, 2)\n\n# This path is THE ONLY VALID one. \n# There\'re no suitable paths for the condition above.\n```\n\n# Approach\n1. define `seen` set to store a current path\n2. define `l` as the count of **cells** in grid\n3. define `isValid` function to check if the robot still inside a grid\n4. define `bt` function, that accepts `row` and `col` as a current cell\n5. check if `seen` has all of the possible `0` cells, and return `1`, since this path is a **valid one**\n6. let the robot move in four directions from `dirs`\n7. check if the robot inside of a grid and that it isn\'t trying to visit a cell, **that was visited before**\n8. add this cell `(x, y)` to the `seen` and continue **backtracking**\n9. return `result` as a count of possible ways from a particular `(x, y)`\n10. define `start` as a starting point and after iterating over grid, find this point\n11. don\'t forget to **decrement count of obstacles from valid cells** as `l -= 1`\n12. return `bt(start[0], start[1])`\n\n# Complexity\n- Time complexity: **O(4^(n*m)**, since we\'re going to visit all of the cells in grid **in four directions**\n\n- Space complexity: **O(n*m)**, to store `(row, col)`\n\n# Code in Python3\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n seen = set()\n n, m = len(grid), len(grid[0])\n l = n * m\n dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n\n def isValid(i, j):\n return 0 <= i < n and 0 <= j < m\n\n def bt(row, col):\n if len(seen) == l and grid[row][col] == 2:\n return 1\n\n result = 0\n\n for dx, dy in dirs:\n x, y = row + dx, col + dy\n key = (x, y)\n\n if isValid(x, y) and key not in seen and grid[row][col] != -1:\n seen.add(key)\n result += bt(x, y)\n seen.remove(key)\n\n return result\n\n start = None\n\n for i in range(n):\n for j in range(m):\n match grid[i][j]:\n case 1:\n start = [i, j]\n seen.add((i, j))\n\n case -1:\n l -=1\n\n return bt(start[0], start[1])\n```\n# Code in TypeScript\n```\nfunction uniquePathsIII(grid: number[][]): number {\n const seen = new Set();\n const [n, m] = [grid.length, grid[0].length];\n let l = n * m;\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];\n\n const keify = (i: number, j: number) => `${i}-${j}`;\n\n const isValid = (i: number, j: number) => 0 <= i && i < n && 0 <= j && j < m;\n\n const bt = (row: number, col: number) => {\n if (seen.size === l && grid[row][col] === 2) return 1\n\n let result = 0\n\n for (const [dx, dy] of dirs) {\n const [x, y] = [row + dx, col + dy];\n const key = keify(x, y);\n\n if (isValid(x, y) && !seen.has(key) && grid[row][col] !== -1) {\n seen.add(key);\n result += bt(x, y);\n seen.delete(key);\n }\n }\n\n return result\n };\n\n let start = [];\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n switch (grid[i][j]) {\n case 1: {\n start = [i, j];\n seen.add(keify(i, j));\n break;\n }\n\n case -1: {\n l--;\n break\n }\n }\n }\n }\n\n return bt(start[0], start[1]);\n}\n```
1
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
EASY PYTHON SOLUTION
unique-paths-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDFS TRAVERSAL\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,i,j,m,n,grid,lst,ei,ej,ct,cnt):\n lst[i][j]=1\n ct+=1\n # print(ct,i,j)\n # print(lst)\n if i==ei and j==ej:\n if ct==cnt:\n # print("ok",ct,cnt)\n # print(lst)\n return 1\n return 0\n row=[-1,1,0,0]\n col=[0,0,-1,1]\n sm=0\n for r in range(4):\n if i+row[r]>=0 and i+row[r]<m and j+col[r]>=0 and j+col[r]<n and grid[i+row[r]][j+col[r]]!=-1 and lst[i+row[r]][j+col[r]]==0:\n sm+=self.dfs(i+row[r],j+col[r],m,n,grid,lst,ei,ej,ct,cnt)\n lst[i+row[r]][j+col[r]]=0\n return sm\n\n\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n hr=0\n m=len(grid)\n n=len(grid[0])\n cnt=0\n for i in range(m):\n for j in range(n):\n if grid[i][j]==-1:\n hr+=1\n elif grid[i][j]==1:\n st=(i,j)\n cnt+=1\n elif grid[i][j]==2:\n end=(i,j)\n cnt+=1\n else:\n cnt+=1\n lst=[[0]*n for _ in range(m)]\n return self.dfs(st[0],st[1],m,n,grid,lst,end[0],end[1],0,cnt)\n```
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
EASY PYTHON SOLUTION
unique-paths-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDFS TRAVERSAL\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,i,j,m,n,grid,lst,ei,ej,ct,cnt):\n lst[i][j]=1\n ct+=1\n # print(ct,i,j)\n # print(lst)\n if i==ei and j==ej:\n if ct==cnt:\n # print("ok",ct,cnt)\n # print(lst)\n return 1\n return 0\n row=[-1,1,0,0]\n col=[0,0,-1,1]\n sm=0\n for r in range(4):\n if i+row[r]>=0 and i+row[r]<m and j+col[r]>=0 and j+col[r]<n and grid[i+row[r]][j+col[r]]!=-1 and lst[i+row[r]][j+col[r]]==0:\n sm+=self.dfs(i+row[r],j+col[r],m,n,grid,lst,ei,ej,ct,cnt)\n lst[i+row[r]][j+col[r]]=0\n return sm\n\n\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n hr=0\n m=len(grid)\n n=len(grid[0])\n cnt=0\n for i in range(m):\n for j in range(n):\n if grid[i][j]==-1:\n hr+=1\n elif grid[i][j]==1:\n st=(i,j)\n cnt+=1\n elif grid[i][j]==2:\n end=(i,j)\n cnt+=1\n else:\n cnt+=1\n lst=[[0]*n for _ in range(m)]\n return self.dfs(st[0],st[1],m,n,grid,lst,end[0],end[1],0,cnt)\n```
1
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Python Solution Explained ✅ | 93.79%
unique-paths-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing DFS backtracking is the the obvious solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe first find the `start` squar and `end` square and `path` length which contains all squares except the blocked.\nthen we start the dfs from the start node to wards the end node.\nAnd we add the node to a viseted set. Then the next nodes are `up`,`down`,`left`,`right`.our base cases will be when we reach the end and the `curpath` is equal to `path` we return `1` else `0`.\nFinaly we count all valid paths and return them.\n# Complexity\n- Time complexity:$$O(4^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ROW, COL = len(grid), len(grid[0])\n start,end = () ,()\n path = 2\n # find start square , end square and squares to walk over\n for i in range(ROW):\n for j in range(COL):\n if grid[i][j] == 1:\n start = (i,j)\n elif grid[i][j] == 2:\n end = (i,j)\n elif grid[i][j] == 0:\n path += 1\n\n visited= set()\n def dfs(start,end,curpath):\n # check if square is visited or obstacle\n if start in visited or grid[start[0]][start[1]] == -1:\n return 0\n # check if destination is reached and all nodes are visited \n if start == end:\n if curpath == path:\n return 1\n else:\n return 0\n \n count = 0\n # add square to visited\n visited.add(start)\n #4-directional walks\n for x,y in [(0,1), (0,-1), (-1,0), (1,0)]:\n if 0<=(x + start[0])<ROW and 0<=(y + start[1])<COL:\n # increment count\n count += dfs((x + start[0],y + start[1]), end,curpath+1) \n # remove square from visited\n visited.remove(start)\n return count\n \n return dfs(start,end,1)\n\n```
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Python Solution Explained ✅ | 93.79%
unique-paths-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing DFS backtracking is the the obvious solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe first find the `start` squar and `end` square and `path` length which contains all squares except the blocked.\nthen we start the dfs from the start node to wards the end node.\nAnd we add the node to a viseted set. Then the next nodes are `up`,`down`,`left`,`right`.our base cases will be when we reach the end and the `curpath` is equal to `path` we return `1` else `0`.\nFinaly we count all valid paths and return them.\n# Complexity\n- Time complexity:$$O(4^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ROW, COL = len(grid), len(grid[0])\n start,end = () ,()\n path = 2\n # find start square , end square and squares to walk over\n for i in range(ROW):\n for j in range(COL):\n if grid[i][j] == 1:\n start = (i,j)\n elif grid[i][j] == 2:\n end = (i,j)\n elif grid[i][j] == 0:\n path += 1\n\n visited= set()\n def dfs(start,end,curpath):\n # check if square is visited or obstacle\n if start in visited or grid[start[0]][start[1]] == -1:\n return 0\n # check if destination is reached and all nodes are visited \n if start == end:\n if curpath == path:\n return 1\n else:\n return 0\n \n count = 0\n # add square to visited\n visited.add(start)\n #4-directional walks\n for x,y in [(0,1), (0,-1), (-1,0), (1,0)]:\n if 0<=(x + start[0])<ROW and 0<=(y + start[1])<COL:\n # increment count\n count += dfs((x + start[0],y + start[1]), end,curpath+1) \n # remove square from visited\n visited.remove(start)\n return count\n \n return dfs(start,end,1)\n\n```
1
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Simple Python - DFS solution
unique-paths-iii
0
1
# Intuition\nStart the solution and track from the starting position where the grid found 1 and calculate all the non obstacle path. This can be achieved by using DFS.\n\n# Approach\nFind the start, end path and the count of non-obstacles and find the paths all the directions to reach the end and it must visit all the non-obstacles then increment the path and return it.\n\n\n# Code\n```\nclass Solution(object):\n def uniquePathsIII(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n self.depth = 0\n\n def dfs(row, col, non_obstacles):\n\n if grid[row][col] == 2 and non_obstacles == 1:\n self.depth += 1\n return\n\n temp = grid[row][col]\n grid[row][col] = -1\n non_obstacles -= 1\n\n for index1, index2 in directions:\n\n next_row = index1 + row\n next_col = index2 + col\n\n if next_row in range(len(grid)) and next_col in range(len(grid[0])) and grid[next_row][next_col] != -1:\n \n dfs(next_row, next_col, non_obstacles)\n\n grid[row][col] = temp\n\n return self.depth\n\n \n non_obstacles = 0\n for row in range(len(grid)):\n\n for col in range(len(grid[0])):\n\n if grid[row][col] == 1:\n result = [row, col]\n if grid[row][col] >= 0:\n non_obstacles += 1\n\n return dfs(result[0], result[1], non_obstacles)\n\n\n\n\n\n```
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Simple Python - DFS solution
unique-paths-iii
0
1
# Intuition\nStart the solution and track from the starting position where the grid found 1 and calculate all the non obstacle path. This can be achieved by using DFS.\n\n# Approach\nFind the start, end path and the count of non-obstacles and find the paths all the directions to reach the end and it must visit all the non-obstacles then increment the path and return it.\n\n\n# Code\n```\nclass Solution(object):\n def uniquePathsIII(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n self.depth = 0\n\n def dfs(row, col, non_obstacles):\n\n if grid[row][col] == 2 and non_obstacles == 1:\n self.depth += 1\n return\n\n temp = grid[row][col]\n grid[row][col] = -1\n non_obstacles -= 1\n\n for index1, index2 in directions:\n\n next_row = index1 + row\n next_col = index2 + col\n\n if next_row in range(len(grid)) and next_col in range(len(grid[0])) and grid[next_row][next_col] != -1:\n \n dfs(next_row, next_col, non_obstacles)\n\n grid[row][col] = temp\n\n return self.depth\n\n \n non_obstacles = 0\n for row in range(len(grid)):\n\n for col in range(len(grid[0])):\n\n if grid[row][col] == 1:\n result = [row, col]\n if grid[row][col] >= 0:\n non_obstacles += 1\n\n return dfs(result[0], result[1], non_obstacles)\n\n\n\n\n\n```
1
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Beats 92% | CodeDominar Solution
unique-paths-iii
0
1
# Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n sr, sc, zeros = [(r, c, sum(1 for row in grid for element in row if element == 0)) for r in range(len(grid)) for c in range(len(grid[0])) if grid[r][c] == 1][0]\n def dfs(r,c,zeros):\n if r not in range(rows) or c not in range(cols) or grid[r][c] == -1:\n return 0\n if grid[r][c] == 2:\n return 1 if zeros == -1 else 0\n grid[r][c] = -1\n zeros-=1\n ans = (dfs(r+1,c,zeros) + dfs(r,c+1,zeros) + dfs(r-1,c,zeros) + dfs(r,c-1,zeros))\n grid[r][c] = 0\n zeros+=1\n return ans\n return dfs(sr,sc,zeros)\n```
2
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Beats 92% | CodeDominar Solution
unique-paths-iii
0
1
# Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n sr, sc, zeros = [(r, c, sum(1 for row in grid for element in row if element == 0)) for r in range(len(grid)) for c in range(len(grid[0])) if grid[r][c] == 1][0]\n def dfs(r,c,zeros):\n if r not in range(rows) or c not in range(cols) or grid[r][c] == -1:\n return 0\n if grid[r][c] == 2:\n return 1 if zeros == -1 else 0\n grid[r][c] = -1\n zeros-=1\n ans = (dfs(r+1,c,zeros) + dfs(r,c+1,zeros) + dfs(r-1,c,zeros) + dfs(r,c-1,zeros))\n grid[r][c] = 0\n zeros+=1\n return ans\n return dfs(sr,sc,zeros)\n```
2
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Two dictionaries
time-based-key-value-store
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:0(logn) per get operation -->0(klogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\nclass TimeMap:\n def __init__(self):\n self.dt = {}\n self.keys_ts = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.dt[(key,timestamp)] = value\n self.keys_ts[key].append(timestamp)\n \n def get(self, key: str, timestamp: int) -> str:\n ats = None\n s_l = self.keys_ts[key]\n if not s_l or timestamp < s_l[0]:\n return \'\'\n l,r = 0,len(s_l)-1\n while r>=l:\n m = (l+r)//2\n if s_l[m]>timestamp:\n r = m-1\n elif s_l[m]<timestamp:\n l = m+1\n else:\n ats = s_l[m]\n break \n if not ats:\n ats = s_l[l-1]\n return self.dt[(key,ats)] \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n```
1
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the `TimeMap` class: * `TimeMap()` Initializes the object of the data structure. * `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`. * `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`. **Example 1:** **Input** \[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\] \[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\] **Output** \[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\] **Explanation** TimeMap timeMap = new TimeMap(); timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1. timeMap.get( "foo ", 1); // return "bar " timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ". timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4. timeMap.get( "foo ", 4); // return "bar2 " timeMap.get( "foo ", 5); // return "bar2 " **Constraints:** * `1 <= key.length, value.length <= 100` * `key` and `value` consist of lowercase English letters and digits. * `1 <= timestamp <= 107` * All the timestamps `timestamp` of `set` are strictly increasing. * At most `2 * 105` calls will be made to `set` and `get`.
null
Two dictionaries
time-based-key-value-store
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:0(logn) per get operation -->0(klogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\nclass TimeMap:\n def __init__(self):\n self.dt = {}\n self.keys_ts = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.dt[(key,timestamp)] = value\n self.keys_ts[key].append(timestamp)\n \n def get(self, key: str, timestamp: int) -> str:\n ats = None\n s_l = self.keys_ts[key]\n if not s_l or timestamp < s_l[0]:\n return \'\'\n l,r = 0,len(s_l)-1\n while r>=l:\n m = (l+r)//2\n if s_l[m]>timestamp:\n r = m-1\n elif s_l[m]<timestamp:\n l = m+1\n else:\n ats = s_l[m]\n break \n if not ats:\n ats = s_l[l-1]\n return self.dt[(key,ats)] \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)\n```
1
Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise. A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. **Example 1:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB " **Output:** \[true,false,true,true,false\] **Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ". "FootBall " can be generated like this "F " + "oot " + "B " + "all ". "FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ". **Example 2:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa " **Output:** \[true,false,true,false,false\] **Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ". "FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ". **Example 3:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT " **Output:** \[false,true,false,false,false\] **Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ". **Constraints:** * `1 <= pattern.length, queries.length <= 100` * `1 <= queries[i].length <= 100` * `queries[i]` and `pattern` consist of English letters.
null
Solution
triples-with-bitwise-and-equal-to-zero
1
1
```C++ []\nclass Solution {\npublic:\n int countTriplets(vector<int>& nums) {\n int table[1<<16] = {0};\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n ++table[nums[i]];\n for (int j = i+1; j < n; ++j) {\n table[nums[i]&nums[j]]+= 2;\n }\n }\n int res = 0;\n for (int i: nums) {\n i = i ^ 0xffff;\n for (int j = i; j; j = (j-1)&i) {\n res += table[j];\n }\n res += table[0];\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def countTriplets(self, A: \'List[int]\') -> \'int\':\n\t\n tmp = []\n maxlen = 0\n for a in A:\n tmp.append(bin(a)[2:])\n maxlen = max(maxlen, len(tmp[-1]))\n pool = []\n for s in tmp:\n extra = maxlen - len(s)\n pool.append(\'0\'*extra + s)\n \n row, col = len(pool), len(pool[0])\n one = collections.defaultdict(set)\n for j in range(col):\n for i in range(row):\n if pool[i][j] == \'1\':\n one[j].add(i)\n \n Venn = collections.defaultdict(list)\n cnt = 0\n for j in range(col):\n if len(one[j]) != 0:\n cnt += (len(one[j]))**3\n for i in range(j, 0, -1):\n for prv in Venn[i]:\n intersec = prv & one[j]\n if len(intersec) != 0:\n cnt += ((-1)**i)*(len(intersec))**3\n Venn[i+1].append(intersec)\n Venn[1].append(one[j])\n \n return row**3 - cnt\n```\n\n```Java []\nclass Solution {\n public int countTriplets(int[] nums) {\n int max = 0;\n for (int num : nums) {\n max = Math.max(max, num);\n }\n int N = 1;\n while (N <= max) {\n N <<= 1;\n }\n int[] cnt = new int[N];\n for (int x : nums) {\n for (int y : nums) {\n cnt[x & y]++;\n }\n }\n int ans = 0;\n for (int num : nums) {\n int subset = num ^ (N - 1);\n ans += cnt[0];\n for (int i = subset; i > 0; i = subset & (i - 1)) {\n ans += cnt[i];\n }\n }\n return ans;\n }\n}\n```\n
1
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 12 **Explanation:** We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 **Example 2:** **Input:** nums = \[0,0,0\] **Output:** 27 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Solution
triples-with-bitwise-and-equal-to-zero
1
1
```C++ []\nclass Solution {\npublic:\n int countTriplets(vector<int>& nums) {\n int table[1<<16] = {0};\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n ++table[nums[i]];\n for (int j = i+1; j < n; ++j) {\n table[nums[i]&nums[j]]+= 2;\n }\n }\n int res = 0;\n for (int i: nums) {\n i = i ^ 0xffff;\n for (int j = i; j; j = (j-1)&i) {\n res += table[j];\n }\n res += table[0];\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def countTriplets(self, A: \'List[int]\') -> \'int\':\n\t\n tmp = []\n maxlen = 0\n for a in A:\n tmp.append(bin(a)[2:])\n maxlen = max(maxlen, len(tmp[-1]))\n pool = []\n for s in tmp:\n extra = maxlen - len(s)\n pool.append(\'0\'*extra + s)\n \n row, col = len(pool), len(pool[0])\n one = collections.defaultdict(set)\n for j in range(col):\n for i in range(row):\n if pool[i][j] == \'1\':\n one[j].add(i)\n \n Venn = collections.defaultdict(list)\n cnt = 0\n for j in range(col):\n if len(one[j]) != 0:\n cnt += (len(one[j]))**3\n for i in range(j, 0, -1):\n for prv in Venn[i]:\n intersec = prv & one[j]\n if len(intersec) != 0:\n cnt += ((-1)**i)*(len(intersec))**3\n Venn[i+1].append(intersec)\n Venn[1].append(one[j])\n \n return row**3 - cnt\n```\n\n```Java []\nclass Solution {\n public int countTriplets(int[] nums) {\n int max = 0;\n for (int num : nums) {\n max = Math.max(max, num);\n }\n int N = 1;\n while (N <= max) {\n N <<= 1;\n }\n int[] cnt = new int[N];\n for (int x : nums) {\n for (int y : nums) {\n cnt[x & y]++;\n }\n }\n int ans = 0;\n for (int num : nums) {\n int subset = num ^ (N - 1);\n ans += cnt[0];\n for (int i = subset; i > 0; i = subset & (i - 1)) {\n ans += cnt[i];\n }\n }\n return ans;\n }\n}\n```\n
1
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`. We can cut these clips into segments freely. * For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`. Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`. **Example 1:** **Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10 **Output:** 3 **Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\]. Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\]. **Example 2:** **Input:** clips = \[\[0,1\],\[1,2\]\], time = 5 **Output:** -1 **Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\]. **Example 3:** **Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9 **Output:** 3 **Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\]. **Constraints:** * `1 <= clips.length <= 100` * `0 <= starti <= endi <= 100` * `1 <= time <= 100` 0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.)
null