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 |
---|---|---|---|---|---|---|---|
Easiest one line solution with explanation || Python | transpose-matrix | 0 | 1 | \n\nIn this code, the `zip(*matrix)` function is used to transpose the matrix. The `*` operator is used for unpacking the rows of the matrix, and `zip` combines the elements with the same index into tuples, effectively transposing the rows and columns. Finally, a list comprehension is used to convert the transposed tuples back into lists.\n\n# Code\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n transposed_matrix=[list(row) for row in zip(*matrix)] \n return transposed_matrix\n \n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 1 | Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109` | null |
Easiest one line solution with explanation || Python | transpose-matrix | 0 | 1 | \n\nIn this code, the `zip(*matrix)` function is used to transpose the matrix. The `*` operator is used for unpacking the rows of the matrix, and `zip` combines the elements with the same index into tuples, effectively transposing the rows and columns. Finally, a list comprehension is used to convert the transposed tuples back into lists.\n\n# Code\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n transposed_matrix=[list(row) for row in zip(*matrix)] \n return transposed_matrix\n \n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 1 | Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** arr = \[0\]
**Output:** 1
**Explanation:** There is only one possible result: 0.
**Example 2:**
**Input:** arr = \[1,1,2\]
**Output:** 3
**Explanation:** The possible subarrays are \[1\], \[1\], \[2\], \[1, 1\], \[1, 2\], \[1, 1, 2\].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
**Example 3:**
**Input:** arr = \[1,2,4\]
**Output:** 6
**Explanation:** The possible results are 1, 2, 3, 4, 6, and 7.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `0 <= arr[i] <= 109` | We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa! |
🔥 Easy solution | JAVA | Python 3 🔥| | transpose-matrix | 1 | 1 | # Intuition\nTranspose Matrix\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Input Validation:\n\n 1. It assumes a non-empty input matrix with at least one row and one column.\n 1. It calculates the number of rows (rows) and columns (cols) in the input matrix.\n1. Creating the Transposed Matrix:\n\n 1. It initializes a new 2D array called transposed with dimensions cols x rows. This is done because the transpose of an m x n matrix results in an n x m matrix.\n1. Transposing the Matrix:\n\n 1. It uses nested loops to iterate through the original matrix (matrix) and assigns the elements to the transposed matrix (transposed) by swapping rows and columns.\n 1. The outer loop iterates over the rows of the original matrix, while the inner loop iterates over the columns.\n 1. For each element in the original matrix (matrix[i][j]), it assigns this element to the transposed matrix at the position transposed[j][i]. The row index becomes the column index in the transposed matrix, and vice versa.\n1. Returning the Transposed Matrix:\n\n 1. Finally, it returns the transposed matrix (transposed).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n\n int[][] transposed = new int[cols][rows];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n transposed[j][i] = matrix[i][j];\n }\n }\n\n return transposed;\n }}\n```\n```python []\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n return zip(*matrix)\n```\n\n | 1 | Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109` | null |
🔥 Easy solution | JAVA | Python 3 🔥| | transpose-matrix | 1 | 1 | # Intuition\nTranspose Matrix\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Input Validation:\n\n 1. It assumes a non-empty input matrix with at least one row and one column.\n 1. It calculates the number of rows (rows) and columns (cols) in the input matrix.\n1. Creating the Transposed Matrix:\n\n 1. It initializes a new 2D array called transposed with dimensions cols x rows. This is done because the transpose of an m x n matrix results in an n x m matrix.\n1. Transposing the Matrix:\n\n 1. It uses nested loops to iterate through the original matrix (matrix) and assigns the elements to the transposed matrix (transposed) by swapping rows and columns.\n 1. The outer loop iterates over the rows of the original matrix, while the inner loop iterates over the columns.\n 1. For each element in the original matrix (matrix[i][j]), it assigns this element to the transposed matrix at the position transposed[j][i]. The row index becomes the column index in the transposed matrix, and vice versa.\n1. Returning the Transposed Matrix:\n\n 1. Finally, it returns the transposed matrix (transposed).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n\n int[][] transposed = new int[cols][rows];\n\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n transposed[j][i] = matrix[i][j];\n }\n }\n\n return transposed;\n }}\n```\n```python []\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n return zip(*matrix)\n```\n\n | 1 | Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** arr = \[0\]
**Output:** 1
**Explanation:** There is only one possible result: 0.
**Example 2:**
**Input:** arr = \[1,1,2\]
**Output:** 3
**Explanation:** The possible subarrays are \[1\], \[1\], \[2\], \[1, 1\], \[1, 2\], \[1, 1, 2\].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
**Example 3:**
**Input:** arr = \[1,2,4\]
**Output:** 6
**Explanation:** The possible results are 1, 2, 3, 4, 6, and 7.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `0 <= arr[i] <= 109` | We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa! |
simple and advanced solution using java and python easy to understand with explanation | transpose-matrix | 1 | 1 | # Intuition\nThe goal is to transpose the given matrix, swapping rows and columns. The idea is to iterate through each element of the original matrix and place it in the corresponding position in the transposed matrix.\n\n# Approach\nInitialize an empty list transposed_matrix to store the transposed elements.\nIterate through the columns of the original matrix using an outer loop.\nFor each column, initialize an empty list row to represent a row in the transposed matrix.\nIterate through the rows of the original matrix using an inner loop.\nAppend the transposed element (matrix[j][i]) to the current row (row).\nAfter the inner loop completes, append the current row to the transposed_matrix.\nAfter the outer loop completes, return the transposed_matrix.\n\n\n# Complexity\n```\nTime complexity: O(m * n)\nSpace complexity: O(m * n) \n```\n# Code\n```python []\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n transposed_matrix = []\n\n for i in range(len(matrix[0])):\n row = []\n for j in range(len(matrix)):\n row.append(matrix[j][i])\n transposed_matrix.append(row)\n\n return transposed_matrix\n```\n```java []\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n int[][] transposedMatrix = new int[n][m];\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n transposedMatrix[i][j] = matrix[j][i];\n }\n }\n\n return transposedMatrix;\n }\n}\n```\n\n\n\n# Advanced Code\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]\n``` | 1 | Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109` | null |
simple and advanced solution using java and python easy to understand with explanation | transpose-matrix | 1 | 1 | # Intuition\nThe goal is to transpose the given matrix, swapping rows and columns. The idea is to iterate through each element of the original matrix and place it in the corresponding position in the transposed matrix.\n\n# Approach\nInitialize an empty list transposed_matrix to store the transposed elements.\nIterate through the columns of the original matrix using an outer loop.\nFor each column, initialize an empty list row to represent a row in the transposed matrix.\nIterate through the rows of the original matrix using an inner loop.\nAppend the transposed element (matrix[j][i]) to the current row (row).\nAfter the inner loop completes, append the current row to the transposed_matrix.\nAfter the outer loop completes, return the transposed_matrix.\n\n\n# Complexity\n```\nTime complexity: O(m * n)\nSpace complexity: O(m * n) \n```\n# Code\n```python []\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n transposed_matrix = []\n\n for i in range(len(matrix[0])):\n row = []\n for j in range(len(matrix)):\n row.append(matrix[j][i])\n transposed_matrix.append(row)\n\n return transposed_matrix\n```\n```java []\nclass Solution {\n public int[][] transpose(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n\n int[][] transposedMatrix = new int[n][m];\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n transposedMatrix[i][j] = matrix[j][i];\n }\n }\n\n return transposedMatrix;\n }\n}\n```\n\n\n\n# Advanced Code\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]\n``` | 1 | Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A **subarray** is a contiguous non-empty sequence of elements within an array.
**Example 1:**
**Input:** arr = \[0\]
**Output:** 1
**Explanation:** There is only one possible result: 0.
**Example 2:**
**Input:** arr = \[1,1,2\]
**Output:** 3
**Explanation:** The possible subarrays are \[1\], \[1\], \[2\], \[1, 1\], \[1, 2\], \[1, 1, 2\].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
**Example 3:**
**Input:** arr = \[1,2,4\]
**Output:** 6
**Explanation:** The possible results are 1, 2, 3, 4, 6, and 7.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `0 <= arr[i] <= 109` | We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa! |
Solution | binary-gap | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int binaryGap(int N) {\n int result = 0;\n int last = -1;\n for (int i = 0; i < 32; ++i) {\n if ((N >> i) & 1) {\n if (last != -1) {\n result = max(result, i - last);\n }\n last = i;\n }\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def binaryGap(self, n: int) -> int:\n s = f\'{n:b}\'\n result = 0\n for i in range(len(s)):\n if s[i] == \'0\':\n continue\n for j in range(i + 1, len(s)):\n if s[j] == \'0\':\n continue\n result = max(result, j - i)\n break\n return result\n```\n\n```Java []\nclass Solution {\n public int binaryGap(int n) {\n int prev=-1;\n int tc=0;\n int mx=-1,ct=0;\n while(n>0){\n int r= n&1;\n if(r==1 ){\n ++tc;\n prev=0;\n mx=Math.max(ct,mx);\n ct=0;\n \n }else {\n if(prev!=-1){\n ct++;\n }\n }\n n=n>>1;\n }\n if(tc<=1){\n return 0;\n }\n return mx+1;\n }\n}\n```\n | 1 | Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109` | null |
Solution | binary-gap | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int binaryGap(int N) {\n int result = 0;\n int last = -1;\n for (int i = 0; i < 32; ++i) {\n if ((N >> i) & 1) {\n if (last != -1) {\n result = max(result, i - last);\n }\n last = i;\n }\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def binaryGap(self, n: int) -> int:\n s = f\'{n:b}\'\n result = 0\n for i in range(len(s)):\n if s[i] == \'0\':\n continue\n for j in range(i + 1, len(s)):\n if s[j] == \'0\':\n continue\n result = max(result, j - i)\n break\n return result\n```\n\n```Java []\nclass Solution {\n public int binaryGap(int n) {\n int prev=-1;\n int tc=0;\n int mx=-1,ct=0;\n while(n>0){\n int r= n&1;\n if(r==1 ){\n ++tc;\n prev=0;\n mx=Math.max(ct,mx);\n ct=0;\n \n }else {\n if(prev!=-1){\n ct++;\n }\n }\n n=n>>1;\n }\n if(tc<=1){\n return 0;\n }\n return mx+1;\n }\n}\n```\n | 1 | You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters. | null |
Python Simple Solution II O(n) || One Pass | binary-gap | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n binary = bin(n)\n binary= binary[2:]\n found = False\n max_count =0\n for i in range(len(binary)):\n if(binary[i]==\'1\' and found ==False):\n start= i\n found = True\n elif(binary[i]==\'1\' and found==True):\n count = i- start\n start= i\n if(count>max_count):\n max_count= count\n return max_count\n\n \n``` | 1 | Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109` | null |
Python Simple Solution II O(n) || One Pass | binary-gap | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n binary = bin(n)\n binary= binary[2:]\n found = False\n max_count =0\n for i in range(len(binary)):\n if(binary[i]==\'1\' and found ==False):\n start= i\n found = True\n elif(binary[i]==\'1\' and found==True):\n count = i- start\n start= i\n if(count>max_count):\n max_count= count\n return max_count\n\n \n``` | 1 | You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters. | null |
[Python3 Easy] | binary-gap | 0 | 1 | # Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n \n ans = 0\n m = -1\n while n:\n if 1&n:\n if m==-1:\n m = 1\n else:\n ans = max(ans,m)\n m=1\n else:\n if m!=-1:\n m+=1\n \n n = n>>1\n \n return ans\n``` | 1 | Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109` | null |
[Python3 Easy] | binary-gap | 0 | 1 | # Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n \n ans = 0\n m = -1\n while n:\n if 1&n:\n if m==-1:\n m = 1\n else:\n ans = max(ans,m)\n m=1\n else:\n if m!=-1:\n m+=1\n \n n = n>>1\n \n return ans\n``` | 1 | You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters. | null |
Easy Solution Using Bin Function !! | binary-gap | 0 | 1 | \n\n# Approach\nFirst of all ,We have to convert the given integer into its equivalent binary string. Then we will store all the indexes of "1" in an array.\nThen we will calculate the difference between adjacent elements. After calculating the differences we will return the maximum difference ..\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n a=[]\n l=bin(n).replace("0b","")\n for i in range(len(l)):\n if l[i]=="1":\n a.append(i)\n if len(a)<=1:\n return 0\n maxi=0\n \n for i in range(len(a)-1):\n maxi=max(maxi,int(a[i+1])-int(a[i]))\n return maxi\n \n``` | 1 | Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._
Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001 "` have a distance of 3.
**Example 1:**
**Input:** n = 22
**Output:** 2
**Explanation:** 22 in binary is "10110 ".
The first adjacent pair of 1's is "10110 " with a distance of 2.
The second adjacent pair of 1's is "10110 " with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110 " is not a valid pair since there is a 1 separating the two 1's underlined.
**Example 2:**
**Input:** n = 8
**Output:** 0
**Explanation:** 8 in binary is "1000 ".
There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.
**Example 3:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 in binary is "101 ".
**Constraints:**
* `1 <= n <= 109` | null |
Easy Solution Using Bin Function !! | binary-gap | 0 | 1 | \n\n# Approach\nFirst of all ,We have to convert the given integer into its equivalent binary string. Then we will store all the indexes of "1" in an array.\nThen we will calculate the difference between adjacent elements. After calculating the differences we will return the maximum difference ..\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def binaryGap(self, n: int) -> int:\n a=[]\n l=bin(n).replace("0b","")\n for i in range(len(l)):\n if l[i]=="1":\n a.append(i)\n if len(a)<=1:\n return 0\n maxi=0\n \n for i in range(len(a)-1):\n maxi=max(maxi,int(a[i+1])-int(a[i]))\n return maxi\n \n``` | 1 | You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters. | null |
Python My Soln | reordered-power-of-2 | 0 | 1 | class Solution:\n\n def reorderedPowerOf2(self, n: int) -> bool:\n n1 = sorted(str(n))\n \n for i in range(30):\n res = sorted(str(2 ** i))\n if res == n1:\n return True\n \n \n return False | 4 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109` | null |
Python My Soln | reordered-power-of-2 | 0 | 1 | class Solution:\n\n def reorderedPowerOf2(self, n: int) -> bool:\n n1 = sorted(str(n))\n \n for i in range(30):\n res = sorted(str(2 ** i))\n if res == n1:\n return True\n \n \n return False | 4 | We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence.
* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the `RLEIterator` class:
* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`.
* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead.
**Example 1:**
**Input**
\[ "RLEIterator ", "next ", "next ", "next ", "next "\]
\[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\]
**Output**
\[null, 8, 8, 5, -1\]
**Explanation**
RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\].
rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\].
rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
but the second term did not exist. Since the last term exhausted does not exist, we return -1.
**Constraints:**
* `2 <= encoding.length <= 1000`
* `encoding.length` is even.
* `0 <= encoding[i] <= 109`
* `1 <= n <= 109`
* At most `1000` calls will be made to `next`. | null |
python3 | easy understanding | sort | reordered-power-of-2 | 0 | 1 | ```\nclass Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n i, arr = 0, []\n v = 2**i\n while v <= 10**9: arr.append(sorted(str(v))); i+=1; v = 2**i\n return sorted(str(n)) in arr\n``` | 3 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109` | null |
python3 | easy understanding | sort | reordered-power-of-2 | 0 | 1 | ```\nclass Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n i, arr = 0, []\n v = 2**i\n while v <= 10**9: arr.append(sorted(str(v))); i+=1; v = 2**i\n return sorted(str(n)) in arr\n``` | 3 | We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence.
* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the `RLEIterator` class:
* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`.
* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead.
**Example 1:**
**Input**
\[ "RLEIterator ", "next ", "next ", "next ", "next "\]
\[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\]
**Output**
\[null, 8, 8, 5, -1\]
**Explanation**
RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\].
rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\].
rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
but the second term did not exist. Since the last term exhausted does not exist, we return -1.
**Constraints:**
* `2 <= encoding.length <= 1000`
* `encoding.length` is even.
* `0 <= encoding[i] <= 109`
* `1 <= n <= 109`
* At most `1000` calls will be made to `next`. | null |
python short and precise answer | reordered-power-of-2 | 0 | 1 | ```\nclass Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n for i in range(32):\n if Counter(str(n))==Counter(str(2**i)):\n return True\n return False\n | 3 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109` | null |
python short and precise answer | reordered-power-of-2 | 0 | 1 | ```\nclass Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n for i in range(32):\n if Counter(str(n))==Counter(str(2**i)):\n return True\n return False\n | 3 | We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence.
* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the `RLEIterator` class:
* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`.
* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead.
**Example 1:**
**Input**
\[ "RLEIterator ", "next ", "next ", "next ", "next "\]
\[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\]
**Output**
\[null, 8, 8, 5, -1\]
**Explanation**
RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\].
rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\].
rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
but the second term did not exist. Since the last term exhausted does not exist, we return -1.
**Constraints:**
* `2 <= encoding.length <= 1000`
* `encoding.length` is even.
* `0 <= encoding[i] <= 109`
* `1 <= n <= 109`
* At most `1000` calls will be made to `next`. | null |
[ Python ] ✅✅ Simple Python Solution Using Two Different Approach 🥳✌👍 | reordered-power-of-2 | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# 1. First Apporach Using Permutation Concept : \n# Runtime: 8288 ms, faster than 5.35% of Python3 online submissions for Reordered Power of 2.\n# Memory Usage: 28.1 MB, less than 11.23% of Python3 online submissions for Reordered Power of 2.\n\tclass Solution:\n\t\tdef reorderedPowerOf2(self, n: int) -> bool:\n\n\t\t\tall_permutations = [] \n\n\t\t\tfor single_number in itertools.permutations(str(n)):\n\n\t\t\t\tif single_number[0] != \'0\':\n\n\t\t\t\t\tnum = int(\'\'.join(single_number))\n\n\t\t\t\t\tall_permutations.append(num)\n\n\t\t\tfor i in range(32):\n\n\t\t\t\tif 2**i in all_permutations:\n\t\t\t\t\treturn True\n\n\t\t\treturn False\n# 2. Second Approach With HashMap Or Dictionary with Sorting : \n# Runtime: 56 ms, faster than 60.96% of Python3 online submissions for Reordered Power of 2.\n# Memory Usage: 13.7 MB, less than 96.79% of Python3 online submissions for Reordered Power of 2.\n\n\tclass Solution:\n\t\tdef reorderedPowerOf2(self, n: int) -> bool:\n\n\t\t\tnum = sorted(str(n))\n\n\t\t\tfor i in range(32):\n\n\t\t\t\tcurrent_num = sorted(str(2**i))\n\n\t\t\t\tif num == current_num:\n\t\t\t\t\treturn True\n\n\t\t\treturn False\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 2 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109` | null |
[ Python ] ✅✅ Simple Python Solution Using Two Different Approach 🥳✌👍 | reordered-power-of-2 | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# 1. First Apporach Using Permutation Concept : \n# Runtime: 8288 ms, faster than 5.35% of Python3 online submissions for Reordered Power of 2.\n# Memory Usage: 28.1 MB, less than 11.23% of Python3 online submissions for Reordered Power of 2.\n\tclass Solution:\n\t\tdef reorderedPowerOf2(self, n: int) -> bool:\n\n\t\t\tall_permutations = [] \n\n\t\t\tfor single_number in itertools.permutations(str(n)):\n\n\t\t\t\tif single_number[0] != \'0\':\n\n\t\t\t\t\tnum = int(\'\'.join(single_number))\n\n\t\t\t\t\tall_permutations.append(num)\n\n\t\t\tfor i in range(32):\n\n\t\t\t\tif 2**i in all_permutations:\n\t\t\t\t\treturn True\n\n\t\t\treturn False\n# 2. Second Approach With HashMap Or Dictionary with Sorting : \n# Runtime: 56 ms, faster than 60.96% of Python3 online submissions for Reordered Power of 2.\n# Memory Usage: 13.7 MB, less than 96.79% of Python3 online submissions for Reordered Power of 2.\n\n\tclass Solution:\n\t\tdef reorderedPowerOf2(self, n: int) -> bool:\n\n\t\t\tnum = sorted(str(n))\n\n\t\t\tfor i in range(32):\n\n\t\t\t\tcurrent_num = sorted(str(2**i))\n\n\t\t\t\tif num == current_num:\n\t\t\t\t\treturn True\n\n\t\t\treturn False\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 2 | We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence.
* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the `RLEIterator` class:
* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`.
* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead.
**Example 1:**
**Input**
\[ "RLEIterator ", "next ", "next ", "next ", "next "\]
\[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\]
**Output**
\[null, 8, 8, 5, -1\]
**Explanation**
RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\].
rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\].
rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
but the second term did not exist. Since the last term exhausted does not exist, we return -1.
**Constraints:**
* `2 <= encoding.length <= 1000`
* `encoding.length` is even.
* `0 <= encoding[i] <= 109`
* `1 <= n <= 109`
* At most `1000` calls will be made to `next`. | null |
SIMPLE C++ SOLUTION | reordered-power-of-2 | 1 | 1 | ```\nclass Solution {\npublic:\n bool reorderedPowerOf2(int n) {\n if(n == 1) return true;\n unordered_map<int, int> map;\n \n string temp = to_string(n);\n for(int i = 0; i < temp.size(); i++){\n map[int(temp[i])-48]++;\n } \n \n int digits = temp.size();\n return helper(map, 1, n, digits);\n }\n \n bool helper(unordered_map<int, int> map, long k, int s, int digits){\n if(k > pow(10, digits) - 1) return false;\n if(k == s) return true;\n \n unordered_map<int, int> copy = map;\n \n string temp = to_string(k);\n for(int i = 0; i < temp.size(); i++){\n copy[int(temp[i])-48]--;\n }\n \n for(auto &it: copy){\n if(it.second != 0) return helper(map, k*2, s, digits);\n }\n \n return true;\n }\n};\n``` | 2 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return `true` _if and only if we can do this so that the resulting number is a power of two_.
**Example 1:**
**Input:** n = 1
**Output:** true
**Example 2:**
**Input:** n = 10
**Output:** false
**Constraints:**
* `1 <= n <= 109` | null |
SIMPLE C++ SOLUTION | reordered-power-of-2 | 1 | 1 | ```\nclass Solution {\npublic:\n bool reorderedPowerOf2(int n) {\n if(n == 1) return true;\n unordered_map<int, int> map;\n \n string temp = to_string(n);\n for(int i = 0; i < temp.size(); i++){\n map[int(temp[i])-48]++;\n } \n \n int digits = temp.size();\n return helper(map, 1, n, digits);\n }\n \n bool helper(unordered_map<int, int> map, long k, int s, int digits){\n if(k > pow(10, digits) - 1) return false;\n if(k == s) return true;\n \n unordered_map<int, int> copy = map;\n \n string temp = to_string(k);\n for(int i = 0; i < temp.size(); i++){\n copy[int(temp[i])-48]--;\n }\n \n for(auto &it: copy){\n if(it.second != 0) return helper(map, k*2, s, digits);\n }\n \n return true;\n }\n};\n``` | 2 | We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence.
* For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`.
Given a run-length encoded array, design an iterator that iterates through it.
Implement the `RLEIterator` class:
* `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`.
* `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead.
**Example 1:**
**Input**
\[ "RLEIterator ", "next ", "next ", "next ", "next "\]
\[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\]
**Output**
\[null, 8, 8, 5, -1\]
**Explanation**
RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\].
rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\].
rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\].
rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,
but the second term did not exist. Since the last term exhausted does not exist, we return -1.
**Constraints:**
* `2 <= encoding.length <= 1000`
* `encoding.length` is even.
* `0 <= encoding[i] <= 109`
* `1 <= n <= 109`
* At most `1000` calls will be made to `next`. | null |
Solution | advantage-shuffle | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {\n vector<pair<int,int>>v;\n for(int i=0;i<nums2.size();i++)\n {\n v.push_back({nums2[i],i});\n }\n sort(nums1.begin(),nums1.end());\n sort(v.begin(),v.end());\n int n=v.size();\n vector<int>res(n,-1);\n int j=0;\n for(int i=0;i<n;i++)\n {\n if(v[j].first<nums1[i])\n {\n res[v[j].second]=nums1[i];\n nums1[i]=-1;\n j++;\n }\n }\n j=0;\n for(int i=0;i<n;i++)\n {\n if(nums1[i]!=-1)\n {\n while(res[j]!=-1)\n {\n j++;\n }\n res[j]=nums1[i];\n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n from collections import deque\n q = deque(sorted(nums1))\n n = len(nums1)\n order = sorted(range(n), key=lambda x: nums2[x], reverse=True)\n res = [0] * n\n for idx in order:\n if q[-1] > nums2[idx]:\n res[idx] = q.pop()\n else:\n res[idx] = q.popleft()\n return res\n```\n\n```Java []\nclass Solution {\n public int[] advantageCount(int[] nums1, int[] nums2) {\n int n = nums1.length;\n Arrays.sort(nums1);\n int[] ans = new int[n];\n boolean[] vis = new boolean[n];\n ArrayList<Integer> arr = new ArrayList<>();\n for(int i=0;i<n;i++){\n int ub = upperBound(nums1, nums2[i]);\n if(ub!=n && vis[ub]==false){\n ans[i] = nums1[ub];\n vis[ub] = true;\n }\n else if(ub<n-1 && vis[ub]==true){\n while(ub<n && vis[ub]==true){\n ub++;\n }\n if(ub==n){\n arr.add(i);\n }\n else{\n ans[i] = nums1[ub];\n vis[ub]=true;\n }\n }\n else{\n arr.add(i);\n }\n }\n int j=0;\n for(int x: arr){\n while(j<n && vis[j]==true){\n j++;\n }\n ans[x]=nums1[j];\n vis[j]=true;\n }\n return ans;\n }\n public int upperBound(int[] nums, int target){\n int low = 0;\n int high = nums.length-1;\n while(low<=high){\n int mid = low+(high-low)/2;\n if(nums[mid]<=target){\n low = mid+1;\n }\n else{\n high = mid-1;\n }\n }\n return low;\n }\n}\n```\n | 2 | You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.
**Example 1:**
**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]
**Example 2:**
**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]
**Constraints:**
* `1 <= nums1.length <= 105`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 109` | null |
Solution | advantage-shuffle | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {\n vector<pair<int,int>>v;\n for(int i=0;i<nums2.size();i++)\n {\n v.push_back({nums2[i],i});\n }\n sort(nums1.begin(),nums1.end());\n sort(v.begin(),v.end());\n int n=v.size();\n vector<int>res(n,-1);\n int j=0;\n for(int i=0;i<n;i++)\n {\n if(v[j].first<nums1[i])\n {\n res[v[j].second]=nums1[i];\n nums1[i]=-1;\n j++;\n }\n }\n j=0;\n for(int i=0;i<n;i++)\n {\n if(nums1[i]!=-1)\n {\n while(res[j]!=-1)\n {\n j++;\n }\n res[j]=nums1[i];\n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n from collections import deque\n q = deque(sorted(nums1))\n n = len(nums1)\n order = sorted(range(n), key=lambda x: nums2[x], reverse=True)\n res = [0] * n\n for idx in order:\n if q[-1] > nums2[idx]:\n res[idx] = q.pop()\n else:\n res[idx] = q.popleft()\n return res\n```\n\n```Java []\nclass Solution {\n public int[] advantageCount(int[] nums1, int[] nums2) {\n int n = nums1.length;\n Arrays.sort(nums1);\n int[] ans = new int[n];\n boolean[] vis = new boolean[n];\n ArrayList<Integer> arr = new ArrayList<>();\n for(int i=0;i<n;i++){\n int ub = upperBound(nums1, nums2[i]);\n if(ub!=n && vis[ub]==false){\n ans[i] = nums1[ub];\n vis[ub] = true;\n }\n else if(ub<n-1 && vis[ub]==true){\n while(ub<n && vis[ub]==true){\n ub++;\n }\n if(ub==n){\n arr.add(i);\n }\n else{\n ans[i] = nums1[ub];\n vis[ub]=true;\n }\n }\n else{\n arr.add(i);\n }\n }\n int j=0;\n for(int x: arr){\n while(j<n && vis[j]==true){\n j++;\n }\n ans[x]=nums1[j];\n vis[j]=true;\n }\n return ans;\n }\n public int upperBound(int[] nums, int target){\n int low = 0;\n int high = nums.length-1;\n while(low<=high){\n int mid = low+(high-low)/2;\n if(nums[mid]<=target){\n low = mid+1;\n }\n else{\n high = mid-1;\n }\n }\n return low;\n }\n}\n```\n | 2 | Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`. | null |
Easy Pyton Solution Beats 98% | advantage-shuffle | 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 advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n sorted_nums1 = sorted(nums1)\n sorted_nums2 = sorted((num, i) for i, num in enumerate(nums2))\n res = [0] * len(nums1)\n remaining = []\n j = 0\n\n for num in sorted_nums1:\n if num > sorted_nums2[j][0]:\n res[sorted_nums2[j][1]] = num\n j += 1\n else:\n remaining.append(num)\n\n for i in range(len(nums2)):\n if res[i] == 0:\n res[i] = remaining.pop()\n\n return res\n``` | 1 | You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.
**Example 1:**
**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]
**Example 2:**
**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]
**Constraints:**
* `1 <= nums1.length <= 105`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 109` | null |
Easy Pyton Solution Beats 98% | advantage-shuffle | 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 advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n sorted_nums1 = sorted(nums1)\n sorted_nums2 = sorted((num, i) for i, num in enumerate(nums2))\n res = [0] * len(nums1)\n remaining = []\n j = 0\n\n for num in sorted_nums1:\n if num > sorted_nums2[j][0]:\n res[sorted_nums2[j][1]] = num\n j += 1\n else:\n remaining.append(num)\n\n for i in range(len(nums2)):\n if res[i] == 0:\n res[i] = remaining.pop()\n\n return res\n``` | 1 | Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`. | null |
Python | Video Walkthrough | Time: O(nlogn) | Space: O(n) | advantage-shuffle | 0 | 1 | [Click Here For Video](https://youtu.be/nz0_sRskx5U)\n```\nclass Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n I, res, _ = deque(sorted(range(len(nums2)),key = lambda idx: nums2[idx])), [-1] * len(nums1), nums1.sort()\n for boy in nums1:\n if boy > nums2[I[0]]: res[I.popleft()] = boy\n else: res[I.pop()] = boy\n return res\n``` | 0 | You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.
**Example 1:**
**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]
**Example 2:**
**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]
**Constraints:**
* `1 <= nums1.length <= 105`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 109` | null |
Python | Video Walkthrough | Time: O(nlogn) | Space: O(n) | advantage-shuffle | 0 | 1 | [Click Here For Video](https://youtu.be/nz0_sRskx5U)\n```\nclass Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n I, res, _ = deque(sorted(range(len(nums2)),key = lambda idx: nums2[idx])), [-1] * len(nums1), nums1.sort()\n for boy in nums1:\n if boy > nums2[I[0]]: res[I.popleft()] = boy\n else: res[I.pop()] = boy\n return res\n``` | 0 | Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`. | null |
Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98% | minimum-number-of-refueling-stops | 0 | 1 | ```\nclass Solution: # Here\'s the plan:\n # \n # 1) We only need to be concerned with two quantities: the dist traveled (pos)\n # and the fuel acquired (fuel). We have to refuel before pos > fuel.\n # \n # 2) Because we have an infinite capacity tank, we only have to plan where to acquire\n # fuel before pos > fuel, and common sense says to stop at the station within range\n # with the most fuel.\n # \n # 3) And that\'s a job for a heap. we heappush the stations that are within range of present\n # fuel, and heappop the best choice if and when we need fuel.\n # \n # 4) We are finished when a) we have acquired sufficient fuel such that fuel >= target \n # (return # of fuelings), or b) fuel < target and the heap is empty (return -1).\n \n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n\n fuel, heap, count = startFuel, [], 0 # <-- initialize some stuff\n \n stations.append([target, 0]) # <-- this handles the "stations = []" test\n\n while stations:\n if fuel >= target: return count # <-- 4) \n\n while stations and stations[0][0] <= fuel: # <-- 3)\n _, liters = stations.pop(0)\n heappush(heap,-liters)\n\n if not heap: return -1 # <-- 4)\n fuel-= heappop(heap)\n\n count+= 1 | 3 | A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109` | null |
Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98% | minimum-number-of-refueling-stops | 0 | 1 | ```\nclass Solution: # Here\'s the plan:\n # \n # 1) We only need to be concerned with two quantities: the dist traveled (pos)\n # and the fuel acquired (fuel). We have to refuel before pos > fuel.\n # \n # 2) Because we have an infinite capacity tank, we only have to plan where to acquire\n # fuel before pos > fuel, and common sense says to stop at the station within range\n # with the most fuel.\n # \n # 3) And that\'s a job for a heap. we heappush the stations that are within range of present\n # fuel, and heappop the best choice if and when we need fuel.\n # \n # 4) We are finished when a) we have acquired sufficient fuel such that fuel >= target \n # (return # of fuelings), or b) fuel < target and the heap is empty (return -1).\n \n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n\n fuel, heap, count = startFuel, [], 0 # <-- initialize some stuff\n \n stations.append([target, 0]) # <-- this handles the "stations = []" test\n\n while stations:\n if fuel >= target: return count # <-- 4) \n\n while stations and stations[0][0] <= fuel: # <-- 3)\n _, liters = stations.pop(0)\n heappush(heap,-liters)\n\n if not heap: return -1 # <-- 4)\n fuel-= heappop(heap)\n\n count+= 1 | 3 | Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`.
Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`.
**Example 1:**
**Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100
**Output:** 20
**Explanation:**
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
**Example 2:**
**Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000
**Output:** 29523
**Explanation:**
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.
**Example 3:**
**Input:** digits = \[ "7 "\], n = 8
**Output:** 1
**Constraints:**
* `1 <= digits.length <= 9`
* `digits[i].length == 1`
* `digits[i]` is a digit from `'1'` to `'9'`.
* All the values in `digits` are **unique**.
* `digits` is sorted in **non-decreasing** order.
* `1 <= n <= 109` | null |
Solution | length-of-longest-fibonacci-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int lenLongestFibSubseq(vector<int>& arr) {\n int n = arr.size();\n map<pair<int,int>,int>indexes;\n\n for(int i = 2 ;i < n;i++) {\n int start = 0;\n int end = i-1;\n long long reqSum = arr[i];\n long long sum;\n while(start != end) {\n sum = arr[start] + (long long)arr[end];\n if(sum == reqSum) {\n indexes[{start,end}] = i;\n start++;\n }\n else if(sum < reqSum) start++;\n else end--;\n }\n }\n int count = 0;\n int maxCount = 0;\n for(auto &it : indexes) {\n count = 2;\n int i=it.first.first,j=it.first.second,k=it.second;\n while((long long)arr[i]+arr[j] == (long long)arr[k]) {\n count++;\n i = j;\n j = k;\n k = indexes[{i,j}];\n }\n if(count > maxCount)maxCount = count;\n }\n return maxCount;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def lenLongestFibSubseq(self, arr: list[int]) -> int:\n longest_subsequence = 0\n index_from_value_table = {x: i for i, x in enumerate(arr)}\n subsequence_length_dict = defaultdict(lambda: 2)\n for k, k_val in enumerate(arr):\n jlo = bisect_right(arr, k_val // 2, hi=k)\n for j_val in arr[jlo:k]:\n j = index_from_value_table[j_val]\n i = index_from_value_table.get(k_val - j_val, None)\n if i is None: continue\n seq = subsequence_length_dict[i, j] + 1\n subsequence_length_dict[j, k] = seq\n longest_subsequence = max(longest_subsequence, seq)\n return longest_subsequence\n```\n\n```Java []\nclass Solution {\n\tpublic int lenLongestFibSubseq(int[] arr) {\n\t\tint length = arr.length;\n\t\tint[][] dp = new int[length][length];\n\t\tint result = 0;\n\t\tfor (int i = 2; i < length; i++) {\n\t\t\tint left = 0;\n\t\t\tint right = i - 1;\n\t\t\twhile (left < right) {\n\t\t\t\tint val = arr[left] + arr[right] - arr[i];\n\t\t\t\tif (val < 0) {\n\t\t\t\t\tleft++;\n\t\t\t\t} else if (val > 0) {\n\t\t\t\t\tright--;\n\t\t\t\t} else {\n\t\t\t\t\tdp[right][i] = dp[left][right] + 1;\n\t\t\t\t\tresult = Math.max(result, dp[right][i]);\n\t\t\t\t\tleft++;\n\t\t\t\t\tright--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result == 0 ? 0 : result + 2;\n\t}\n}\n```\n | 1 | A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if:
* `n >= 3`
* `xi + xi+1 == xi+2` for all `i + 2 <= n`
Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`.
A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5,6,7,8\]
**Output:** 5
**Explanation:** The longest subsequence that is fibonacci-like: \[1,2,3,5,8\].
**Example 2:**
**Input:** arr = \[1,3,7,11,12,14,18\]
**Output:** 3
**Explanation**: The longest subsequence that is fibonacci-like: \[1,11,12\], \[3,11,14\] or \[7,11,18\].
**Constraints:**
* `3 <= arr.length <= 1000`
* `1 <= arr[i] < arr[i + 1] <= 109` | null |
Solution | length-of-longest-fibonacci-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int lenLongestFibSubseq(vector<int>& arr) {\n int n = arr.size();\n map<pair<int,int>,int>indexes;\n\n for(int i = 2 ;i < n;i++) {\n int start = 0;\n int end = i-1;\n long long reqSum = arr[i];\n long long sum;\n while(start != end) {\n sum = arr[start] + (long long)arr[end];\n if(sum == reqSum) {\n indexes[{start,end}] = i;\n start++;\n }\n else if(sum < reqSum) start++;\n else end--;\n }\n }\n int count = 0;\n int maxCount = 0;\n for(auto &it : indexes) {\n count = 2;\n int i=it.first.first,j=it.first.second,k=it.second;\n while((long long)arr[i]+arr[j] == (long long)arr[k]) {\n count++;\n i = j;\n j = k;\n k = indexes[{i,j}];\n }\n if(count > maxCount)maxCount = count;\n }\n return maxCount;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def lenLongestFibSubseq(self, arr: list[int]) -> int:\n longest_subsequence = 0\n index_from_value_table = {x: i for i, x in enumerate(arr)}\n subsequence_length_dict = defaultdict(lambda: 2)\n for k, k_val in enumerate(arr):\n jlo = bisect_right(arr, k_val // 2, hi=k)\n for j_val in arr[jlo:k]:\n j = index_from_value_table[j_val]\n i = index_from_value_table.get(k_val - j_val, None)\n if i is None: continue\n seq = subsequence_length_dict[i, j] + 1\n subsequence_length_dict[j, k] = seq\n longest_subsequence = max(longest_subsequence, seq)\n return longest_subsequence\n```\n\n```Java []\nclass Solution {\n\tpublic int lenLongestFibSubseq(int[] arr) {\n\t\tint length = arr.length;\n\t\tint[][] dp = new int[length][length];\n\t\tint result = 0;\n\t\tfor (int i = 2; i < length; i++) {\n\t\t\tint left = 0;\n\t\t\tint right = i - 1;\n\t\t\twhile (left < right) {\n\t\t\t\tint val = arr[left] + arr[right] - arr[i];\n\t\t\t\tif (val < 0) {\n\t\t\t\t\tleft++;\n\t\t\t\t} else if (val > 0) {\n\t\t\t\t\tright--;\n\t\t\t\t} else {\n\t\t\t\t\tdp[right][i] = dp[left][right] + 1;\n\t\t\t\t\tresult = Math.max(result, dp[right][i]);\n\t\t\t\t\tleft++;\n\t\t\t\t\tright--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result == 0 ? 0 : result + 2;\n\t}\n}\n```\n | 1 | Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000` | null |
Python Elegant & Short | length-of-longest-fibonacci-subsequence | 0 | 1 | # Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def lenLongestFibSubseq(self, arr: List[int]) -> int:\n nums = set(arr)\n longest = 0\n\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n a, b = arr[i], arr[j]\n length = 2\n\n while a + b in nums:\n a, b = b, a + b\n length += 1\n\n if length > 2 and length > longest:\n longest = length\n\n return longest\n``` | 3 | A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if:
* `n >= 3`
* `xi + xi+1 == xi+2` for all `i + 2 <= n`
Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`.
A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5,6,7,8\]
**Output:** 5
**Explanation:** The longest subsequence that is fibonacci-like: \[1,2,3,5,8\].
**Example 2:**
**Input:** arr = \[1,3,7,11,12,14,18\]
**Output:** 3
**Explanation**: The longest subsequence that is fibonacci-like: \[1,11,12\], \[3,11,14\] or \[7,11,18\].
**Constraints:**
* `3 <= arr.length <= 1000`
* `1 <= arr[i] < arr[i + 1] <= 109` | null |
Python Elegant & Short | length-of-longest-fibonacci-subsequence | 0 | 1 | # Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def lenLongestFibSubseq(self, arr: List[int]) -> int:\n nums = set(arr)\n longest = 0\n\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n a, b = arr[i], arr[j]\n length = 2\n\n while a + b in nums:\n a, b = b, a + b\n length += 1\n\n if length > 2 and length > longest:\n longest = length\n\n return longest\n``` | 3 | Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000` | null |
Solution | walking-robot-simulation | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {\n set<pair<int,int>> obs_maps;\n int orientation = 1;\n int movement[4][4] = {{1,0},{0,1},{-1,0},{0,-1}};\n int x = 0, y = 0, x_max = 0, y_max = 0;\n for(auto &obs:obstacles) {\n obs_maps.insert(pair<int,int>(obs[0],obs[1]));\n }\n int max_distance = 0;\n for(int command:commands) {\n if(command == -1) {\n orientation = (orientation - 1 +4) % 4;\n }\n else if (command == -2) {\n orientation = (orientation+1)%4;\n }\n else {\n for(int i = 0; i < command; i++) {\n if (obs_maps.find(pair<int,int>(x+movement[orientation][0], \n y+movement[orientation][1])) == obs_maps.end() ) {\n x += movement[orientation][0];\n y += movement[orientation][1];\n }\n else\n break;\n }\n if (x*x+y*y >max_distance)\n max_distance = x*x+y*y;\n }\n }\n return max_distance;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set((a, b) for a, b in obstacles)\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n d = 0\n res = 0\n x, y = 0, 0\n for num in commands:\n if num == -2:\n d -= 1\n d += 4\n d %= 4\n \n elif num == -1:\n d += 1\n d %= 4\n \n else:\n dx, dy = dirs[d]\n for k in range(1, num+1):\n nx, ny = x + dx, y + dy\n if (nx, ny) in obstacles:\n break\n x, y = nx, ny\n res = max(res, x*x + y*y)\n return res\n```\n\n```Java []\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n Robot robot = new Robot();\n Set<Obstacle> obstacleSet = new HashSet<>();\n for (int[] obstacle : obstacles) {\n obstacleSet.add(new Obstacle(obstacle[0], obstacle[1]));\n }\n for (int command : commands) robot.handleCommand(command, obstacleSet);\n return robot.maxDistance;\n }\n private static class Robot {\n public int x = 0, y = 0, dir = 0, maxDistance = 0;\n public Set<Obstacle> obstacles;\n\n Robot() {}\n private void handleCommand(int command, Set<Obstacle> obstacles) {\n switch (command) {\n case -2:\n dir = (dir + 3) % 4;\n return;\n case -1:\n dir = (dir + 1) % 4;\n return;\n default: {\n while (command-- > 0) {\n int newX = x, newY = y;\n switch (dir) {\n case 0: ++newY; break;\n case 1: ++newX; break;\n case 2: --newY; break;\n default: --newX;\n }\n if (!obstacles.contains(new Obstacle(newX, newY))) {\n x = newX;\n y = newY;\n }\n }\n maxDistance = Math.max(x * x + y * y, maxDistance);\n }\n }\n }\n }\n private static class Obstacle {\n public int x, y;\n\n public Obstacle(int x, int y) {\n this.x = x;\n this.y = y;\n }\n public boolean equals(Object other) {\n return x == ((Obstacle) other).x && y == ((Obstacle) other).y;\n }\n public int hashCode() {\n return x + y * 413;\n }\n }\n}\n```\n | 1 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Solution | walking-robot-simulation | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {\n set<pair<int,int>> obs_maps;\n int orientation = 1;\n int movement[4][4] = {{1,0},{0,1},{-1,0},{0,-1}};\n int x = 0, y = 0, x_max = 0, y_max = 0;\n for(auto &obs:obstacles) {\n obs_maps.insert(pair<int,int>(obs[0],obs[1]));\n }\n int max_distance = 0;\n for(int command:commands) {\n if(command == -1) {\n orientation = (orientation - 1 +4) % 4;\n }\n else if (command == -2) {\n orientation = (orientation+1)%4;\n }\n else {\n for(int i = 0; i < command; i++) {\n if (obs_maps.find(pair<int,int>(x+movement[orientation][0], \n y+movement[orientation][1])) == obs_maps.end() ) {\n x += movement[orientation][0];\n y += movement[orientation][1];\n }\n else\n break;\n }\n if (x*x+y*y >max_distance)\n max_distance = x*x+y*y;\n }\n }\n return max_distance;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set((a, b) for a, b in obstacles)\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n d = 0\n res = 0\n x, y = 0, 0\n for num in commands:\n if num == -2:\n d -= 1\n d += 4\n d %= 4\n \n elif num == -1:\n d += 1\n d %= 4\n \n else:\n dx, dy = dirs[d]\n for k in range(1, num+1):\n nx, ny = x + dx, y + dy\n if (nx, ny) in obstacles:\n break\n x, y = nx, ny\n res = max(res, x*x + y*y)\n return res\n```\n\n```Java []\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n Robot robot = new Robot();\n Set<Obstacle> obstacleSet = new HashSet<>();\n for (int[] obstacle : obstacles) {\n obstacleSet.add(new Obstacle(obstacle[0], obstacle[1]));\n }\n for (int command : commands) robot.handleCommand(command, obstacleSet);\n return robot.maxDistance;\n }\n private static class Robot {\n public int x = 0, y = 0, dir = 0, maxDistance = 0;\n public Set<Obstacle> obstacles;\n\n Robot() {}\n private void handleCommand(int command, Set<Obstacle> obstacles) {\n switch (command) {\n case -2:\n dir = (dir + 3) % 4;\n return;\n case -1:\n dir = (dir + 1) % 4;\n return;\n default: {\n while (command-- > 0) {\n int newX = x, newY = y;\n switch (dir) {\n case 0: ++newY; break;\n case 1: ++newX; break;\n case 2: --newY; break;\n default: --newX;\n }\n if (!obstacles.contains(new Obstacle(newX, newY))) {\n x = newX;\n y = newY;\n }\n }\n maxDistance = Math.max(x * x + y * y, maxDistance);\n }\n }\n }\n }\n private static class Obstacle {\n public int x, y;\n\n public Obstacle(int x, int y) {\n this.x = x;\n this.y = y;\n }\n public boolean equals(Object other) {\n return x == ((Obstacle) other).x && y == ((Obstacle) other).y;\n }\n public int hashCode() {\n return x + y * 413;\n }\n }\n}\n```\n | 1 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
python solution | walking-robot-simulation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is that we can use a simple simulation of the robot\'s movements, updating its position and keeping track of the maximum distance it has traveled so far.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this solution is to first convert the list of obstacles into a set for faster lookup of obstacle\'s position during the simulation. Next, it creates an array containing the direction in which the robot can move, and it initializes the variables for the robot\'s position (x, y) and direction (di) to 0. Then it iterates over the commands, and for each command, it checks if the command is a turn left or right command, in which case it adjusts the direction accordingly or it is a move command. If it\'s a move command, it iterates over the command\'s value, checking if the next position is in the set of obstacles, if not, it moves to that position, and updates the maximum distance (ans) so far. Finally, it returns the maximum distance.\n\n\n# Complexity \n- Time complexity:$$O(n * m)$$\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```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set(map(tuple, obstacles))\n direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n x = y = di = 0\n ans = 0\n for cmd in commands:\n if cmd == -2:\n di = (di - 1) % 4\n elif cmd == -1:\n di = (di + 1) % 4\n else:\n for k in range(cmd):\n if (x + direction[di][0], y + direction[di][1]) not in obstacles:\n x += direction[di][0]\n y += direction[di][1]\n ans = max(ans, x * x + y * y)\n return ans\n``` | 1 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
python solution | walking-robot-simulation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is that we can use a simple simulation of the robot\'s movements, updating its position and keeping track of the maximum distance it has traveled so far.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this solution is to first convert the list of obstacles into a set for faster lookup of obstacle\'s position during the simulation. Next, it creates an array containing the direction in which the robot can move, and it initializes the variables for the robot\'s position (x, y) and direction (di) to 0. Then it iterates over the commands, and for each command, it checks if the command is a turn left or right command, in which case it adjusts the direction accordingly or it is a move command. If it\'s a move command, it iterates over the command\'s value, checking if the next position is in the set of obstacles, if not, it moves to that position, and updates the maximum distance (ans) so far. Finally, it returns the maximum distance.\n\n\n# Complexity \n- Time complexity:$$O(n * m)$$\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```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set(map(tuple, obstacles))\n direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n x = y = di = 0\n ans = 0\n for cmd in commands:\n if cmd == -2:\n di = (di - 1) % 4\n elif cmd == -1:\n di = (di + 1) % 4\n else:\n for k in range(cmd):\n if (x + direction[di][0], y + direction[di][1]) not in obstacles:\n x += direction[di][0]\n y += direction[di][1]\n ans = max(ans, x * x + y * y)\n return ans\n``` | 1 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python, simple, 99% fast | walking-robot-simulation | 0 | 1 | ```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = {(x, y) for x, y in obstacles}\n \n dist = 0\n x, y = 0, 0\n dx, dy = 0, 1\n \n for move in commands:\n if move == -2:\n dx, dy = -dy, dx\n elif move == -1:\n dx, dy = dy, -dx\n else:\n for _ in range(move):\n if (x + dx, y + dy) in obstacles:\n break\n x, y = x + dx, y + dy\n \n dist = max(dist, x*x + y*y)\n \n return dist\n``` | 11 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python, simple, 99% fast | walking-robot-simulation | 0 | 1 | ```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = {(x, y) for x, y in obstacles}\n \n dist = 0\n x, y = 0, 0\n dx, dy = 0, 1\n \n for move in commands:\n if move == -2:\n dx, dy = -dy, dx\n elif move == -1:\n dx, dy = dy, -dx\n else:\n for _ in range(move):\n if (x + dx, y + dy) in obstacles:\n break\n x, y = x + dx, y + dy\n \n dist = max(dist, x*x + y*y)\n \n return dist\n``` | 11 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python brute-force solution. | walking-robot-simulation | 0 | 1 | # Intuition\nI figured there was no better way than actually making the moves and calculating the distances.\n\n# Approach\nMy emphasis here was on properly separating the parts of the code. The "algorithm" itself isn\'t very complicated but I felt that at the very least writing the ```make_move``` function separately would go a long way. (and lo and behold, ```robotSim``` is nice and succinct.)\n\nNOTE: This solution wouldn\'t work without converting the list of obstacles to a set in ```obstacles = set(map(tuple, obstacles))```. Without this step it takes too long to execute.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(obstacles+commands)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(obstacles)$$\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set(map(tuple, obstacles))\n\n max_distance = 0\n location = [0, 0]\n orientation = [0, 1]\n\n for command in commands:\n location, orientation = self.make_move(command, obstacles, location, orientation)\n max_distance = max(max_distance, self.get_distance_squared(location))\n\n return max_distance\n \n def make_move(\n self,\n command: int,\n obstacles: Set[Tuple[int]],\n location: List[int],\n orientation: List[int]\n ) -> List[List[int]]:\n if command == -2:\n orientation = (-orientation[1], orientation[0])\n elif command == -1:\n orientation = (orientation[1], -orientation[0])\n else:\n for _ in range(command):\n target_location = (\n location[0] + orientation[0],\n location[1] + orientation[1]\n )\n if target_location in obstacles:\n break\n\n location = target_location\n\n return (location, orientation)\n\n def get_distance_squared(self, location: List[int]) -> float:\n return location[0] * location[0] + location[1] * location[1]\n\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python brute-force solution. | walking-robot-simulation | 0 | 1 | # Intuition\nI figured there was no better way than actually making the moves and calculating the distances.\n\n# Approach\nMy emphasis here was on properly separating the parts of the code. The "algorithm" itself isn\'t very complicated but I felt that at the very least writing the ```make_move``` function separately would go a long way. (and lo and behold, ```robotSim``` is nice and succinct.)\n\nNOTE: This solution wouldn\'t work without converting the list of obstacles to a set in ```obstacles = set(map(tuple, obstacles))```. Without this step it takes too long to execute.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(obstacles+commands)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(obstacles)$$\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obstacles = set(map(tuple, obstacles))\n\n max_distance = 0\n location = [0, 0]\n orientation = [0, 1]\n\n for command in commands:\n location, orientation = self.make_move(command, obstacles, location, orientation)\n max_distance = max(max_distance, self.get_distance_squared(location))\n\n return max_distance\n \n def make_move(\n self,\n command: int,\n obstacles: Set[Tuple[int]],\n location: List[int],\n orientation: List[int]\n ) -> List[List[int]]:\n if command == -2:\n orientation = (-orientation[1], orientation[0])\n elif command == -1:\n orientation = (orientation[1], -orientation[0])\n else:\n for _ in range(command):\n target_location = (\n location[0] + orientation[0],\n location[1] + orientation[1]\n )\n if target_location in obstacles:\n break\n\n location = target_location\n\n return (location, orientation)\n\n def get_distance_squared(self, location: List[int]) -> float:\n return location[0] * location[0] + location[1] * location[1]\n\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Easiest Solution | walking-robot-simulation | 1 | 1 | \n\n# Code\n```java []\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n int x = 0, y = 0, j = 0, result = 0;\n\t\tint[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};\n Set<String> set = new HashSet<>();\n for(int[] ob : obstacles) set.add(ob[0] + "_" + ob[1]);\n for(int i=0; i<commands.length; i++) {\n if(commands[i]==-1) j = (j+1)%4;\n else if(commands[i]==-2) j = (j+3)%4;\n else {\n while(commands[i]-- >0 && !set.contains((x+dirs[j][0])+ "_" +(y+dirs[j][1]))) {\n x += dirs[j][0];\n y += dirs[j][1];\n }\n }\n result = Math.max(result, x*x + y*y);\n }\n return result;\n }\n}\n```\n```python3 []\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n # directions starting north, going clockwise\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n blockers = set(tuple(x) for x in obstacles)\n\n d = 0\n curX, curY = 0, 0\n maxDist = 0\n\n for c in commands:\n if c < 0:\n if c == -1:\n d = (d + 1) % 4\n else:\n d = (d - 1) % 4\n else:\n while c != 0:\n nextX = curX + directions[d][0]\n nextY = curY + directions[d][1]\n if (nextX, nextY) in blockers:\n break\n curX = nextX\n curY = nextY\n c -= 1\n dist = pow(curX, 2) + pow(curY, 2)\n maxDist = max(maxDist, dist)\n\n return maxDist\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Easiest Solution | walking-robot-simulation | 1 | 1 | \n\n# Code\n```java []\nclass Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n int x = 0, y = 0, j = 0, result = 0;\n\t\tint[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};\n Set<String> set = new HashSet<>();\n for(int[] ob : obstacles) set.add(ob[0] + "_" + ob[1]);\n for(int i=0; i<commands.length; i++) {\n if(commands[i]==-1) j = (j+1)%4;\n else if(commands[i]==-2) j = (j+3)%4;\n else {\n while(commands[i]-- >0 && !set.contains((x+dirs[j][0])+ "_" +(y+dirs[j][1]))) {\n x += dirs[j][0];\n y += dirs[j][1];\n }\n }\n result = Math.max(result, x*x + y*y);\n }\n return result;\n }\n}\n```\n```python3 []\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n # directions starting north, going clockwise\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n blockers = set(tuple(x) for x in obstacles)\n\n d = 0\n curX, curY = 0, 0\n maxDist = 0\n\n for c in commands:\n if c < 0:\n if c == -1:\n d = (d + 1) % 4\n else:\n d = (d - 1) % 4\n else:\n while c != 0:\n nextX = curX + directions[d][0]\n nextY = curY + directions[d][1]\n if (nextX, nextY) in blockers:\n break\n curX = nextX\n curY = nextY\n c -= 1\n dist = pow(curX, 2) + pow(curY, 2)\n maxDist = max(maxDist, dist)\n\n return maxDist\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python3 - Simultation + Set of Obstacles | walking-robot-simulation | 0 | 1 | # Intuition\nOriginally I was going to have a dictionary of obstacles for every column and row (which had an obstacle) and a sorted list to look for the obstacles. But then I realized, that it could only ever move 9 at a time. That solution makes sense if it is moving thousands or even hundreds, it might even be slower for something as small as 9! So I just moved 1 cell at a time.\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n x, y, d, m = 0, 0, 0, 0\n obs = {tuple(i) for i in obstacles}\n dirs = [(0,1), (1,0), (0, -1), (-1, 0)]\n for i in commands:\n if i == -2:\n d -= 1\n elif i == -1:\n d += 1\n else:\n for j in range(i):\n px, py = x + dirs[d%4][0], y + dirs[d%4][1]\n if (px, py) in obs:\n break\n else:\n x, y = px, py\n m = max(m, x**2 + y ** 2)\n return m\n\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python3 - Simultation + Set of Obstacles | walking-robot-simulation | 0 | 1 | # Intuition\nOriginally I was going to have a dictionary of obstacles for every column and row (which had an obstacle) and a sorted list to look for the obstacles. But then I realized, that it could only ever move 9 at a time. That solution makes sense if it is moving thousands or even hundreds, it might even be slower for something as small as 9! So I just moved 1 cell at a time.\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n x, y, d, m = 0, 0, 0, 0\n obs = {tuple(i) for i in obstacles}\n dirs = [(0,1), (1,0), (0, -1), (-1, 0)]\n for i in commands:\n if i == -2:\n d -= 1\n elif i == -1:\n d += 1\n else:\n for j in range(i):\n px, py = x + dirs[d%4][0], y + dirs[d%4][1]\n if (px, py) in obs:\n break\n else:\n x, y = px, py\n m = max(m, x**2 + y ** 2)\n return m\n\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python easy to understand beats 87.99% | walking-robot-simulation | 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 robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n direction=[(0,1),(1,0),(0,-1),(-1,0)]\n direct=0\n x=0\n y=0\n obstr=set((x,y) for x,y in obstacles)\n res=0\n for c in commands:\n if c==-1:\n direct=(direct+1)%4\n elif c==-2:\n direct=(direct+3)%4\n else:\n for _ in range(c):\n nx=x+direction[direct][0]\n ny=y+direction[direct][1]\n if (nx,ny) in obstr:\n break\n x=nx\n y=ny\n res=max(res,x**2 + y**2)\n return res\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python easy to understand beats 87.99% | walking-robot-simulation | 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 robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n direction=[(0,1),(1,0),(0,-1),(-1,0)]\n direct=0\n x=0\n y=0\n obstr=set((x,y) for x,y in obstacles)\n res=0\n for c in commands:\n if c==-1:\n direct=(direct+1)%4\n elif c==-2:\n direct=(direct+3)%4\n else:\n for _ in range(c):\n nx=x+direction[direct][0]\n ny=y+direction[direct][1]\n if (nx,ny) in obstr:\n break\n x=nx\n y=ny\n res=max(res,x**2 + y**2)\n return res\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Intuitive and Readable Python Solution (Beats 97%) | walking-robot-simulation | 0 | 1 | # Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n dir = ((0,1),(1,0),(0,-1),(-1,0)) # North, East, South, West\n curr_dir = 0\n curr_pos=[0,0]\n\n max_dist = 0\n\n obstacle_set = set()\n for obstacle in obstacles:\n obstacle_set.add((obstacle[0], obstacle[1]))\n \n for command in commands:\n if command == -2:\n if curr_dir == 0: curr_dir = 3\n else: curr_dir -= 1\n elif command == -1:\n if curr_dir == 3: curr_dir = 0\n else: curr_dir += 1\n else:\n for i in range(command):\n next_x_pos = curr_pos[0] + dir[curr_dir][0]\n next_y_pos = curr_pos[1] + dir[curr_dir][1]\n if (next_x_pos, next_y_pos) in obstacle_set:\n break\n curr_pos[0] = next_x_pos\n curr_pos[1] = next_y_pos\n\n max_dist = max(max_dist, next_x_pos*next_x_pos + next_y_pos*next_y_pos)\n \n return max_dist\n\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Intuitive and Readable Python Solution (Beats 97%) | walking-robot-simulation | 0 | 1 | # Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n dir = ((0,1),(1,0),(0,-1),(-1,0)) # North, East, South, West\n curr_dir = 0\n curr_pos=[0,0]\n\n max_dist = 0\n\n obstacle_set = set()\n for obstacle in obstacles:\n obstacle_set.add((obstacle[0], obstacle[1]))\n \n for command in commands:\n if command == -2:\n if curr_dir == 0: curr_dir = 3\n else: curr_dir -= 1\n elif command == -1:\n if curr_dir == 3: curr_dir = 0\n else: curr_dir += 1\n else:\n for i in range(command):\n next_x_pos = curr_pos[0] + dir[curr_dir][0]\n next_y_pos = curr_pos[1] + dir[curr_dir][1]\n if (next_x_pos, next_y_pos) in obstacle_set:\n break\n curr_pos[0] = next_x_pos\n curr_pos[1] = next_y_pos\n\n max_dist = max(max_dist, next_x_pos*next_x_pos + next_y_pos*next_y_pos)\n \n return max_dist\n\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
C++ and Python Stimulation | walking-robot-simulation | 0 | 1 | # Code\n```\nclass Solution {\npublic:\n int directions[4][2] = {\n {0, 1}, {1, 0}, {0, -1}, {-1, 0},\n };\n\n int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {\n int farthest = 0;\n int d = 0;\n int curX = 0, curY = 0;\n\n set<vector<int>> blockers(obstacles.begin(), obstacles.end());\n\n for (int c : commands) {\n if (c == -1) {\n d = (d + 1) % 4;\n } else if (c == -2) {\n d = (d + 3) % 4;\n } else {\n int nextX = curX;\n int nextY = curY;\n\n while (c != 0) {\n nextX += directions[d][0];\n nextY += directions[d][1];\n\n if (blockers.count({nextX, nextY})) {\n break;\n }\n \n int dist = pow(nextX, 2) + pow(nextY, 2);\n farthest = max(farthest, dist);\n curX = nextX;\n curY = nextY;\n c--;\n }\n }\n }\n\n return farthest;\n\n }\n};\n```\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n # directions starting north, going clockwise\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n blockers = set(tuple(x) for x in obstacles)\n\n d = 0\n curX, curY = 0, 0\n maxDist = 0\n\n for c in commands:\n if c < 0:\n if c == -1:\n d = (d + 1) % 4\n else:\n d = (d - 1) % 4\n else:\n while c != 0:\n nextX = curX + directions[d][0]\n nextY = curY + directions[d][1]\n if (nextX, nextY) in blockers:\n break\n curX = nextX\n curY = nextY\n c -= 1\n dist = pow(curX, 2) + pow(curY, 2)\n maxDist = max(maxDist, dist)\n\n return maxDist\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
C++ and Python Stimulation | walking-robot-simulation | 0 | 1 | # Code\n```\nclass Solution {\npublic:\n int directions[4][2] = {\n {0, 1}, {1, 0}, {0, -1}, {-1, 0},\n };\n\n int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {\n int farthest = 0;\n int d = 0;\n int curX = 0, curY = 0;\n\n set<vector<int>> blockers(obstacles.begin(), obstacles.end());\n\n for (int c : commands) {\n if (c == -1) {\n d = (d + 1) % 4;\n } else if (c == -2) {\n d = (d + 3) % 4;\n } else {\n int nextX = curX;\n int nextY = curY;\n\n while (c != 0) {\n nextX += directions[d][0];\n nextY += directions[d][1];\n\n if (blockers.count({nextX, nextY})) {\n break;\n }\n \n int dist = pow(nextX, 2) + pow(nextY, 2);\n farthest = max(farthest, dist);\n curX = nextX;\n curY = nextY;\n c--;\n }\n }\n }\n\n return farthest;\n\n }\n};\n```\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n # directions starting north, going clockwise\n directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n blockers = set(tuple(x) for x in obstacles)\n\n d = 0\n curX, curY = 0, 0\n maxDist = 0\n\n for c in commands:\n if c < 0:\n if c == -1:\n d = (d + 1) % 4\n else:\n d = (d - 1) % 4\n else:\n while c != 0:\n nextX = curX + directions[d][0]\n nextY = curY + directions[d][1]\n if (nextX, nextY) in blockers:\n break\n curX = nextX\n curY = nextY\n c -= 1\n dist = pow(curX, 2) + pow(curY, 2)\n maxDist = max(maxDist, dist)\n\n return maxDist\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
My Python3 Solution hash into set | walking-robot-simulation | 0 | 1 | # Code\n```\n dirs_l = {"l":"b","b":"r","r":"u","u":"l"}\n dirs_r = {"l":"u","u":"r","r":"b","b":"l"}\n move = {"l":[-1,0],"r":[1,0],"u":[0,1],"b":[0,-1]}\n\n temp = \'u\'\n position = [0,0]\n res = 0\n\n # convert obstacles list of lists into set of tuples\n obstacles = set(map(tuple, obstacles))\n\n for command in commands:\n if command == -2:\n temp = dirs_l[temp]\n elif command == -1:\n temp = dirs_r[temp]\n else:\n for i in range(command):\n x,y = position[0]+move[temp][0],position[1]+move[temp][1]\n if (x,y) in obstacles:\n break\n else:\n position = [x,y]\n res = max(res,position[0]**2+position[1]**2)\n return res\n\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
My Python3 Solution hash into set | walking-robot-simulation | 0 | 1 | # Code\n```\n dirs_l = {"l":"b","b":"r","r":"u","u":"l"}\n dirs_r = {"l":"u","u":"r","r":"b","b":"l"}\n move = {"l":[-1,0],"r":[1,0],"u":[0,1],"b":[0,-1]}\n\n temp = \'u\'\n position = [0,0]\n res = 0\n\n # convert obstacles list of lists into set of tuples\n obstacles = set(map(tuple, obstacles))\n\n for command in commands:\n if command == -2:\n temp = dirs_l[temp]\n elif command == -1:\n temp = dirs_r[temp]\n else:\n for i in range(command):\n x,y = position[0]+move[temp][0],position[1]+move[temp][1]\n if (x,y) in obstacles:\n break\n else:\n position = [x,y]\n res = max(res,position[0]**2+position[1]**2)\n return res\n\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python Solution | walking-robot-simulation | 0 | 1 | Posting because didn\'t see anyone handle directions like this. Kinda neat.\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n\n obs = {(coords[0], coords[1]) for coords in obstacles}\n\n x,y = 0,0\n dx,dy = 0,1\n\n dist = 0\n\n for command in commands:\n if command < 0:\n dx,dy = self.changeDir(dx, dy, command)\n else:\n x,y = self.move(x, y, dx, dy, obs, command)\n dist = max(dist, pow(x,2) + pow(y, 2))\n\n return dist\n \n\n def move(self, x, y, dx, dy, obs, moves):\n if moves <= 0:\n return x,y\n \n tentative = x + dx, y + dy\n if tentative in obs:\n return x,y\n\n return self.move(tentative[0], tentative[1], dx, dy, obs, moves - 1)\n\n def changeDir(self, dx, dy, command):\n if command is -2:\n return -dy, dx\n if command is -1:\n return dy, -dx\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python Solution | walking-robot-simulation | 0 | 1 | Posting because didn\'t see anyone handle directions like this. Kinda neat.\n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n\n obs = {(coords[0], coords[1]) for coords in obstacles}\n\n x,y = 0,0\n dx,dy = 0,1\n\n dist = 0\n\n for command in commands:\n if command < 0:\n dx,dy = self.changeDir(dx, dy, command)\n else:\n x,y = self.move(x, y, dx, dy, obs, command)\n dist = max(dist, pow(x,2) + pow(y, 2))\n\n return dist\n \n\n def move(self, x, y, dx, dy, obs, moves):\n if moves <= 0:\n return x,y\n \n tentative = x + dx, y + dy\n if tentative in obs:\n return x,y\n\n return self.move(tentative[0], tentative[1], dx, dy, obs, moves - 1)\n\n def changeDir(self, dx, dy, command):\n if command is -2:\n return -dy, dx\n if command is -1:\n return dy, -dx\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Python Solution | walking-robot-simulation | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n x,y = 0,0\n dire = [(0,1),(1,0),(0,-1),(-1,0)]\n d = 0\n ret = 0\n obstacles = {tuple(x) for x in obstacles}\n\n for step in commands:\n if step == -2:\n d = (d-1) % 4\n elif step == -1:\n d = (d+1) % 4\n else:\n dx , dy = dire[d]\n for i in range(step):\n x += dx\n y+= dy\n if (x,y) in obstacles:\n x-=dx\n y-=dy\n\n break\n ret = max(ret,(x*x)+(y*y))\n\n \n return ret\n\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Python Solution | walking-robot-simulation | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n x,y = 0,0\n dire = [(0,1),(1,0),(0,-1),(-1,0)]\n d = 0\n ret = 0\n obstacles = {tuple(x) for x in obstacles}\n\n for step in commands:\n if step == -2:\n d = (d-1) % 4\n elif step == -1:\n d = (d+1) % 4\n else:\n dx , dy = dire[d]\n for i in range(step):\n x += dx\n y+= dy\n if (x,y) in obstacles:\n x-=dx\n y-=dy\n\n break\n ret = max(ret,(x*x)+(y*y))\n\n \n return ret\n\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Walking Robot Simulation | walking-robot-simulation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic approach is straightforward: keep track of x, y, and the direction, represented as a two-vector dx, dy. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically, a case statement for the three types of commands: left and right turns and forward. Note the "backing off" step when encountering an obstacle.\n# Complexity\nMy initial attempts failed due to execution time. By commenting out the handling of obstacles entirely, I was able to infer that that was the most time-consuming step, which included (1) Forming a two-list [x,y] and then looking whether than is "in" (list membership) the list of obstacles. I was able to reduce the time sufficiently by refactoring obstacles from a list of [x,y] lists to a dictionary {x: {y1, ..., yN}} and then doing the lookup in two stages, first comparing x\'s and then y\'s. I also tried to avoid list formation and indexing by breaking the state up into individual scalar variables.\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe basic work is $$O(n)$$ because there are $$n$$ commands to be processed, and the number of iterations in the "for" loop is limited to 9. Add to that the time cost of doing the obstacle lookup, which is basically $$O(n log m)$$ where "n" is the number of commands and "m" is the number of obstacles.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe only complex space requirement is for the refactored representation of obstacles, which is approximately $$O(m)$$.\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n maxDistSqd = 0\n nobstacles = defaultdict( list )\n for ox, oy in obstacles:\n nobstacles[ ox ].append( oy )\n # Represent robot state as (x,y,dx,dy), where dx, dy is the direction\n # the robot is facing, e.g., (0,1) is north, (-1,0) is west, etc.\n x, y, dx, dy = 0, 0, 0, 1 # At origin, facing north\n for command in commands:\n if command == -2:\n temp = dx\n dx = -dy\n dy = temp\n elif command == -1:\n temp = -dx\n dx = dy\n dy = temp\n else:\n for i in range( command ):\n x += dx\n y += dy\n if x in nobstacles:\n if y in nobstacles[ x ]:\n x -= dx\n y -= dy\n break\n maxDistSqd = max( maxDistSqd, x * x + y * y )\n return maxDistSqd\n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
Walking Robot Simulation | walking-robot-simulation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic approach is straightforward: keep track of x, y, and the direction, represented as a two-vector dx, dy. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically, a case statement for the three types of commands: left and right turns and forward. Note the "backing off" step when encountering an obstacle.\n# Complexity\nMy initial attempts failed due to execution time. By commenting out the handling of obstacles entirely, I was able to infer that that was the most time-consuming step, which included (1) Forming a two-list [x,y] and then looking whether than is "in" (list membership) the list of obstacles. I was able to reduce the time sufficiently by refactoring obstacles from a list of [x,y] lists to a dictionary {x: {y1, ..., yN}} and then doing the lookup in two stages, first comparing x\'s and then y\'s. I also tried to avoid list formation and indexing by breaking the state up into individual scalar variables.\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe basic work is $$O(n)$$ because there are $$n$$ commands to be processed, and the number of iterations in the "for" loop is limited to 9. Add to that the time cost of doing the obstacle lookup, which is basically $$O(n log m)$$ where "n" is the number of commands and "m" is the number of obstacles.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe only complex space requirement is for the refactored representation of obstacles, which is approximately $$O(m)$$.\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n maxDistSqd = 0\n nobstacles = defaultdict( list )\n for ox, oy in obstacles:\n nobstacles[ ox ].append( oy )\n # Represent robot state as (x,y,dx,dy), where dx, dy is the direction\n # the robot is facing, e.g., (0,1) is north, (-1,0) is west, etc.\n x, y, dx, dy = 0, 0, 0, 1 # At origin, facing north\n for command in commands:\n if command == -2:\n temp = dx\n dx = -dy\n dy = temp\n elif command == -1:\n temp = -dx\n dx = dy\n dy = temp\n else:\n for i in range( command ):\n x += dx\n y += dy\n if x in nobstacles:\n if y in nobstacles[ x ]:\n x -= dx\n y -= dy\n break\n maxDistSqd = max( maxDistSqd, x * x + y * y )\n return maxDistSqd\n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
PYTHON EZ MODE CHECKING ROTATE | walking-robot-simulation | 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 robotSim(self, commands: List[int], obs: List[List[int]]) -> int:\n start=[0,0]\n rotate="+Y"\n res=0\n arr=set([f"{i[0]}-{i[1]}" for i in obs])\n for i in commands:\n if not i==-2 and not i==-1:\n if rotate=="+Y":\n for j in range(i):\n if f"{start[0]}-{start[1]+1}" in arr:break\n else:start[1]+=1\n elif rotate=="+X":\n for j in range(i):\n if f"{start[0]+1}-{start[1]}" in arr:break\n else:start[0]+=1\n elif rotate=="-Y":\n for j in range(i):\n if f"{start[0]}-{start[1]-1}" in arr:break\n else:start[1]-=1\n elif rotate=="-X":\n for j in range(i):\n if f"{start[0]-1}-{start[1]}" in arr:break\n else:start[0]-=1\n res=max(res,((start[0]**2)+(start[1]**2)))\n else:\n if i==-1:\n if rotate=="+Y":rotate="+X"\n elif rotate=="+X":rotate="-Y"\n elif rotate=="-Y":rotate="-X"\n elif rotate=="-X":rotate="+Y"\n elif i==-2:\n if rotate=="+Y":rotate="-X"\n elif rotate=="+X":rotate="+Y"\n elif rotate=="-Y":rotate="+X"\n elif rotate=="-X":rotate="-Y"\n return res\n\n\n\n \n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
PYTHON EZ MODE CHECKING ROTATE | walking-robot-simulation | 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 robotSim(self, commands: List[int], obs: List[List[int]]) -> int:\n start=[0,0]\n rotate="+Y"\n res=0\n arr=set([f"{i[0]}-{i[1]}" for i in obs])\n for i in commands:\n if not i==-2 and not i==-1:\n if rotate=="+Y":\n for j in range(i):\n if f"{start[0]}-{start[1]+1}" in arr:break\n else:start[1]+=1\n elif rotate=="+X":\n for j in range(i):\n if f"{start[0]+1}-{start[1]}" in arr:break\n else:start[0]+=1\n elif rotate=="-Y":\n for j in range(i):\n if f"{start[0]}-{start[1]-1}" in arr:break\n else:start[1]-=1\n elif rotate=="-X":\n for j in range(i):\n if f"{start[0]-1}-{start[1]}" in arr:break\n else:start[0]-=1\n res=max(res,((start[0]**2)+(start[1]**2)))\n else:\n if i==-1:\n if rotate=="+Y":rotate="+X"\n elif rotate=="+X":rotate="-Y"\n elif rotate=="-Y":rotate="-X"\n elif rotate=="-X":rotate="+Y"\n elif i==-2:\n if rotate=="+Y":rotate="-X"\n elif rotate=="+X":rotate="+Y"\n elif rotate=="-Y":rotate="+X"\n elif rotate=="-X":rotate="-Y"\n return res\n\n\n\n \n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
<py> | walking-robot-simulation | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n \'\'\'\n 0 1 2 3\n directions = ["North", "East", "South", "West"]\n (0, 1) (1, 0) (0, -1) (-1, 0)\n \'\'\'\n def turn(direction):\n nonlocal cur_direction\n # direction == -1\n if direction == -1:\n direction = 1\n # direction == -2\n else: \n direction = -1\n \n cur_direction = (cur_direction + direction) % 4\n\n def Euclidean_distance(cur_x, cur_y):\n nonlocal Max_distance\n Max_distance = max(Max_distance, (cur_x) ** 2 + (cur_y) ** 2)\n\n \n\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n obs = set(tuple(ob) for ob in obstacles)\n cur_x = 0\n cur_y = 0\n cur_direction = 0 # North\n Max_distance = 0\n\n for command in commands:\n if command == -1 or command == -2:\n turn(direction = command)\n \n else:\n dx, dy = directions[cur_direction] \n for _ in range(command):\n if (cur_x + dx, cur_y + dy) in obs:\n break\n else:\n cur_x += dx\n cur_y += dy\n Euclidean_distance(cur_x, cur_y)\n\n \n return Max_distance\n \n \n\n\n \n\n\n\n\n\n \n``` | 0 | A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`. | null |
<py> | walking-robot-simulation | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n \'\'\'\n 0 1 2 3\n directions = ["North", "East", "South", "West"]\n (0, 1) (1, 0) (0, -1) (-1, 0)\n \'\'\'\n def turn(direction):\n nonlocal cur_direction\n # direction == -1\n if direction == -1:\n direction = 1\n # direction == -2\n else: \n direction = -1\n \n cur_direction = (cur_direction + direction) % 4\n\n def Euclidean_distance(cur_x, cur_y):\n nonlocal Max_distance\n Max_distance = max(Max_distance, (cur_x) ** 2 + (cur_y) ** 2)\n\n \n\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n obs = set(tuple(ob) for ob in obstacles)\n cur_x = 0\n cur_y = 0\n cur_direction = 0 # North\n Max_distance = 0\n\n for command in commands:\n if command == -1 or command == -2:\n turn(direction = command)\n \n else:\n dx, dy = directions[cur_direction] \n for _ in range(command):\n if (cur_x + dx, cur_y + dy) in obs:\n break\n else:\n cur_x += dx\n cur_y += dy\n Euclidean_distance(cur_x, cur_y)\n\n \n return Max_distance\n \n \n\n\n \n\n\n\n\n\n \n``` | 0 | Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`. | null |
Binary search over answer in python | koko-eating-bananas | 0 | 1 | # Approach\nBinary search over answer\n\n# Complexity\n- Time complexity: $$O(n * log n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n def check_can_eat(k):\n actual_h = 0\n for pile in piles:\n actual_h += (pile+k-1)//k\n return actual_h <= h\n l,r = 0,max(piles)\n while r-l>1:\n m=(l+r)//2\n if check_can_eat(m):\n r = m\n else:\n l = m\n return r\n``` | 1 | Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4
**Example 2:**
**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30
**Example 3:**
**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109` | null |
Binary search over answer in python | koko-eating-bananas | 0 | 1 | # Approach\nBinary search over answer\n\n# Complexity\n- Time complexity: $$O(n * log n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n def check_can_eat(k):\n actual_h = 0\n for pile in piles:\n actual_h += (pile+k-1)//k\n return actual_h <= h\n l,r = 0,max(piles)\n while r-l>1:\n m=(l+r)//2\n if check_can_eat(m):\n r = m\n else:\n l = m\n return r\n``` | 1 | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null |
Optimized Bounds + Binary Search Python3 Solution | koko-eating-bananas | 0 | 1 | # Optimized Bounds + Binary Search\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIn addition to the binary search solution, I also added an optimization at the beginning to find the bounds of where k could be. This should be better than the posted solutions, since it\'s able to find the bounds in O(nlog(n)), which is equivalent to the modified BS and can severely cut down on the starting space that\'s checked, more than doubling the % beat from 35% to 80%\n\n# Code\n```\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n k = 1\n hours_taken = sum(piles)\n while hours_taken > h:\n k *= 2\n hours_taken = sum([math.ceil(p / k) for p in piles])\n if k == 1:\n return k\n\n l = k/2\n while l < k:\n mid = (l + k) // 2\n val = sum([math.ceil(p / mid) for p in piles])\n\n if val <= h:\n k = mid\n else:\n l = mid + 1\n return int(k)\n``` | 3 | Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4
**Example 2:**
**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30
**Example 3:**
**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109` | null |
Optimized Bounds + Binary Search Python3 Solution | koko-eating-bananas | 0 | 1 | # Optimized Bounds + Binary Search\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIn addition to the binary search solution, I also added an optimization at the beginning to find the bounds of where k could be. This should be better than the posted solutions, since it\'s able to find the bounds in O(nlog(n)), which is equivalent to the modified BS and can severely cut down on the starting space that\'s checked, more than doubling the % beat from 35% to 80%\n\n# Code\n```\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n k = 1\n hours_taken = sum(piles)\n while hours_taken > h:\n k *= 2\n hours_taken = sum([math.ceil(p / k) for p in piles])\n if k == 1:\n return k\n\n l = k/2\n while l < k:\n mid = (l + k) // 2\n val = sum([math.ceil(p / mid) for p in piles])\n\n if val <= h:\n k = mid\n else:\n l = mid + 1\n return int(k)\n``` | 3 | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null |
Easy python solution using binary search, beginners friendly!!🔥🔥 | koko-eating-bananas | 0 | 1 | # Code\n```\nimport math\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n a = 1\n b=max(piles)\n while a<b:\n mid=(a+b)//2\n c=0\n for j in piles:\n c+=math.ceil(j/mid)\n if c>h:\n a=mid+1\n else:\n b=mid\n return a\n``` | 2 | Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4
**Example 2:**
**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30
**Example 3:**
**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109` | null |
Easy python solution using binary search, beginners friendly!!🔥🔥 | koko-eating-bananas | 0 | 1 | # Code\n```\nimport math\nclass Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n a = 1\n b=max(piles)\n while a<b:\n mid=(a+b)//2\n c=0\n for j in piles:\n c+=math.ceil(j/mid)\n if c>h:\n a=mid+1\n else:\n b=mid\n return a\n``` | 2 | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null |
Assalomu aleykum... | middle-of-the-linked-list | 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 singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n cur = head\n n = 0\n\n while cur:\n n += 1\n cur = cur.next\n cur = head\n n = (n // 2) + 1\n i = 0 \n\n while cur:\n i += 1\n if i == n:\n head = cur\n return head\n cur = cur.next \n\n \n \n \n``` | 0 | Given the `head` of a singly linked list, return _the middle node of the linked list_.
If there are two middle nodes, return **the second middle** node.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.
**Example 2:**
**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
**Constraints:**
* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100` | null |
Assalomu aleykum... | middle-of-the-linked-list | 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 singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n cur = head\n n = 0\n\n while cur:\n n += 1\n cur = cur.next\n cur = head\n n = (n // 2) + 1\n i = 0 \n\n while cur:\n i += 1\n if i == n:\n head = cur\n return head\n cur = cur.next \n\n \n \n \n``` | 0 | You are given an integer array `nums` and an integer `k`.
In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 0
**Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Simple solution with Dynamic Programming in Python3 | stone-game | 0 | 1 | # Intuition\nWe have `piles` with stones to play game.\nThere\'re two participants: `A` and `B`.\nOur goal is to check, if it\'s feasible for `A` to win a game in a such way, that `A` has amount of stones **more than** `B` has.\nEach player take `piles[i]` by their turn from **left/right side**. \nThe game continues **greedily** for both players.\n\n# Approach\nAt the first point it might look, that **Greedy approach** is enough, since we want to **maximize** score for `A`, but it\'s not optimal.\nWe\'re going to use **DP**, since we don\'t know, if `A` wants to take a stone from **left** or from **right** side. \n\n# Complexity\n- Time complexity: **O(N)**\n\n- Space complexity: **O(N)**\n\n# Code (tabulation / recursion tabs)\n```python3 []\n# tabulation\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n n = len(piles)\n dp = [0] * (n // 2 + 1)\n\n for i in range(1, n // 2 + 1):\n dp[i] = dp[i - 1] + max(piles[i] - piles[n - i], piles[n - i] - piles[i])\n\n return dp[len(piles) // 2] > 0\n```\n```python3 []\n# recursion\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n @cache\n def dp(i, j):\n if i > j:\n return 0\n \n left, right = piles[i] - piles[j], piles[j] - piles[i]\n \n return max(dp(i + 1, j - 1) + left, dp(i + 1, j - 1) + right)\n\n return dp(0, len(piles) - 1)\n``` | 1 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
Simple solution with Dynamic Programming in Python3 | stone-game | 0 | 1 | # Intuition\nWe have `piles` with stones to play game.\nThere\'re two participants: `A` and `B`.\nOur goal is to check, if it\'s feasible for `A` to win a game in a such way, that `A` has amount of stones **more than** `B` has.\nEach player take `piles[i]` by their turn from **left/right side**. \nThe game continues **greedily** for both players.\n\n# Approach\nAt the first point it might look, that **Greedy approach** is enough, since we want to **maximize** score for `A`, but it\'s not optimal.\nWe\'re going to use **DP**, since we don\'t know, if `A` wants to take a stone from **left** or from **right** side. \n\n# Complexity\n- Time complexity: **O(N)**\n\n- Space complexity: **O(N)**\n\n# Code (tabulation / recursion tabs)\n```python3 []\n# tabulation\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n n = len(piles)\n dp = [0] * (n // 2 + 1)\n\n for i in range(1, n // 2 + 1):\n dp[i] = dp[i - 1] + max(piles[i] - piles[n - i], piles[n - i] - piles[i])\n\n return dp[len(piles) // 2] > 0\n```\n```python3 []\n# recursion\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n @cache\n def dp(i, j):\n if i > j:\n return 0\n \n left, right = piles[i] - piles[j], piles[j] - piles[i]\n \n return max(dp(i + 1, j - 1) + left, dp(i + 1, j - 1) + right)\n\n return dp(0, len(piles) - 1)\n``` | 1 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
Python short and clean. Functional programming. | stone-game | 0 | 1 | # Approach 1: Recursive DP\n\n# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n is number of piles.`\n\n# Code\n```python\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n @cache\n def score(i: int, j: int) -> int:\n return (i < j) and max(piles[i] + score(i + 1, j), piles[j] + score(i, j - 1))\n \n return score(0, len(piles) - 1)\n\n\n```\n\n# Approach 2: Math\n\n# Complexity\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n return True\n``` | 2 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
Python short and clean. Functional programming. | stone-game | 0 | 1 | # Approach 1: Recursive DP\n\n# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\nwhere, `n is number of piles.`\n\n# Code\n```python\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n @cache\n def score(i: int, j: int) -> int:\n return (i < j) and max(piles[i] + score(i + 1, j), piles[j] + score(i, j - 1))\n \n return score(0, len(piles) - 1)\n\n\n```\n\n# Approach 2: Math\n\n# Complexity\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def stoneGame(self, piles: list[int]) -> bool:\n return True\n``` | 2 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
MIND BLOW UP SOLUTION, Beginer Friendly ✅ | stone-game | 0 | 1 | # Intuition\nAll the time Alice take the first number. So if alice isn\'t stupid she takes the big number of the list. Alice never lose the game.\n\n# Approach\nWrite to the return True\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n``` | 4 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
MIND BLOW UP SOLUTION, Beginer Friendly ✅ | stone-game | 0 | 1 | # Intuition\nAll the time Alice take the first number. So if alice isn\'t stupid she takes the big number of the list. Alice never lose the game.\n\n# Approach\nWrite to the return True\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n``` | 4 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
EASIEST SOLUTION EVER ONE LINER PYTHON | stone-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n\n``` | 2 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
EASIEST SOLUTION EVER ONE LINER PYTHON | stone-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True\n\n``` | 2 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
Python 3, dp | stone-game | 0 | 1 | # Intuition\ndp\n\n# Approach\ndp\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n\n n: int = len(piles)\n first: List[List[int]] = [[0] * n for _ in range(n)]\n second: List[List[int]] = [[0] * n for _ in range(n)]\n for j in range(n):\n first[j][j] = piles[j]\n for i in range(j - 1, -1, -1):\n first[i][j] = max(piles[i] + second[i + 1][j], piles[j] + second[i][j - 1])\n second[i][j] = min(first[i + 1][j], first[i][j - 1])\n \n return first[n-1][n-1] > second[n-1][n-1]\n\n``` | 1 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
Python 3, dp | stone-game | 0 | 1 | # Intuition\ndp\n\n# Approach\ndp\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n\n n: int = len(piles)\n first: List[List[int]] = [[0] * n for _ in range(n)]\n second: List[List[int]] = [[0] * n for _ in range(n)]\n for j in range(n):\n first[j][j] = piles[j]\n for i in range(j - 1, -1, -1):\n first[i][j] = max(piles[i] + second[i + 1][j], piles[j] + second[i][j - 1])\n second[i][j] = min(first[i + 1][j], first[i][j - 1])\n \n return first[n-1][n-1] > second[n-1][n-1]\n\n``` | 1 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
Faster than 89.38% and memory beats 80.57% | stone-game | 0 | 1 | \nRuntime = 48ms\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n a,b = 0,0\n l = 0\n h = len(piles)-1\n while l<h:\n a += max(piles[l],piles[h])\n b += min(piles[l],piles[h])\n l += 1\n h -= 1\n return a>b\n``` | 1 | Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**. | null |
Faster than 89.38% and memory beats 80.57% | stone-game | 0 | 1 | \nRuntime = 48ms\n# Code\n```\nclass Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n a,b = 0,0\n l = 0\n h = len(piles)-1\n while l<h:\n a += max(piles[l],piles[h])\n b += min(piles[l],piles[h])\n l += 1\n h -= 1\n return a>b\n``` | 1 | You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row.
You start on square `1` of the board. In each move, starting from square `curr`, do the following:
* Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`.
* This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board.
* If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`.
* The game ends when you reach the square `n2`.
A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder.
* For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`.
Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`.
**Example 1:**
**Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\]
**Output:** 4
**Explanation:**
In the beginning, you start at square 1 (at row 5, column 0).
You decide to move to square 2 and must take the ladder to square 15.
You then decide to move to square 17 and must take the snake to square 13.
You then decide to move to square 14 and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
This is the lowest possible number of moves to reach the last square, so return 4.
**Example 2:**
**Input:** board = \[\[-1,-1\],\[-1,3\]\]
**Output:** 1
**Constraints:**
* `n == board.length == board[i].length`
* `2 <= n <= 20`
* `board[i][j]` is either `-1` or in the range `[1, n2]`.
* The squares labeled `1` and `n2` do not have any ladders or snakes. | null |
easiest binary search approach in python. | nth-magical-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n x = 10 ** 9 + 7\n low=min(a,b)\n high=n*min(a,b)\n lcm=math.lcm(a,b)\n while (low<high):\n mid = (low + high) // 2\n if (mid//a)+(mid//b)-(mid//lcm)<n:\n low=mid+1\n else:\n high=mid\n return low%x\n\n``` | 2 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
easiest binary search approach in python. | nth-magical-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n x = 10 ** 9 + 7\n low=min(a,b)\n high=n*min(a,b)\n lcm=math.lcm(a,b)\n while (low<high):\n mid = (low + high) // 2\n if (mid//a)+(mid//b)-(mid//lcm)<n:\n low=mid+1\n else:\n high=mid\n return low%x\n\n``` | 2 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Awesome Trick With Binary Tree | nth-magical-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n num=10**9+7\n lcm1=math.lcm(a,b)\n left=min(a,b)\n right=n*min(a,b)\n while left<right:\n middle=(left+right)//2\n if (middle//a) + (middle//b)-(middle//lcm1)<n:\n left=middle+1\n else:\n right=middle\n return left%(num)\n\n\n``` | 1 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
Awesome Trick With Binary Tree | nth-magical-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n num=10**9+7\n lcm1=math.lcm(a,b)\n left=min(a,b)\n right=n*min(a,b)\n while left<right:\n middle=(left+right)//2\n if (middle//a) + (middle//b)-(middle//lcm1)<n:\n left=middle+1\n else:\n right=middle\n return left%(num)\n\n\n``` | 1 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Solution | nth-magical-number | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int gcdHelper(int r, int d){\n if(r == 0)\n return d;\n return gcd(d%r, r);\n }\n int nthMagicalNumber(int n, int a, int b) {\n long long int low = min(a, b);\n long long int high = (n*low);\n long long int lcm = (a*b)/gcdHelper(a,b);\n\n while(low < high){\n long long int mid = (low + (high-low)/2);\n long long int factor = mid/a + mid/b - mid/lcm;\n if(factor < n)\n low = mid+1;\n else\n high = mid;\n }\n int mod = 1e9+7;\n return low%mod;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n def GCD(a: int, b: int) -> int:\n x, y = a, b\n while y:\n x, y = y, x % y\n return x\n \n def LCM(a: int, b: int) -> int:\n return a * b / GCD(a, b)\n\n lcm = LCM(a, b)\n low, high = 2, 10 ** 14\n while low < high:\n mid = (low + high) // 2\n if mid // a + mid // b - mid // lcm < n:\n low = mid + 1\n else:\n high = mid\n \n return low % (10 ** 9 + 7)\n```\n\n```Java []\nclass Solution {\n public int nthMagicalNumber(int n, int a, int b) {\n long A = a, B = b;\n long mod = (long)(Math.pow(10,9)+7);\n long left = Math.min(a,b), right = (long)n*Math.min(a,b);\n while (B > 0) {\n long tmp = A;\n A = B;\n B = tmp % B;\n }\n long lcm = (a*b)/A;\n while (left < right) {\n long m = left+(right-left)/2;\n if ((m / a) + (m / b) - (m / lcm) < n) left = m + 1; \n else right = m;\n }\n return (int)(left % mod);\n }\n}\n```\n | 2 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
Solution | nth-magical-number | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int gcdHelper(int r, int d){\n if(r == 0)\n return d;\n return gcd(d%r, r);\n }\n int nthMagicalNumber(int n, int a, int b) {\n long long int low = min(a, b);\n long long int high = (n*low);\n long long int lcm = (a*b)/gcdHelper(a,b);\n\n while(low < high){\n long long int mid = (low + (high-low)/2);\n long long int factor = mid/a + mid/b - mid/lcm;\n if(factor < n)\n low = mid+1;\n else\n high = mid;\n }\n int mod = 1e9+7;\n return low%mod;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n def GCD(a: int, b: int) -> int:\n x, y = a, b\n while y:\n x, y = y, x % y\n return x\n \n def LCM(a: int, b: int) -> int:\n return a * b / GCD(a, b)\n\n lcm = LCM(a, b)\n low, high = 2, 10 ** 14\n while low < high:\n mid = (low + high) // 2\n if mid // a + mid // b - mid // lcm < n:\n low = mid + 1\n else:\n high = mid\n \n return low % (10 ** 9 + 7)\n```\n\n```Java []\nclass Solution {\n public int nthMagicalNumber(int n, int a, int b) {\n long A = a, B = b;\n long mod = (long)(Math.pow(10,9)+7);\n long left = Math.min(a,b), right = (long)n*Math.min(a,b);\n while (B > 0) {\n long tmp = A;\n A = B;\n B = tmp % B;\n }\n long lcm = (a*b)/A;\n while (left < right) {\n long m = left+(right-left)/2;\n if ((m / a) + (m / b) - (m / lcm) < n) left = m + 1; \n else right = m;\n }\n return (int)(left % mod);\n }\n}\n```\n | 2 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Python Hard | nth-magical-number | 0 | 1 | ```\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int: \n MOD = 10 ** 9 + 7\n lcm = math.lcm(a, b)\n l, r = min(a, b), max(a, b) * n\n\n while l < r:\n mid = (l + r) // 2\n\n if (mid // a) + (mid // b) - (mid // lcm) < n:\n l = mid + 1\n\n else:\n r = mid\n\n\n return l % MOD\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n \n``` | 0 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
Python Hard | nth-magical-number | 0 | 1 | ```\nclass Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int: \n MOD = 10 ** 9 + 7\n lcm = math.lcm(a, b)\n l, r = min(a, b), max(a, b) * n\n\n while l < r:\n mid = (l + r) // 2\n\n if (mid // a) + (mid // b) - (mid // lcm) < n:\n l = mid + 1\n\n else:\n r = mid\n\n\n return l % MOD\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n \n``` | 0 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Solution using binary search | nth-magical-number | 0 | 1 | # Complexity\n- Time complexity:$$O(log(n*min(a,b)))$$\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n mod = (10**9)+7\n n = n%mod\n a,b = a%mod, b%mod\n l = min(a,b)\n h = min(a,b) * n\n lcm = (a*b)//self.gcd(a,b)\n\n while(l <= h):\n mid = (l+h)//2 \n x = mid//a + mid//b - mid//lcm\n if(x >= n):\n h = mid-1\n else:\n l = mid + 1\n \n return l % mod\n\n\n def gcd(self,a,b):\n if(b == 0):\n return a\n return self.gcd(b,a%b)\n \n``` | 0 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
Solution using binary search | nth-magical-number | 0 | 1 | # Complexity\n- Time complexity:$$O(log(n*min(a,b)))$$\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n mod = (10**9)+7\n n = n%mod\n a,b = a%mod, b%mod\n l = min(a,b)\n h = min(a,b) * n\n lcm = (a*b)//self.gcd(a,b)\n\n while(l <= h):\n mid = (l+h)//2 \n x = mid//a + mid//b - mid//lcm\n if(x >= n):\n h = mid-1\n else:\n l = mid + 1\n \n return l % mod\n\n\n def gcd(self,a,b):\n if(b == 0):\n return a\n return self.gcd(b,a%b)\n \n``` | 0 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Recursive Binary Search | nth-magical-number | 0 | 1 | # Intuition\nProblem looks simple but can get tricky to understand. We need to find the number at a particular rank\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecursive Binary Search:\n\nRequired number has to be a multiple of a or b, once we decide on multiplier for a, we can find overall rank of the number, so binary search is appropriate here. Calculating rank is straightforward if required rank is less than the rank of LCM(a,b). So we reduce is it to less than LCM(a,b) and then do binary search like below\n\n# Complexity\n- Time complexity: $$O(log(lcmRank))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n\n mod = (10**9)+7\n LCM = (a*b)/math.gcd(a,b)\n lcmRank = (LCM/a)+(LCM/b)-1\n res = 0\n\n ## make n less than lcmRank\n\n if n>=lcmRank:\n res+=((n//lcmRank)%mod)*(LCM%mod)%mod\n n-=(n//lcmRank)*lcmRank\n if n == 0:\n return int(res)%mod\n\n ## recursive binary search on a and b\n\n def check(x,y):\n left = 0\n right = n\n while left<=right:\n mid = left+(right-left)//2\n rank = (x*mid//y)+ mid\n if rank ==n:\n return mid*x%mod\n if rank > n:\n right = mid-1\n elif rank < n:\n left = mid+1\n return check(y,x)\n \n return int(res+check(a,b))%mod\n``` | 0 | A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104` | null |
Recursive Binary Search | nth-magical-number | 0 | 1 | # Intuition\nProblem looks simple but can get tricky to understand. We need to find the number at a particular rank\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecursive Binary Search:\n\nRequired number has to be a multiple of a or b, once we decide on multiplier for a, we can find overall rank of the number, so binary search is appropriate here. Calculating rank is straightforward if required rank is less than the rank of LCM(a,b). So we reduce is it to less than LCM(a,b) and then do binary search like below\n\n# Complexity\n- Time complexity: $$O(log(lcmRank))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\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 nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n\n mod = (10**9)+7\n LCM = (a*b)/math.gcd(a,b)\n lcmRank = (LCM/a)+(LCM/b)-1\n res = 0\n\n ## make n less than lcmRank\n\n if n>=lcmRank:\n res+=((n//lcmRank)%mod)*(LCM%mod)%mod\n n-=(n//lcmRank)*lcmRank\n if n == 0:\n return int(res)%mod\n\n ## recursive binary search on a and b\n\n def check(x,y):\n left = 0\n right = n\n while left<=right:\n mid = left+(right-left)//2\n rank = (x*mid//y)+ mid\n if rank ==n:\n return mid*x%mod\n if rank > n:\n right = mid-1\n elif rank < n:\n left = mid+1\n return check(y,x)\n \n return int(res+check(a,b))%mod\n``` | 0 | You are given an integer array `nums` and an integer `k`.
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
Return _the minimum **score** of_ `nums` _after changing the values at each index_.
**Example 1:**
**Input:** nums = \[1\], k = 0
**Output:** 0
**Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0.
**Example 2:**
**Input:** nums = \[0,10\], k = 2
**Output:** 6
**Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6.
**Example 3:**
**Input:** nums = \[1,3,6\], k = 3
**Output:** 3
**Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 104`
* `0 <= k <= 104` | null |
Python3 Solution | profitable-schemes | 0 | 1 | \n```\nclass Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n m=len(group)\n dp=[[[0]*(minProfit+1) for _ in range(n+1)] for _ in range(m+1)]\n for j in range(n+1):\n dp[m][j][0]=1\n\n for i in range(m-1,-1,-1):\n for j in range(n+1):\n for k in range(minProfit+1):\n dp[i][j][k]=dp[i+1][j][k]\n if group[i]<=j:\n dp[i][j][k]+=dp[i+1][j-group[i]][max(0,k-profit[i])]\n dp[i][j][k]%=10**9+7\n\n return dp[0][n][minProfit] \n``` | 6 | There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`.
Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\]
**Output:** 2
**Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
**Example 2:**
**Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\]
**Output:** 7
**Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
**Constraints:**
* `1 <= n <= 100`
* `0 <= minProfit <= 100`
* `1 <= group.length <= 100`
* `1 <= group[i] <= 100`
* `profit.length == group.length`
* `0 <= profit[i] <= 100` | null |
Python3 Solution | profitable-schemes | 0 | 1 | \n```\nclass Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n m=len(group)\n dp=[[[0]*(minProfit+1) for _ in range(n+1)] for _ in range(m+1)]\n for j in range(n+1):\n dp[m][j][0]=1\n\n for i in range(m-1,-1,-1):\n for j in range(n+1):\n for k in range(minProfit+1):\n dp[i][j][k]=dp[i+1][j][k]\n if group[i]<=j:\n dp[i][j][k]+=dp[i+1][j-group[i]][max(0,k-profit[i])]\n dp[i][j][k]%=10**9+7\n\n return dp[0][n][minProfit] \n``` | 6 | You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`.
For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.
Implement the `TopVotedCandidate` class:
* `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays.
* `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules.
**Example 1:**
**Input**
\[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\]
\[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\]
**Output**
\[null, 0, 1, 1, 0, 0, 1\]
**Explanation**
TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]);
topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading.
topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading.
topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.)
topVotedCandidate.q(15); // return 0
topVotedCandidate.q(24); // return 0
topVotedCandidate.q(8); // return 1
**Constraints:**
* `1 <= persons.length <= 5000`
* `times.length == persons.length`
* `0 <= persons[i] < persons.length`
* `0 <= times[i] <= 109`
* `times` is sorted in a strictly increasing order.
* `times[0] <= t <= 109`
* At most `104` calls will be made to `q`. | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.