title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Simplify Path
simplify-path
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path.
String,Stack
Medium
null
928
10
Here is Line by line code in \n**Python :**\n```\ndef simplify_path(path):\n # Split path into a list of directory names\n dirs = path.split(\'/\')\n # Initialize the stack of directories\n stack = []\n # Iterate through the directories\n for d in dirs:\n # Ignore double slashes\n if d == \'\':\n continue\n # If it\'s a double period, pop the top directory from the stack\n elif d == \'..\':\n if stack:\n stack.pop()\n # If it\'s a single period or a regular directory name, add it to the stack\n elif d != \'.\':\n stack.append(d)\n # Construct the simplified canonical path\n simplified_path = \'/\' + \'/\'.join(stack)\n return simplified_path\n```\nUpvote if you find it useful
6,983
Simplify Path
simplify-path
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path. In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names. The canonical path should have the following format: Return the simplified canonical path.
String,Stack
Medium
null
860
5
\n# Code\n```\nclass Solution:\n def simplifyPath(self, path: str) -> str:\n stack = []\n\n # different directories present in the string\n temp = path.split(\'/\') \n\n for i in temp:\n if i != \'.\' and i != \'\' and i != \'..\':\n stack.append(i) # add if it is directory\n\n # move to back directory if \'..\'\n elif i == \'..\':\n if stack:\n stack.pop()\n \n return \'/\' + \'/\'.join(stack)\n```
6,986
Edit Distance
edit-distance
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word:
String,Dynamic Programming
Hard
null
31,077
322
# Intuition :\n- Here we have to find the minimum edit distance problem between two strings word1 and word2. \n- The minimum edit distance is defined as the minimum number of operations required to transform one string into another.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\n- The approach here that I am using is dynamic programming. The idea is to build a 2D matrix dp where `dp[i][j] `represents the minimum number of operations required to transform the substring `word1[0...i-1]` into the substring `word2[0...j-1].`\n# How is Matrix built :\n- The matrix is built iteratively using the following recurrence relation:\n1. If `word1[i-1] == word2[j-1]`, then `dp[i][j] = dp[i-1][j-1]`. That is, no operation is required because the characters at positions `i-1` and `j-1` are already the same.\n2. Otherwise, `dp[i][j]` is the minimum of the following three values:\n- `dp[i-1][j-1] + 1`: replace the character at position `i-1` in `word1` with the character at position `j-1` in` word2`.\n- `dp[i-1][j] + 1`: delete the character at position `i-1` in `word1.`\n- `dp[i][j-1] + 1`: insert the character at position `j-1` in `word2` into `word1` at position `i`.\n# The base cases are:\n- `dp[i][0] = i`: transforming `word1[0...i-1]` into an empty string requires `i` deletions.\n- `dp[0][j] = j`: transforming an empty string into `word2[0...j-1] `requires `j` insertions.\n<!-- Describe your approach to solving the problem. -->\n# Final Step :\n- Finally, return `dp[m][n]`, which represents the minimum number of operations required to transform `word1 `into `word2`, where `m` is the length of `word1` and `n` is the length of `word2`.\n\n# Complexity\n- Time complexity : O(mn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(mn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A\n```\n# Codes [C++ |Java |Python3] : With Comments\n```C++ []\nclass Solution {\n public:\n int minDistance(string word1, string word2) {\n const int m = word1.length();//first word length\n const int n = word2.length();//second word length\n // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j)\n vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n for (int i = 1; i <= m; ++i)\n dp[i][0] = i;\n\n for (int j = 1; j <= n; ++j)\n dp[0][j] = j;\n\n for (int i = 1; i <= m; ++i)\n for (int j = 1; j <= n; ++j)\n if (word1[i - 1] == word2[j - 1])//same characters\n dp[i][j] = dp[i - 1][j - 1];//no operation\n else\n dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;\n //replace //delete //insert\n return dp[m][n];\n }\n};\n```\n```Java []\nclass Solution {\n public int minDistance(String word1, String word2) {\n final int m = word1.length();//first word length\n final int n = word2.length();///second word length\n // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j)\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; ++i)\n dp[i][0] = i;\n\n for (int j = 1; j <= n; ++j)\n dp[0][j] = j;\n\n for (int i = 1; i <= m; ++i)\n for (int j = 1; j <= n; ++j)\n if (word1.charAt(i - 1) == word2.charAt(j - 1))//same characters\n dp[i][j] = dp[i - 1][j - 1];//no operation\n else\n dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; //replace //delete //insert\n\n return dp[m][n];\n }\n}\n\n```\n```Python []\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m = len(word1)\n n = len(word2)\n # dp[i][j] := min # Of operations to convert word1[0..i) to word2[0..j)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(1, m + 1):\n dp[i][0] = i\n\n for j in range(1, n + 1):\n dp[0][j] = j\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n\n return dp[m][n]\n```\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n![ezgif-3-22a360561c.gif]()\n\n
7,001
Edit Distance
edit-distance
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word:
String,Dynamic Programming
Hard
null
934
26
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> dp;\n \n int solve(int i, int j, string &s, string &t){\n if(i<0 && j<0)\n return 0;\n \n if(i < 0 && j>=0){\n return j+1;\n }\n \n if(i>=0 && j<0){\n return i+1;\n }\n \n if(dp[i][j] != -1)\n return dp[i][j];\n \n int l = 1000, r = 1000, z = 1000, p = 1000;\n if(s[i] == t[j]){\n l = solve(i-1,j-1,s,t);\n }\n else{\n r = 1 + solve(i-1,j,s,t);\n z = 1 + solve(i-1,j-1,s,t);\n p = 1 + solve(i,j-1,s,t);\n }\n \n return dp[i][j] = min(l,min(r,min(z,p)));\n }\n \n \n int minDistance(string s, string t) {\n dp.resize(s.size()+1,vector<int>(t.size()+1,-1));\n return solve(s.size(),t.size(),s,t);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n n = len(word1)\n m = len(word2)\n \n to_visit = [(0, 0)]\n visited = set()\n dist = 0\n while to_visit:\n nxt_lvl = []\n while to_visit:\n i, j = to_visit.pop()\n if (i, j) in visited:\n continue\n while i < n and j < m and word1[i] == word2[j]:\n i += 1\n j += 1\n if i == n and j == m:\n return dist\n if (i, j + 1) not in visited:\n nxt_lvl.append((i, j + 1))\n if (i + 1, j) not in visited:\n nxt_lvl.append((i + 1, j))\n if (i + 1, j + 1) not in visited:\n nxt_lvl.append((i + 1, j + 1))\n visited.add((i, j))\n dist += 1\n to_visit = nxt_lvl\n```\n\n```Java []\nclass Solution {\n public int minDistance(String word1, String word2) {\n if (word1.length() < word2.length()) {\n return minDistance(word2, word1);\n }\n char[] w1 = word1.toCharArray(), w2 = word2.toCharArray();\n int[] dp = new int[w2.length];\n int last = 0;\n int diag = 0;\n for (int i = 0; i < dp.length; i++) {\n dp[i] = dp.length - i;\n }\n for (int i = w1.length - 1; i > -1; i--) {\n last = w1.length - i;\n diag = w1.length - 1 - i;\n for (int j = w2.length - 1; j > -1; j--) {\n int tmp = dp[j];\n if (w1[i] == w2[j]) {\n last = dp[j] = diag;\n } else {\n last = dp[j] = Math.min(diag, Math.min(dp[j], last)) + 1;\n }\n diag = tmp;\n }\n }\n return last;\n }\n}\n```\n
7,030
Edit Distance
edit-distance
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word:
String,Dynamic Programming
Hard
null
1,806
8
**Python3 Solution**\n```python\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n # base case - i steps away\n for i in range(1, m + 1):\n dp[i][0] = i\n for j in range(1, n + 1):\n dp[0][j] = j\n # each step has four possibilities\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n # same character, i and j move ahead together\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n # find min of insert, replace, remove a character\n else:\n dp[i][j] = min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + 1\n )\n \n return dp[m][n]\n```
7,038
Edit Distance
edit-distance
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word:
String,Dynamic Programming
Hard
null
3,603
18
```\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n\n w1, w2 = len(word1), len(word2)\n \n @lru_cache(None)\n def dp(i, j):\n\n if i >= w1 : return w2-j # word1 used up, so all inserts\n if j >= w2 : return w1-i # word2 used up, so all deletes\n if word1[i] == word2[j]: return dp(i+1, j+1) # letters match, so no operation\n\n return min(dp(i,j+1), dp(i+1,j), dp(i+1,j+1)) + 1 # insert, delete, replace\n\n return dp(0,0)\n```\n[](http://)\n\nI could be wrong, but I think that time complexity is *O*(*MN*) and space complexity is *O*(*MN*), in which *M, N* ~ `len(word1),len(word2)`.\n
7,087
Set Matrix Zeroes
set-matrix-zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.
Array,Hash Table,Matrix
Medium
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
24,113
195
Note: m = number of rows, n = number of cols\n\n**Brute force using O(m*n) space:** The initial approach is to start with creating another matrix to store the result. From doing that, you\'ll notice that we want a way to know when each row and col should be changed to zero. We don\'t want to prematurely change the values in the matrix to zero because as we go through it, we might change a row to 0 because of the new value. \n\n**More optimized using O(m + n) space:** To do better, we want O(m + n). How do we go about that? Well, we really just need a way to track if any row or any col has a zero, because then that means the entire row or col has to be zero. Ok, well, then we can use an array to track the zeroes for the row and zeros for the col. Whenever we see a zero, just set that row or col to be True.\n\nSpace: O(m + n) for the zeroes_row and zeroes_col array \n``` Python\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # input validation\n if not matrix:\n return []\n\n m = len(matrix)\n n = len(matrix[0])\n\n zeroes_row = [False] * m\n zeroes_col = [False] * n\n for row in range(m):\n for col in range(n):\n if matrix[row][col] == 0:\n zeroes_row[row] = True\n zeroes_col[col] = True\n\n for row in range(m):\n for col in range(n):\n if zeroes_row[row] or zeroes_col[col]:\n matrix[row][col] = 0\n```\n\n**Most optimized using O(1) space:** But, we can do even better, O(1) - initial ask of the problem. What if instead of having a separate array to track the zeroes, we simply use the first row or col to track them and then go back to update the first row and col with zeroes after we\'re done replacing it? The approach to get constant space is to use first row and first col of the matrix as a tracker. \n* At each row or col, if you see a zero, then mark the first row or first col as zero with the current row and col. \n* Then iterate through the array again to see where the first row and col were marked as zero and then set that row/col as 0. \n* After doing that, you\'ll need to traverse through the first row and/or first col if there were any zeroes there to begin with and set everything to be equal to 0 in the first row and/or first col. \n\nTime complexity for all three progression is O(m * n).\n\n\n\n**Space:** O(1) for modification in place and using the first row and first col to keep track of zeros instead of zeroes_row and zeroes_col\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n\n m = len(matrix)\n n = len(matrix[0])\n\t\t\n first_row_has_zero = False\n first_col_has_zero = False\n \n # iterate through matrix to mark the zero row and cols\n for row in range(m):\n for col in range(n):\n if matrix[row][col] == 0:\n if row == 0:\n first_row_has_zero = True\n if col == 0:\n first_col_has_zero = True\n matrix[row][0] = matrix[0][col] = 0\n \n # iterate through matrix to update the cell to be zero if it\'s in a zero row or col\n for row in range(1, m):\n for col in range(1, n):\n matrix[row][col] = 0 if matrix[0][col] == 0 or matrix[row][0] == 0 else matrix[row][col]\n \n # update the first row and col if they\'re zero\n if first_row_has_zero:\n for col in range(n):\n matrix[0][col] = 0\n \n if first_col_has_zero:\n for row in range(m):\n matrix[row][0] = 0\n \n```
7,142
Set Matrix Zeroes
set-matrix-zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.
Array,Hash Table,Matrix
Medium
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
1,997
13
# without Space ---->O(1)\n# Time complexity ------>O(N^3)\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m=len(matrix)\n n=len(matrix[0])\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==0:\n for row in range(n):\n if matrix[i][row]!=0:\n matrix[i][row]=-2**32\n for col in range(m):\n if matrix[col][j]!=0:\n matrix[col][j]=-2**32\n\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==(-2**32):\n matrix[i][j]=0\n```\n# with space Complexity:O(2*k) \n# Time Complexity--->O(N^2)\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m=len(matrix)\n n=len(matrix[0])\n arr=[]\n for i in range(m):\n for j in range(n):\n if matrix[i][j]==0:\n arr.append([i,j])\n \n for k,l in arr:\n for row in range(n):\n matrix[k][row]=0\n for col in range(m):\n matrix[col][l]=0\n ```\n # please upvote me it would encourage me alot\n\n\n \n\n\n \n \n
7,148
Set Matrix Zeroes
set-matrix-zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.
Array,Hash Table,Matrix
Medium
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
6,503
17
# Intuition:\nWe need to modify the matrix in-place, so we can\'t use an auxiliary matrix or hash table. We can instead use the first row and first column of the original matrix as a replacement for the auxiliary array. This way, we can save the extra space required for the auxiliary arrays and also set the values in the first row and column to zero if any element in the corresponding row or column is zero.\n\n# Approach:\n1. First, the code initializes two dummy vectors, `dummyRow` and `dummyCol`, with initial values of -1. These vectors will be used to mark the rows and columns that need to be set to zero.\n2. The code then iterates through each element of the matrix and checks if it is zero. If an element is zero, it updates the corresponding indices in `dummyRow` and `dummyCol` to 0.\n3. After marking the rows and columns, the code iterates through the matrix again. For each element, it checks if the corresponding row index or column index in `dummyRow` or `dummyCol` is zero. If either of them is zero, it sets the current element to zero.\n4. Finally, the matrix will have rows and columns set to zero based on the values in `dummyRow` and `dummyCol`.\n\n# Complexity:\n- Time complexity: O(mn), where m and n are the number of rows and columns in the matrix, respectively. We have to traverse the matrix twice.\n- Space complexity: O(m+n), where m and n are the number of rows and columns in the matrix, respectively. We are using two auxiliary vectors of size m and n to keep track of the rows and columns that contain zero elements.\n\n---\n# C++\n```cpp\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int row = matrix.size();\n int col = matrix[0].size();\n vector <int> dummyRow(row,-1);\n vector<int> dummyCol(col,-1);\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n }\n};\n```\n\n---\n# Java\n```java\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int row = matrix.length;\n int col = matrix[0].length;\n int[] dummyRow = new int[row];\n int[] dummyCol = new int[col];\n Arrays.fill(dummyRow, -1);\n Arrays.fill(dummyCol, -1);\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n }\n}\n\n```\n\n---\n# Python\n```py\nclass Solution(object):\n def setZeroes(self, matrix):\n row = len(matrix)\n col = len(matrix[0])\n dummyRow = [-1] * row\n dummyCol = [-1] * col\n for i in range(row):\n for j in range(col):\n if matrix[i][j] == 0:\n dummyRow[i] = 0\n dummyCol[j] = 0\n for i in range(row):\n for j in range(col):\n if dummyRow[i] == 0 or dummyCol[j] == 0:\n matrix[i][j] = 0\n\n```\n---\n# JavaScript\n```js\nvar setZeroes = function(matrix) {\n const row = matrix.length;\n const col = matrix[0].length;\n const dummyRow = new Array(row).fill(-1);\n const dummyCol = new Array(col).fill(-1);\n for(let i=0;i<row;i++){\n for(let j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(let i=0;i<row;i++){\n for(let j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n};\n\n```
7,158
Set Matrix Zeroes
set-matrix-zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place.
Array,Hash Table,Matrix
Medium
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
3,885
12
```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n firstRowVal, R, C = 1, len(matrix), len(matrix[0])\n\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n matrix[0][j] = 0 # mark column\n if i != 0: \n matrix[i][0] = 0\n else:\n firstRowVal = 0\n \n for i in reversed(range(R)):\n for j in reversed(range(C)):\n if i == 0:\n matrix[i][j] *= firstRowVal\n elif matrix[0][j] == 0 or matrix[i][0] == 0:\n matrix[i][j] = 0\n```
7,166
Search a 2D Matrix
search-a-2d-matrix
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Array,Binary Search,Matrix
Medium
null
16,801
98
# Problem Understanding\nThe task is to find a target integer in a 2D matrix with the following properties: \n1. Each row is sorted in non-decreasing order.\n2. The first integer of each row is greater than the last integer of the previous row.\n\nThe challenge is to determine if the target integer exists within the matrix.\n\n# Approach\nGiven the problem, it may be tempting to perform a linear search through the entire matrix, but this would result in a time complexity of $$O(m \\times n)$$, which is not acceptable given the problem\'s constraint of $$O(\\log(m \\times n))$$.\n\nInstead, we can leverage the fact that the matrix is sorted both row-wise and column-wise, and apply a binary search to find the target.\n\n# Live Coding & Explenation\n\n\n## Treating the Matrix as a 1-Dimensional Array\nTo apply binary search, we need a one-dimensional array. We can treat our 2-D matrix as a one-dimensional array because of the matrix\'s sorted property. The first integer of each row is greater than the last integer of the previous row, so we can think of the rows as being appended one after the other to form a single sorted array.\n\n## Binary Search\nBinary search is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated, and the search continues on the remaining half until it is successful or the remaining half is empty.\n\n## Initialization\nBefore we start the binary search, we need to initialize two pointers:\n\n1. `left` - This represents the start of the array. We set this to 0 (the index of the first element).\n2. `right` - This represents the end of the array. We set this to `m * n - 1` (the index of the last element), where `m` and `n` are the number of rows and columns in the matrix, respectively.\n\n## Iterative Binary Search\nWe perform a binary search iteratively within a while loop until `left` exceeds `right`. In each iteration, we calculate the midpoint between `left` and `right`.\n\nTo get the row and column of the midpoint in the matrix, we use the `divmod` function with `mid` and `n`. The `divmod` function takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.\n\nWe then compare the value at the midpoint with the target:\n\n1. If the midpoint value is equal to the target, we have found the target in the matrix, and we return `True`.\n2. If the midpoint value is less than the target, this means the target must be in the right half of the array. So, we adjust `left` to be `mid + 1`.\n3. If the midpoint value is greater than the target, this means the target must be in the left half of the array. So, we adjust `right` to be `mid - 1`.\n\nIf we exit the while loop, that means we did not find the target in the matrix, so we return `False`.\n\n# Complexity\n## Time Complexity\nThe time complexity is $$O(\\log(m \\times n))$$, since we\'re effectively performing a binary search over the $$m \\times n$$ elements of the matrix.\n\n## Space Complexity\nThe space complexity is $$O(1)$$ because we only use a constant amount of space to store our variables (`left`, `right`, `mid`, `mid_value`), regardless of the size of the input matrix.\n\n# Performance\nThe performance of this solution is optimal given the problem constraints. Since the matrix is sorted and the problem requires us to find an element, binary search is the best possible approach.\n\nCertainly, here\'s the table sorted by runtime (ms) and then by memory usage (MB):\n\n| Programming Language | Runtime (ms) | Beats (%) | Memory (MB) | Beats (%) |\n|---|---|---|---|---|\n| Rust | 0 | 100 | 2.2 | 28.37 |\n| Java | 0 | 100 | 41.6 | 9.3 |\n| C++ | 3 | 82.89 | 9.5 | 19.73 |\n| Go | 3 | 58.16 | 2.7 | 98.33 |\n| JavaScript | 48 | 92.89 | 42.3 | 28.19 |\n| Python3 | 49 | 90.75 | 16.8 | 64.57 |\n| C# | 82 | 99.1 | 40.9 | 35.48 |\n\n![perf-74.png]()\n\n\n# Code\n```Python []\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n if not matrix:\n return False\n m, n = len(matrix), len(matrix[0])\n left, right = 0, m * n - 1\n\n while left <= right:\n mid = (left + right) // 2\n mid_row, mid_col = divmod(mid, n)\n\n if matrix[mid_row][mid_col] == target:\n return True\n elif matrix[mid_row][mid_col] < target:\n left = mid + 1\n else:\n right = mid - 1\n\n return False\n```\n``` C++ []\nclass Solution {\npublic:\n bool searchMatrix(vector<vector<int>>& matrix, int target) {\n int m = matrix.size();\n int n = matrix[0].size();\n int left = 0, right = m * n - 1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n int mid_val = matrix[mid / n][mid % n];\n\n if (mid_val == target)\n return true;\n else if (mid_val < target)\n left = mid + 1;\n else\n right = mid - 1;\n }\n return false;\n }\n};\n```\n``` Java []\nclass Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n int m = matrix.length;\n int n = matrix[0].length;\n int left = 0, right = m * n - 1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n int mid_val = matrix[mid / n][mid % n];\n\n if (mid_val == target)\n return true;\n else if (mid_val < target)\n left = mid + 1;\n else\n right = mid - 1;\n }\n return false;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[][]} matrix\n * @param {number} target\n * @return {boolean}\n */\nvar searchMatrix = function(matrix, target) {\n let m = matrix.length;\n let n = matrix[0].length;\n let left = 0, right = m * n - 1;\n\n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n let mid_val = matrix[Math.floor(mid / n)][mid % n];\n\n if (mid_val === target)\n return true;\n else if (mid_val < target)\n left = mid + 1;\n else\n right = mid - 1;\n }\n return false;\n};\n```\n``` C# []\npublic class Solution {\n public bool SearchMatrix(int[][] matrix, int target) {\n int m = matrix.Length;\n int n = matrix[0].Length;\n int left = 0, right = m * n - 1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n int mid_val = matrix[mid / n][mid % n];\n\n if (mid_val == target)\n return true;\n else if (mid_val < target)\n left = mid + 1;\n else\n right = mid - 1;\n }\n return false;\n }\n}\n```\n``` Go []\nfunc searchMatrix(matrix [][]int, target int) bool {\n m := len(matrix)\n n := len(matrix[0])\n left, right := 0, m*n-1\n\n for left <= right {\n mid := left + (right-left)/2\n mid_val := matrix[mid/n][mid%n]\n\n if mid_val == target {\n return true\n } else if mid_val < target {\n left = mid + 1\n } else {\n right = mid - 1\n }\n }\n return false\n}\n```\n``` Rust []\nimpl Solution {\n pub fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {\n let rows = matrix.len() as i32;\n let cols = matrix[0].len() as i32;\n\n let mut start = 0;\n let mut end = rows * cols - 1;\n\n while start <= end {\n let mid = start + (end - start) / 2;\n let mid_value = matrix[(mid / cols) as usize][(mid % cols) as usize];\n\n if mid_value == target {\n return true;\n } else if mid_value < target {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n\n false\n }\n}\n```\n\n# Live Coding + Explenation in Go\n\n\nI hope you find this solution helpful in understanding how to solve the "Search a 2D Matrix" problem. If you have any further questions or need additional clarifications, please don\'t hesitate to ask. If you understood the solution and found it beneficial, please consider giving it an upvote. Happy coding, and may your coding journey be filled with success and satisfaction! \uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB\uD83D\uDC69\u200D\uD83D\uDCBB
7,232
Search a 2D Matrix
search-a-2d-matrix
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
Array,Binary Search,Matrix
Medium
null
6,559
39
\n# Binary Search Approach---->O(LogN) \n```\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> \n row,col=len(matrix),len(matrix[0])\n left,right=0,row*col-1\n while left<=right:\n mid=(left+right)//2\n num=matrix[mid//col][mid%col]\n if num==target:\n return True\n if num>target:\n right=mid-1\n else:\n left=mid+1\n return False\n```\n# Binary Search Approach---->O(N+LogN)\n```\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n list1=[]\n for row in matrix:\n if row[-1]>=target:\n list1=row\n break\n left,right=0,len(list1)-1\n while left<=right:\n mid=(right+left)//2\n if list1[mid]==target:\n return True\n elif list1[mid]>target:\n right=mid-1\n else:\n left=mid+1\n return False\n //please upvote me it would encourage me alot\n \n```\n# 3 Lines Of Code ---->O(N^2)\n```\nclass Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n for row in matrix:\n if row[-1] >= target:\n return target in row\n\n# please upvote me it would encourage me alot\n```\n# please upvote me it would encourage me alot\n\n
7,286
Sort Colors
sort-colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function.
Array,Two Pointers,Sorting
Medium
A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.
22,516
465
```C++ []\nclass Solution {\npublic:\n void sortColors(vector<int>& nums) {\n int l = 0;\n int m = 0;\n int h = nums.size()-1;\n\n while(m<=h){\n if(nums[m]==0){\n swap(nums[l], nums[m]);\n l++;\n m++;\n }\n else if(nums[m]==1){\n m++;\n }\n else if(nums[m]==2){\n swap(nums[m], nums[h]);\n h--;\n }\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n\n red, white, blue = 0, 0, len(nums) - 1\n\n while white <= blue:\n if nums[white] == 0:\n nums[white], nums[red] = nums[red], nums[white]\n red += 1\n white += 1\n elif nums[white] == 1:\n white += 1\n else:\n nums[white], nums[blue] = nums[blue], nums[white]\n blue -= 1\n```\n\n```Java []\nclass Solution {\n public void sortColors(int[] nums) {\n int l = 0;\n int r = nums.length - 1;\n\n for (int i = 0; i <= r;)\n if (nums[i] == 0)\n swap(nums, i++, l++);\n else if (nums[i] == 1)\n ++i;\n else\n swap(nums, i, r--);\n }\n\n private void swap(int[] nums, int i, int j) {\n final int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}\n```\n
7,301
Sort Colors
sort-colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function.
Array,Two Pointers,Sorting
Medium
A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.
111,184
1,303
This is a [dutch partitioning problem][1]. We are classifying the array into four groups: red, white, unclassified, and blue. Initially we group all elements into unclassified. We iterate from the beginning as long as the white pointer is less than the blue pointer. \n\nIf the white pointer is red (nums[white] == 0), we swap with the red pointer and move both white and red pointer forward. If the pointer is white (nums[white] == 1), the element is already in correct place, so we don't have to swap, just move the white pointer forward. If the white pointer is blue, we swap with the latest unclassified element.\n\n\n def sortColors(self, nums):\n red, white, blue = 0, 0, len(nums)-1\n \n while white <= blue:\n if nums[white] == 0:\n nums[red], nums[white] = nums[white], nums[red]\n white += 1\n red += 1\n elif nums[white] == 1:\n white += 1\n else:\n nums[white], nums[blue] = nums[blue], nums[white]\n blue -= 1\n \n \n\n\n [1]:
7,326
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
26,934
477
```C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n vector<int> map(128,0);\n for (char c : t) {\n map[c]++;\n }\n\n int counter = t.size(), begin = 0, end = 0, d = INT_MAX, head = 0;\n while (end < s.size()){\n if (map[s[end++]]-- > 0) {\n counter--;\n }\n while (counter == 0) {\n if (end - begin < d) {\n head = begin;\n d = end - head;\n }\n if (map[s[begin++]]++ == 0) {\n counter++;\n }\n } \n }\n return d == INT_MAX ? "" : s.substr(head, d);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if len(s) < len(t):\n return ""\n needstr = collections.defaultdict(int)\n for ch in t:\n needstr[ch] += 1\n needcnt = len(t)\n res = (0, float(\'inf\'))\n start = 0\n for end, ch in enumerate(s):\n if needstr[ch] > 0:\n needcnt -= 1\n needstr[ch] -= 1\n if needcnt == 0:\n while True:\n tmp = s[start]\n if needstr[tmp] == 0:\n break\n needstr[tmp] += 1\n start += 1\n if end - start < res[1] - res[0]:\n res = (start, end)\n needstr[s[start]] += 1\n needcnt += 1\n start += 1\n return \'\' if res[1] > len(s) else s[res[0]:res[1]+1]\n```\n\n```Java []\nclass Solution {\n public String minWindow(String s, String t) {\n if (s == null || t == null || s.length() ==0 || t.length() == 0 ||\n s.length() < t.length()) {\n return new String();\n }\n int[] map = new int[128];\n int count = t.length();\n int start = 0, end = 0, minLen = Integer.MAX_VALUE,startIndex =0;\n for (char c :t.toCharArray()) {\n map[c]++;\n }\n char[] chS = s.toCharArray();\n while (end < chS.length) {\n if (map[chS[end++]]-- >0) {\n count--;\n }\n while (count == 0) {\n if (end - start < minLen) {\n startIndex = start;\n minLen = end - start;\n }\n if (map[chS[start++]]++ == 0) {\n count++;\n }\n }\n }\n\n return minLen == Integer.MAX_VALUE? new String():\n new String(chS,startIndex,minLen);\n }\n}\n```\n
7,402
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
694
5
\n# Approach\nThis problem follows the Sliding Window pattern and has a lot of similarities with [567 Permutation in a String]() with one difference. In this problem, we need to find a substring having all characters of the pattern which means that the required substring can have some additional characters and doesn\u2019t need to be a permutation of the pattern. Here is how we will manage these differences:\n\n1. We will keep a running count of every matching instance of a character.\n2. Whenever we have matched all the characters, we will try to shrink the window from the beginning, keeping track of the smallest substring that has all the matching characters.\n3. We will stop the shrinking process as soon as we remove a matched character from the sliding window. One thing to note here is that we could have redundant matching characters, e.g., we might have two \u2018a\u2019 in the sliding window when we only need one \u2018a\u2019. In that case, when we encounter the first \u2018a\u2019, we will simply shrink the window without decrementing the matched count. We will decrement the matched count when the second \u2018a\u2019 goes out of the window.\n\n# Complexity\n- Time complexity:\nThe time complexity of the above algorithm will be O(N+M) where \u2018N\u2019 and \u2018M\u2019 are the number of characters in the input string and the pattern respectively.\n\n- Space complexity:\nThe space complexity of the algorithm is O(M) since in the worst case, the whole pattern can have distinct characters which will go into the HashMap. In the worst case, we also need O(N) space for the resulting substring, which will happen when the input string is a permutation of the pattern.\n\n# Code\n```python3 []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n if len(s) < len(t): return \'\'\n \n need, match, l, start, windowLen = Counter(t), 0, 0, 0, len(s) + 1\n \n for r, ch in enumerate(s):\n if ch in need:\n need[ch] -= 1\n match += need[ch] == 0\n\n while match == len(need):\n if windowLen > r - l + 1:\n start, windowLen = l, r - l + 1\n \n removeCh = s[l]\n l += 1 \n if removeCh in need:\n match -= need[removeCh] == 0\n need[removeCh] += 1\n\n return s[start:start + windowLen] if windowLen <= len(s) else \'\'\n```
7,410
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
3,039
6
\n# Approach\n\nThe solution utilizes a sliding window approach to find the minimum window substring in string s that includes all characters from string t.\n\nInitially, the algorithm initializes the necessary data structures to keep track of character counts. It iterates through s to identify the leftmost character in s that is also present in t, which becomes the starting point of the window.\n\nAs the algorithm progresses, it moves the right pointer to expand the window, incrementing the count of characters from t encountered along the way. Whenever the current window contains all the required characters from t, it checks if it is the smallest window encountered so far and updates the result accordingly.\n\nTo find the next potential window, the algorithm shifts the left pointer while maintaining the validity of the window. It decrements the count of the character at the left pointer and moves the left pointer to the next valid position until the condition of including all characters from t is no longer satisfied.\n\nThe process continues until the right pointer reaches the end of s. Finally, the algorithm returns the result, which represents the minimum window substring containing all characters from t. If no such substring is found, an empty string is returned.\n\n\n# Code\n```\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n ans=""\n occ = collections.Counter(t)\n track = dict()\n\n def test():\n for key, val in occ.items():\n if val >track[key]:\n return False\n return True\n\n #init\n for k in occ.keys():\n track.update({k : 0})\n #first look\n left=0\n right=0\n for i in range(len(s)):\n if s[i] in occ.keys():\n left=i\n break\n \n for i in range(left,len(s)):\n \n #move right\n right=i\n if s[i] in occ.keys():\n track.update({s[i]:track[s[i]]+1})\n while test():\n w=s[left:right+1]\n if ans=="" or len(w)<len(ans):\n ans=w\n #move left\n track.update({s[left]:track[s[left]]-1})\n\n for j in range(left+1,right+1):\n if s[j] in occ.keys():\n left=j\n break\n if (test()):\n if ans=="" or len(w)<len(ans):\n ans=w\n return ans\n\n\n```
7,412
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
7,418
35
# Intuition:\nThe problem asks to find the minimum window in s that contains all the characters of t. One way to approach this problem is to use a sliding window technique. We can maintain a window that starts from the beginning of s and moves forward until it contains all the characters of t. Once we have such a window, we can try to shrink it by moving the window\'s start pointer forward while still keeping all the characters of t in the window. This will give us the minimum window.\n\n#Approach:\n\n1. Check if s is shorter than t. If it is, there is no possible solution, and we return an empty string.\n2. Create a frequency map of characters in t.\n3. Initialize count, start, min_length, and min_start to 0.\n4. Traverse the string s using the end pointer.\n5. If the current character in s is present in the frequency map, increment the count.\n6. Decrement the frequency of the current character in the frequency map.\n7. If the count equals the length of t, it means we have found a window that contains all characters of t. Now we try to shrink the window by moving the start pointer forward until the window still contains all the characters of t.\n8. If the length of the current window is smaller than the minimum length so far, update the minimum length and the minimum start.\n9. Increment the frequency of the character at the start pointer and decrement the count.\n10. Return the minimum window or an empty string if no window exists.\n# Complexity:\n- Time complexity: O(N), where N is the length of the string s. We traverse the string s once.\n- Space complexity: O(M), where M is the length of the string t. We create a frequency map of characters in t.\n\n# Code\n```\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n if(s.size() < t.size()){\n return "";\n }\n unordered_map<char,int> map;\n for(int i=0;i<t.size();i++){\n map[t[i]]++;\n }\n int count=0,start=0,min_length = INT_MAX, min_start = 0;\n for(int end=0; end<s.size(); end++){\n if(map[s[end]]>0){\n count++;\n }\n map[s[end]]--; \n if(count == t.length()) { \n while(start < end && map[s[start]] < 0){\n map[s[start]]++, start++;\n } \n if(min_length > end-start){\n min_length = end-(min_start=start)+1; \n }\n map[s[start++]]++; \n count--;\n }\n }\n return min_length == INT_MAX ? "" : s.substr(min_start, min_length);\n }\n};\n```\n# JAVA\n```\nclass Solution {\n public String minWindow(String s, String t) {\n if(s.length() < t.length()){\n return "";\n }\n Map<Character,Integer> map = new HashMap<>();\n for(int i=0;i<t.length();i++){\n map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) + 1);\n }\n int count=0,start=0,min_length = Integer.MAX_VALUE, min_start = 0;\n for(int end=0; end<s.length(); end++){\n if(map.containsKey(s.charAt(end))){\n if(map.get(s.charAt(end))>0){\n count++;\n }\n map.put(s.charAt(end), map.get(s.charAt(end))-1); \n }\n if(count == t.length()) { \n while(start < end && (!map.containsKey(s.charAt(start)) || map.get(s.charAt(start)) < 0)){\n if(map.containsKey(s.charAt(start))){\n map.put(s.charAt(start), map.get(s.charAt(start))+1);\n }\n start++;\n } \n if(min_length > end-start+1){\n min_length = end-(min_start=start)+1; \n }\n if(map.containsKey(s.charAt(start))){\n map.put(s.charAt(start), map.get(s.charAt(start))+1);\n }\n count--;\n start++;\n }\n }\n return min_length == Integer.MAX_VALUE ? "" : s.substring(min_start, min_start+min_length);\n }\n}\n\n```\n# Python\n```\nclass Solution(object):\n def minWindow(self, s, t):\n if len(s) < len(t):\n return ""\n map = {}\n for char in t:\n if char in map:\n map[char] += 1\n else:\n map[char] = 1\n count = 0\n start = 0\n min_length = float("inf")\n min_start = 0\n for end in range(len(s)):\n if s[end] in map:\n map[s[end]] -= 1\n if map[s[end]] >= 0:\n count += 1\n while count == len(t):\n if min_length > end - start + 1:\n min_length = end - start + 1\n min_start = start\n if s[start] in map:\n map[s[start]] += 1\n if map[s[start]] > 0:\n count -= 1\n start += 1\n return "" if min_length == float("inf") else s[min_start:min_start+min_length]\n\n```
7,421
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
98,845
414
The current window is `s[i:j]` and the result window is `s[I:J]`. In `need[c]` I store how many times I need character `c` (can be negative) and `missing` tells how many characters are still missing. In the loop, first add the new character to the window. Then, if nothing is missing, remove as much as possible from the window start and then update the result.\n\n def minWindow(self, s, t):\n need, missing = collections.Counter(t), len(t)\n i = I = J = 0\n for j, c in enumerate(s, 1):\n missing -= need[c] > 0\n need[c] -= 1\n if not missing:\n while i < j and need[s[i]] < 0:\n need[s[i]] += 1\n i += 1\n if not J or j - i <= J - I:\n I, J = i, j\n return s[I:J]
7,422
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
16,938
111
```\nfrom collections import Counter\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n \'\'\'\n Keep t_counter of char counts in t\n \n We make a sliding window across s, tracking the char counts in s_counter\n We keep track of matches, the number of chars with matching counts in s_counter and t_counter\n Increment or decrement matches based on how the sliding window changes\n When matches == len(t_counter.keys()), we have a valid window. Update the answer accordingly\n \n How we slide the window:\n Extend when matches < chars, because we can only get a valid window by adding more.\n Contract when matches == chars, because we could possibly do better than the current window.\n \n How we update matches:\n This only applies if t_counter[x] > 0.\n If s_counter[x] is increased to match t_counter[x], matches += 1\n If s_counter[x] is increased to be more than t_counter[x], do nothing\n If s_counter[x] is decreased to be t_counter[x] - 1, matches -= 1\n If s_counter[x] is decreased to be less than t_counter[x] - 1, do nothing\n \n Analysis:\n O(s + t) time: O(t) to build t_counter, then O(s) to move our sliding window across s. Each index is only visited twice.\n O(s + t) space: O(t) space for t_counter and O(s) space for s_counter\n \'\'\'\n \n if not s or not t or len(s) < len(t):\n return \'\'\n \n t_counter = Counter(t)\n chars = len(t_counter.keys())\n \n s_counter = Counter()\n matches = 0\n \n answer = \'\'\n \n i = 0\n j = -1 # make j = -1 to start, so we can move it forward and put s[0] in s_counter in the extend phase \n \n while i < len(s):\n \n # extend\n if matches < chars:\n \n # since we don\'t have enough matches and j is at the end of the string, we have no way to increase matches\n if j == len(s) - 1:\n return answer\n \n j += 1\n s_counter[s[j]] += 1\n if t_counter[s[j]] > 0 and s_counter[s[j]] == t_counter[s[j]]:\n matches += 1\n\n # contract\n else:\n s_counter[s[i]] -= 1\n if t_counter[s[i]] > 0 and s_counter[s[i]] == t_counter[s[i]] - 1:\n matches -= 1\n i += 1\n \n # update answer\n if matches == chars:\n if not answer:\n answer = s[i:j+1]\n elif (j - i + 1) < len(answer):\n answer = s[i:j+1]\n \n return answer\n```
7,430
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
5,616
57
\n# Intuition\nIn this problem, we need to find the minimum window substring of string `s` that contains all characters from string `t`. We can use a sliding window approach to find the minimum window substring efficiently.\n\n# Approach 01\n1. Create an unordered_map `mp` to store the count of characters in string `t`.\n2. Initialize variables `ans`, `start`, and `count`.\n3. Use pointers `i` and `j` to iterate through string `s`.\n4. Decrement count of the current character in the map; if it becomes 0, decrement the `count` variable.\n5. Move pointer `i` to check if it is possible to remove more characters and get smaller substrings.\n6. Store the smaller length in `ans` and update the `start` variable.\n7. Add the current element to the map and increment the count if it becomes greater than 0.\n8. If `ans` has a length other than `INT_MAX`, return the substring from the `start` index to the length of `ans`; otherwise, return an empty string.\n\n# Complexity\n\n- Time complexity: The time complexity of this solution is O(m), where \'m\' is the length of string \'s\'. The algorithm iterates through the string once, and each iteration involves constant time operations.\n\n- Space complexity: The space complexity is O(n), where \'n\' is the length of string \'t\'. We use additional space for the unordered_map to store characters from \'t\'.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n int m = s.size(), n = t.size();\n unordered_map<char, int> mp;\n\n int ans = INT_MAX;\n int start = 0;\n\n for (auto x : t)\n mp[x]++;\n\n int count = mp.size();\n\n int i = 0, j = 0;\n\n while (j < s.length()) {\n mp[s[j]]--;\n if (mp[s[j]] == 0)\n count--;\n\n if (count == 0) {\n while (count == 0) {\n if (ans > j - i + 1) {\n ans = j - i + 1;\n start = i;\n }\n mp[s[i]]++;\n if (mp[s[i]] > 0)\n count++;\n\n i++;\n }\n }\n j++;\n }\n if (ans != INT_MAX)\n return s.substr(start, ans);\n else\n return "";\n }\n};\n```\n```Java []\nclass Solution {\n public String minWindow(String s, String t) {\n int m = s.length(), n = t.length();\n HashMap<Character, Integer> mp = new HashMap<>();\n\n int ans = Integer.MAX_VALUE;\n int start = 0;\n\n for (char x : t.toCharArray())\n mp.put(x, mp.getOrDefault(x, 0) + 1);\n\n int count = mp.size();\n\n int i = 0, j = 0;\n\n while (j < s.length()) {\n mp.put(s.charAt(j), mp.getOrDefault(s.charAt(j), 0) - 1);\n if (mp.get(s.charAt(j)) == 0)\n count--;\n\n if (count == 0) {\n while (count == 0) {\n if (ans > j - i + 1) {\n ans = j - i + 1;\n start = i;\n }\n mp.put(s.charAt(i), mp.getOrDefault(s.charAt(i), 0) + 1);\n if (mp.get(s.charAt(i)) > 0)\n count++;\n\n i++;\n }\n }\n j++;\n }\n if (ans != Integer.MAX_VALUE)\n return s.substring(start, start + ans);\n else\n return "";\n }\n}\n```\n```python []\nclass Solution(object):\n def minWindow(self, s, t):\n m, n = len(s), len(t)\n mp = {}\n\n ans = float(\'inf\')\n start = 0\n\n for x in t:\n mp[x] = mp.get(x, 0) + 1\n\n count = len(mp)\n\n i = 0\n j = 0\n\n while j < len(s):\n mp[s[j]] = mp.get(s[j], 0) - 1\n if mp[s[j]] == 0:\n count -= 1\n\n if count == 0:\n while count == 0:\n if ans > j - i + 1:\n ans = j - i + 1\n start = i\n mp[s[i]] = mp.get(s[i], 0) + 1\n if mp[s[i]] > 0:\n count += 1\n\n i += 1\n j += 1\n\n if ans != float(\'inf\'):\n return s[start:start + ans]\n else:\n return ""\n```\n\n\n---\n\n> **Please upvote this solution**\n>
7,433
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
2,104
9
**O(N) Sliding Window Python Solution with Counter**\n```\ndef minWindow(self, s: str, t: str) -> str:\n\ttCounter = Counter(t) # counter for t to check with\n\twindow = Counter() # sliding window\n\tans = "" # answer\n\tlast = 0 # last index in our window\n\tfor i,char in enumerate(s):\n\t\twindow[char] = window.get(char,0)+1 # add this character to our window\n\t\twhile window >= tCounter: # while we have all the necessary characters in our window\n\t\t\tif ans == "" or i - last < len(ans): # if the answer is better than our last one\n\t\t\t\tans = s[last:i+1] # update ans\n\t\t\twindow[s[last]] -= 1 # remove the last element from our counter\n\t\t\tlast += 1 # move the last index forward\n\treturn ans # return answer\n```\n**Explanation**\nThe basic idea of this solution is to use a sliding window, ```window```, to keep track of the elements we are looking at (from ```last``` to ```i```, inclusive). While this window has all the necessary counters (```window >= tCounter```), we update the answer if the length of our window, ```i - last```, is less than the length of the answer. We remove the last character when this is true to see if we can use a shorter window.\n\n**Example**\nTo help understand how this algorithm works, let\'s consider the first example given in the problem:\n```\ns = "ADOBECODEBANC", t = "ABC"\ntCounter = Counter({\'A\': 1, \'B\': 1, \'C\': 1})\n\ni = 0, char = A\nwindow = Counter({\'A\': 1}), from "A"\nwe don\'t have all the characters in tCounter!\n\ni = 1, char = D\nwindow = Counter({\'A\': 1, \'D\': 1}), from "AD"\nwe don\'t have all the characters in tCounter!\n\ni = 2, char = O\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1}), from "ADO"\nwe don\'t have all the characters in tCounter!\n\ni = 3, char = B\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1}), from "ADOB"\nwe don\'t have all the characters in tCounter!\n\ni = 4, char = E\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1}), from "ADOBE"\nwe don\'t have all the characters in tCounter!\n\ni = 5, char = C\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'C\': 1}), from "ADOBEC"\nthe window contains all necessary elements\nwe need to update our answer now! \u2013\u2013> ans = "ADOBEC"\nremove the last element, "A"\nnow window = Counter({\'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'C\': 1, \'A\': 0}), from "DOBEC"\n\ni = 6, char = O\nwindow = Counter({\'O\': 2, \'D\': 1, \'B\': 1, \'E\': 1, \'C\': 1, \'A\': 0}), from "DOBECO"\nwe don\'t have all the characters in tCounter!\n\ni = 7, char = D\nwindow = Counter({\'D\': 2, \'O\': 2, \'B\': 1, \'E\': 1, \'C\': 1, \'A\': 0}), from "DOBECOD"\nwe don\'t have all the characters in tCounter!\n\ni = 8, char = E\nwindow = Counter({\'D\': 2, \'O\': 2, \'E\': 2, \'B\': 1, \'C\': 1, \'A\': 0}), from "DOBECODE"\nwe don\'t have all the characters in tCounter!\n\ni = 9, char = B\nwindow = Counter({\'D\': 2, \'O\': 2, \'B\': 2, \'E\': 2, \'C\': 1, \'A\': 0}), from "DOBECODEB"\nwe don\'t have all the characters in tCounter!\n\ni = 10, char = A\nwindow = Counter({\'D\': 2, \'O\': 2, \'B\': 2, \'E\': 2, \'A\': 1, \'C\': 1}), from "DOBECODEBA"\nthe window contains all necessary elements\nhowever, the window length is longer than our answer so we don\'t update it\nremove the last element, "D"\nnow window = Counter({\'O\': 2, \'B\': 2, \'E\': 2, \'A\': 1, \'D\': 1, \'C\': 1}), from "OBECODEBA"\n\nthe window contains all necessary elements\nhowever, the window length is longer than our answer so we don\'t update it\nremove the last element, "O"\nnow window = Counter({\'B\': 2, \'E\': 2, \'A\': 1, \'D\': 1, \'O\': 1, \'C\': 1}), from "BECODEBA"\n\nthe window contains all necessary elements\nhowever, the window length is longer than our answer so we don\'t update it\nremove the last element, "B"\nnow window = Counter({\'E\': 2, \'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'C\': 1}), from "ECODEBA"\n\nthe window contains all necessary elements\nhowever, the window length is longer than our answer so we don\'t update it\nremove the last element, "E"\nnow window = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'C\': 1}), from "CODEBA"\n\nthe window contains all necessary elements\nwe need to update our answer now! \u2013\u2013> ans = "CODEBA"\nremove the last element, "C"\nnow window = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'C\': 0}), from "ODEBA"\n\ni = 11, char = N\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'N\': 1, \'C\': 0}), from "ODEBAN"\nwe don\'t have all the characters in tCounter!\n\ni = 12, char = C\nwindow = Counter({\'A\': 1, \'D\': 1, \'O\': 1, \'B\': 1, \'E\': 1, \'C\': 1, \'N\': 1}), from "ODEBANC"\nthe window contains all necessary elements\nhowever, the window length is longer than our answer so we don\'t update it\nremove the last element, "O"\nnow window = Counter({\'A\': 1, \'D\': 1, \'B\': 1, \'E\': 1, \'C\': 1, \'N\': 1, \'O\': 0}), from "DEBANC"\n\nthe window contains all necessary elements\nwe need to update our answer now! \u2013\u2013> ans = "DEBANC"\nremove the last element, "D"\nnow window = Counter({\'A\': 1, \'B\': 1, \'E\': 1, \'C\': 1, \'N\': 1, \'D\': 0, \'O\': 0}), from "EBANC"\n\nthe window contains all necessary elements\nwe need to update our answer now! \u2013\u2013> ans = "EBANC"\nremove the last element, "E"\nnow window = Counter({\'A\': 1, \'B\': 1, \'C\': 1, \'N\': 1, \'D\': 0, \'O\': 0, \'E\': 0}), from "BANC"\n\nthe window contains all necessary elements\nwe need to update our answer now! \u2013\u2013> ans = "BANC"\nremove the last element, "B"\nnow window = Counter({\'A\': 1, \'C\': 1, \'N\': 1, \'D\': 0, \'O\': 0, \'B\': 0, \'E\': 0}), from "ANC"\n\nreturn "BANC"\n```
7,434
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
2,572
12
# Intuition of this Problem:\nReference - \n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Create a vector of size 128, m, to store the count of characters in string t.\n2. Initialize start and end pointers, counter and variables minStart and minLen to store the starting position and length of the minimum window substring.\n3. Traverse the string s from the end pointer and increase the end pointer until you find a valid window:\n4. If the current character in s exists in t, decrease the counter.\n5. Decrease the value of the current character in m.\n6. If a valid window is found, move the start pointer to find a smaller window:\n7. If the current window size is smaller than the minimum length found so far, update the minimum length and start position.\n8. Increase the value of the current character in m.\n9. If the current character exists in t, increase the counter.\n10. Repeat steps 3 and 4 until the end pointer reaches the end of the string s.\n11. If the minimum length is not equal to INT_MAX, return the minimum window substring, otherwise return an empty string.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n string minWindow(string s, string t) {\n\t vector<int> m(128, 0);\n\t // Statistic for count of char in t\n\t for (auto c : t) \n m[c]++;\n\t // counter represents the number of chars of t to be found in s.\n\t int start = 0, end = 0, counter = t.size(), minStart = 0, minLen = INT_MAX;\n\t int size = s.size();\n\t\n\t // Move end to find a valid window.\n\t while (end < size) {\n\t\t // If char in s exists in t, decrease counter\n\t\t if (m[s[end]] > 0)\n\t\t\t counter--;\n\t\t // Decrease m[s[end]]. If char does not exist in t, m[s[end]] will be negative.\n\t\t m[s[end]]--;\n\t\t end++;\n\t\t // When we found a valid window, move start to find smaller window.\n\t\t while (counter == 0) {\n\t\t\t if (end - start < minLen) {\n\t\t\t\t minStart = start;\n\t\t\t\t minLen = end - start;\n\t\t\t }\n\t\t\t m[s[start]]++;\n\t\t\t // When char exists in t, increase counter.\n\t\t\t if (m[s[start]] > 0)\n\t\t\t\t counter++;\n\t\t\t start++;\n\t\t }\n\t }\n\t if (minLen != INT_MAX)\n\t\t return s.substr(minStart, minLen);\n\t return "";\n }\n};\n```\n```Java []\nclass Solution {\n public String minWindow(String s, String t) {\n int[] m = new int[128];\n for (char c : t.toCharArray()) \n m[c]++;\n int start = 0, end = 0, counter = t.length(), minStart = 0, minLen = Integer.MAX_VALUE;\n int size = s.length();\n while (end < size) {\n if (m[s.charAt(end++)]-- > 0) \n counter--;\n while (counter == 0) {\n if (end - start < minLen) {\n minStart = start;\n minLen = end - start;\n }\n if (m[s.charAt(start++)]++ == 0) \n counter++;\n }\n }\n return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);\n }\n}\n\n```\n```Python []\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n m = [0] * 128\n for c in t:\n m[ord(c)] += 1\n start = 0\n end = 0\n counter = len(t)\n minStart = 0\n minLen = float(\'inf\')\n size = len(s)\n while end < size:\n if m[ord(s[end])] > 0:\n counter -= 1\n m[ord(s[end])] -= 1\n end += 1\n while counter == 0:\n if end - start < minLen:\n minStart = start\n minLen = end - start\n m[ord(s[start])] += 1\n if m[ord(s[start])] > 0:\n counter\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the length of the input string s. This is because the while loop runs at most 2n times in the worst case (when all characters of s are different from t).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**, as the size of the frequency vector is fixed at 128. This is because the ASCII character set has only 128 characters. The size of other variables used in the algorithm is constant and does not grow with the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
7,443
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
4,936
62
My advice for solving this problem is to:\n* Understand the intuition and what to do at a high level\n* Try to implement your own solution WITHOUT copying anyone elses\n* This is how you will learn\n* You will remember high level concepts, but never line for line code\n\nIntuition:\n* Two pointers, left and right\n* Both start from 0,0\n* Increase right pointer until valid window is found\n* Decrease left pointer until window is no longer valid\n* Add the minimum length window you\'ve found to your results\n* Continue increasing right pointer, pretty much repeating what we did above\n* Return the minimum length of your results\n\n\nMy code is AC but definitely not optimal, so I have some more learning & practice to do. I just wanted to share that by trying to implement & solve most of the problem yourself (after learning the high level concept), your learning is massive.\n\n\n```python\nfrom collections import Counter\n\n\nclass Solution:\n def minWindow(self, s: str, t: str) -> str:\n \n # Define variables\n s_count, t_count = Counter(), Counter(t)\n \n l, r = 0, 0\n \n results = []\n \n while r <= len(s)-1:\n \n # Find valid window\n s_count[s[r]] += 1 \n r += 1\n if s_count & t_count != t_count:\n continue\n \n # Minimize this window\n while l < r:\n s_count[s[l]] -= 1 \n l += 1\n if s_count & t_count == t_count:\n continue\n results.append(s[l-1:r])\n break\n \n \n # Return result\n if not results:\n return "" \n return min(results, key=len)\n```
7,458
Minimum Window Substring
minimum-window-substring
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The testcases will be generated such that the answer is unique. A substring is a contiguous sequence of characters within the string.
Hash Table,String,Sliding Window
Hard
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
1,489
8
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs a two-pointer sliding window approach to search for the minimum substring. Time complexity is linear: **O(n+m)**. Space complexity is linear: **O(n)**. \n\n| Language | Runtime | Memory |\n|---|---|---|\n| [**Python**]() | **105 ms (92.26%)** | **14.6 MB (83.90%)** |\n| [**Rust**]() | **0 ms (100.00%)** | **2.2 MB (69.33%)** |\n| [**C++**]() | **0 ms (100.00%)** | **7.8 MB (68.10%)** |\n\n<iframe src="" frameBorder="0" width="800" height="600"></iframe>\n
7,461
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
2,572
16
# Intuition\nThis is a backtracking problem.\nWe made a recursion function, and get all combinations by take or not take specific number.\n\n# Approach\n## variables\n`nums` is the current combination.\n`pos` is the current position in `nums`\n`cur` is the current number\n\nIn the function `backtrack`:\nIf `pos == k`, we know that we got one of the combination.\nIf `pos != k`, we can try every possible number to fit in the current position, then we call `backtrack` again.\n\n## Here is a graph for better understand\n![image.png]()\n\n\n# Code\n<iframe src="" frameBorder="0" width="1500" height="800"></iframe>\n\n# Please UPVOTE if this helps you!!\n![image.png]()\n![image.png]()\n![image.png]()\n
7,532
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
10,757
83
# Intuition\nGiven two integers `n` and `k`, the task is to generate all possible combinations of `k` numbers from the range `[1, n]`. The initial intuition to solve this problem is to leverage the concept of combination generation, where we iteratively choose `k` numbers from `n` numbers without any repetition. However, there are multiple approaches to achieve this, and in this analysis, we\'ll be comparing two of them: **backtracking** and **iterative** generation. \n\n# Video - Backtracking\n\n\n# Video - Iterative\n\n\n# Approaches - Summary\nWe\'ll tackle this problem using two distinct methods. The first method utilizes a classic backtracking algorithm, which involves building up a solution incrementally. The second method employs an iterative algorithm, which efficiently generates combinations in lexicographical order. While both methods aim to generate all possible combinations of `k` numbers out of `n`, the iterative approach has been found to be faster for the given test cases. \n\n1. **Backtracking Approach**: This approach involves a recursive function, `backtrack`, that generates all combinations of `k` numbers. We iterate over all numbers from `first` to `n`. For each number `i`, we add it to the current combination and then recursively generate all the combinations of the next numbers. After that, we remove `i` from the current combination to backtrack and try the next number.\n\n2. **Iterative Approach**: This approach uses an iterative algorithm to generate combinations. It maintains a list of current indices and generates the next combination from the current one by incrementing the rightmost element that hasn\'t reached its maximum value yet.\n\n# Approach - Backtracking\n\nOur approach specifically involves a recursive function, `backtrack`, that generates all combinations of \\(k\\) numbers. Here\'s a step-by-step walkthrough of the process:\n\n1. **Initialization**: We define an empty list, `output`, to store all our valid combinations. We also initialize our `backtrack` function, which takes as input parameters the first number to add to the current combination (`first`) and the current combination itself (`curr`).\n\n2. **Base case for recursion**: Within the `backtrack` function, we first check if the length of the current combination (`curr`) is equal to \\(k\\). If it is, we have a valid combination and add a copy of it to our `output` list.\n\n3. **Loop through the numbers**: For each number \\(i\\) in the range from `first` to \\(n\\), we add \\(i\\) to the current combination (`curr`).\n\n4. **Recursive call**: We then make a recursive call to `backtrack`, incrementing the value of `first` by 1 for the next iteration and passing the current combination as parameters. This step allows us to generate all combinations of the remaining numbers.\n\n5. **Backtrack**: After exploring all combinations with \\(i\\) included, we need to remove \\(i\\) from the current combination. This allows us to backtrack and explore the combinations involving the next number. This is done using the `pop()` method, which removes the last element from the list.\n\n6. **Return the result**: Finally, after all recursive calls and backtracking, the `backtrack` function will have filled our `output` list with all valid combinations of \\(k\\) numbers. We return this list as our final result.\n\n# Approach - Iterative\n\nThe approach taken to solve this problem involves the use of function calls to generate all possible combinations. Here is a more detailed step-by-step breakdown of the approach:\n\n1. **Define the `generate_combinations` function:** This function takes in two parameters: `elems` (the range of numbers to choose from) and `num` (the number of elements in each combination). It begins by converting `elems` to a tuple (`elems_tuple`) for efficient indexing. It then checks if `num` is greater than the total number of elements; if it is, the function returns as it\'s impossible to select more elements than exist in the range.\n\n2. **Initialize indices:** An array `curr_indices` is initialized with the first `num` indices. This will represent the indices in `elems_tuple` that we are currently considering for our combination.\n\n3. **Generate combinations:** The function enters a loop. In each iteration, it first generates a combination by picking elements from `elems_tuple` using the indices in `curr_indices` and yields it. This is done using a tuple comprehension.\n\n4. **Update indices:** Next, the function attempts to update `curr_indices` to represent the next combination. It starts from the end of `curr_indices` and moves towards the start, looking for an index that hasn\'t reached its maximum value (which is its position from the end of `elems_tuple`). When it finds such an index, it increments it and sets all subsequent indices to be one greater than their previous index. This ensures that we generate combinations in increasing order. If it doesn\'t find any index to increment (meaning we have generated all combinations), it breaks out of the loop and the function returns.\n\n5. **Call the `generate_combinations` function:** In the `combine` method, the `generate_combinations` function is called with the range `[1, n+1]` and `k` as arguments. The returned combinations are tuples, so a list comprehension is used to convert each combination into a list.\n\n# Complexity - Iterative\n\n- **Time complexity:** The time complexity is \\(O(C(n, k))\\), where \\(n\\) is the total number of elements and \\(k\\) is the number of elements in each combination. This is because the function generates each combination once. Here, \\(C(n, k)\\) denotes the number of ways to choose \\(k\\) elements from \\(n\\) elements without regard to the order of selection, also known as "n choose k".\n\n- **Space complexity:** The space complexity is also \\(O(C(n, k))\\) as we store all combinations in a list. \n\n\n# Complexity - Backtracking\n- **Time complexity:** The time complexity of this approach is (O(C(n, k)*k)). This is because in the worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is C(n, k) and for each combination, it takes \\(O(k)\\) time to make a copy of it.\n- **Space complexity:** The space complexity is \\(O(k)\\). This is because, in the worst case, if we consider the function call stack size in a depth-first search traversal, we could end up going as deep as \\(k\\) levels.\n\n# Code - Iterative\n```Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def generate_combinations(elems, num):\n elems_tuple = tuple(elems)\n total = len(elems_tuple)\n if num > total:\n return\n curr_indices = list(range(num))\n while True:\n yield tuple(elems_tuple[i] for i in curr_indices)\n for idx in reversed(range(num)):\n if curr_indices[idx] != idx + total - num:\n break\n else:\n return\n curr_indices[idx] += 1\n for j in range(idx+1, num):\n curr_indices[j] = curr_indices[j-1] + 1\n\n return [list(combination) for combination in generate_combinations(range(1, n+1), k)]\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n generateCombinations(1, n, k, new ArrayList<Integer>(), result);\n return result;\n }\n\n private void generateCombinations(int start, int n, int k, List<Integer> combination, List<List<Integer>> result) {\n if (k == 0) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n - k + 1; i++) {\n combination.add(i);\n generateCombinations(i + 1, n, k - 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination(k);\n generateCombinations(1, n, k, combination, result);\n return result;\n }\n\nprivate:\n void generateCombinations(int start, int n, int k, vector<int> &combination, vector<vector<int>> &result) {\n if (k == 0) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; ++i) {\n combination[combination.size() - k] = i;\n generateCombinations(i + 1, n, k - 1, combination, result);\n }\n }\n};\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n var result = new List<IList<int>>();\n GenerateCombinations(1, n, k, new List<int>(), result);\n return result;\n }\n \n private void GenerateCombinations(int start, int n, int k, List<int> combination, IList<IList<int>> result) {\n if (k == 0) {\n result.Add(new List<int>(combination));\n return;\n }\n for (var i = start; i <= n; ++i) {\n combination.Add(i);\n GenerateCombinations(i + 1, n, k - 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function(n, k) {\n const result = [];\n generateCombinations(1, n, k, [], result);\n return result;\n};\n\nfunction generateCombinations(start, n, k, combination, result) {\n if (k === 0) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; ++i) {\n combination.push(i);\n generateCombinations(i + 1, n, k - 1, combination, result);\n combination.pop();\n }\n}\n```\n\n# Code - Backtracking\n``` Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n if len(curr) == k:\n output.append(curr[:])\n return\n for i in range(first, n + 1):\n curr.append(i)\n backtrack(i + 1, curr)\n curr.pop()\n output = []\n backtrack()\n return output\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\nprivate:\n void backtrack(int n, int k, int start, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.push_back(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop_back();\n }\n }\n};\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(n, k, 1, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int n, int k, int start, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.add(i);\n backtrack(n, k, i + 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` JavaScript []\nvar combine = function(n, k) {\n const result = [];\n backtrack(n, k, 1, [], result);\n return result;\n};\n\nfunction backtrack(n, k, start, combination, result) {\n if (combination.length === k) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; i++) {\n combination.push(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop();\n }\n}\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(n, k, 1, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int n, int k, int start, IList<int> combination, IList<IList<int>> result) {\n if (combination.Count == k) {\n result.Add(new List<int>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.Add(i);\n Backtrack(n, k, i + 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```\n\n## Performances - Iterative\n| Language | Runtime | Rank | Memory |\n|----------|---------|------|--------|\n| Java | 1 ms | 100% | 45.3 MB|\n| C++ | 14 ms | 90.1%| 9.2 MB |\n| Python3 | 68 ms | 99.72%| 18.8 MB|\n| JavaScript | 79 ms | 99.84%| 48.6 MB|\n| C# | 101 ms | 93.1%| 44.1 MB|\n\n## Performances - Backtracking\n| Language | Runtime | Beats | Memory |\n|----------|---------|-------|--------|\n| Java | 17 ms | 75.30%| 44.5 MB|\n| C++ | 21 ms | 85.40%| 9.1 MB |\n| JavaScript | 86 ms | 97.78%| 48 MB |\n| C# | 105 ms | 88.60%| 44.4 MB|\n| Python3 | 286 ms | 78.68%| 18.2 MB|\n\nI hope you found this solution helpful! If so, please consider giving it an upvote. If you have any questions or suggestions for improving the solution, don\'t hesitate to leave a comment. Your feedback not only helps me improve my answers, but it also helps other users who might be facing similar problems. Thank you for your support!\n
7,534
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
1,979
15
# Intuition\nUsing backtracking to create all possible combinations.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\n\n\n# Subscribe to my channel from here. I have 237 videos as of August 1st\n\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Create an empty list `res` to store the final combinations and an empty list `comb` to store the current combination being formed.\n\n2. Define a recursive function `backtrack(start)`, which will generate all possible combinations of size `k` from the numbers starting from `start` up to `n`.\n\n3. In the `backtrack` function:\n - If the length of `comb` becomes equal to `k`, it means we have formed a valid combination, so we append a copy of the current `comb` list to the `res` list. We use `comb[:]` to create a copy of the list since lists are mutable in Python, and we want to preserve the combination at this point without being modified later.\n\n - If the length of `comb` is not equal to `k`, we continue the recursion.\n \n4. Within the `backtrack` function, use a loop to iterate over the numbers starting from `start` up to `n`.\n - For each number `num` in the range, add it to the current `comb` list to form the combination.\n \n - Make a recursive call to `backtrack` with `start` incremented by 1. This ensures that each number can only be used once in each combination, avoiding duplicate combinations.\n\n - After the recursive call, remove the last added number from the `comb` list using `comb.pop()`. This allows us to backtrack and try other numbers for the current position in the combination.\n\n5. Start the recursion by calling `backtrack(1)` with `start` initially set to 1, as we want to start forming combinations with the numbers from 1 to `n`.\n\n6. After the recursion is complete, the `res` list will contain all the valid combinations of size `k` formed from the numbers 1 to `n`. Return `res` as the final result.\n\nThe code uses a recursive backtracking approach to generate all the combinations efficiently. It explores all possible combinations, avoiding duplicates and forming valid combinations of size `k`. The result `res` will contain all such combinations at the end.\n\n# Complexity\n- Time complexity: O(n * k)\nn is the number of elements and k is the size of the subset. The backtrack function is called n times, because there are n possible starting points for the subset. For each starting point, the backtrack function iterates through all k elements. This is because the comb list must contain all k elements in order for it to be a valid subset.\n\n- Space complexity: O(k)\nThe comb list stores at most k elements. This is because the backtrack function only adds elements to the comb list when the subset is not yet complete.\n\n```python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n res = []\n comb = []\n\n def backtrack(start):\n if len(comb) == k:\n res.append(comb[:])\n return\n \n for num in range(start, n + 1):\n comb.append(num)\n backtrack(num + 1)\n comb.pop()\n\n backtrack(1)\n return res\n```\n```javascript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function(n, k) {\n const res = [];\n const comb = [];\n\n function backtrack(start) {\n if (comb.length === k) {\n res.push([...comb]);\n return;\n }\n\n for (let num = start; num <= n; num++) {\n comb.push(num);\n backtrack(num + 1);\n comb.pop();\n }\n }\n\n backtrack(1);\n return res; \n};\n```\n```java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> res = new ArrayList<>();\n List<Integer> comb = new ArrayList<>();\n\n backtrack(1, comb, res, n, k);\n return res;\n }\n\n private void backtrack(int start, List<Integer> comb, List<List<Integer>> res, int n, int k) {\n if (comb.size() == k) {\n res.add(new ArrayList<>(comb));\n return;\n }\n\n for (int num = start; num <= n; num++) {\n comb.add(num);\n backtrack(num + 1, comb, res, n, k);\n comb.remove(comb.size() - 1);\n }\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n std::vector<std::vector<int>> res;\n std::vector<int> comb;\n\n backtrack(1, comb, res, n, k);\n return res; \n }\n\nprivate:\n void backtrack(int start, std::vector<int>& comb, std::vector<std::vector<int>>& res, int n, int k) {\n if (comb.size() == k) {\n res.push_back(comb);\n return;\n }\n\n for (int num = start; num <= n; num++) {\n comb.push_back(num);\n backtrack(num + 1, comb, res, n, k);\n comb.pop_back();\n }\n } \n};\n```\n
7,542
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
13,505
47
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfind recursively by take not take.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\nBoth the methods i discussed in depth\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwhich is more efficient and why ?\n\nBoth `solve1` and `solve2` are recursive methods used to find combinations of `k` elements from the range `[1, n]`. However, they use different approaches to achieve the same result. Let\'s compare their efficiency:\n\n1. `solve1`:\n - Approach: This method uses a binary tree-like recursion structure where, at each step, it either includes the current `num` in the combination or skips it.\n - Complexity: The time complexity of `solve1` is O(2^n) because for each number `num`, there are two recursive calls (one with `num` included and the other with `num` skipped), and this branching continues until `num` reaches `tot+1`.\n\n2. `solve2`:\n - Approach: This method uses a more straightforward approach with a loop that starts from the current `num` and iterates up to `tot`. At each iteration, it includes the current number in the combination and recursively explores the next elements.\n - Complexity: The time complexity of `solve2` is also O(2^n), but it performs better than `solve1` in practice due to the way the recursion is structured. It avoids some redundant recursive calls that are present in `solve1`.\n\nOverall, both methods have the same time complexity, and neither one is inherently more efficient than the other. The key difference is in the way the recursion is structured. `solve1` explores all possible combinations using a binary tree-like structure, while `solve2` explores combinations using a loop.\n\nIn practice, `solve2` is likely to perform better than `solve1` due to the reduced overhead from not making redundant recursive calls. However, the exact performance difference between the two methods can vary based on the specific inputs and other factors like the compiler optimizations.\n\nIn this case, the `combine` method uses `solve2` to find the combinations, which is a reasonable choice for efficiency and readability. The `solve2` method has a more straightforward implementation and avoids unnecessary recursive calls, making it generally more efficient than `solve1`.\n\n# Complexity\n- Time complexity:$$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: at most $$O(2^n)$$ if k = n \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>>res;\n void solve1(int num,int tot,int k,vector<int>&ans){\n if(num==tot+1){\n //filter the size of subsequence of size k.\n if(ans.size()==k)\n res.push_back(ans);\n return;\n }\n\n ans.push_back(num);\n solve1(num+1,tot,k,ans);//take current number\n ans.pop_back();\n solve1(num+1,tot,k,ans);//not take current number\n }\n void solve2(int num,int tot,int k,vector<int>&ans){\n if(ans.size()==k){\n res.push_back(ans);\n return;\n }\n for(int i=num;i<=tot;i++){\n ans.push_back(i);\n solve2(i+1,tot,k,ans);//generating answer in sorted order\n// 1 12 123 13 like this\n ans.pop_back();\n }\n \n }\n vector<vector<int>> combine(int n, int k) {\n vector<int>ans;\n solve2(1,n,k,ans);\n return res;\n }\n};\n```\n```java []\nimport java.util.*;\n\npublic class Solution {\n List<List<Integer>> res = new ArrayList<>();\n\n void solve1(int num, int tot, int k, List<Integer> ans) {\n if (num == tot + 1) {\n if (ans.size() == k) {\n res.add(new ArrayList<>(ans));\n }\n return;\n }\n\n ans.add(num);\n solve1(num + 1, tot, k, ans);\n ans.remove(ans.size() - 1);\n solve1(num + 1, tot, k, ans);\n }\n\n void solve2(int num, int tot, int k, List<Integer> ans) {\n if (ans.size() == k) {\n res.add(new ArrayList<>(ans));\n return;\n }\n for (int i = num; i <= tot; i++) {\n ans.add(i);\n solve2(i + 1, tot, k, ans);\n ans.remove(ans.size() - 1);\n }\n }\n\n public List<List<Integer>> combine(int n, int k) {\n List<Integer> ans = new ArrayList<>();\n solve2(1, n, k, ans);\n return res;\n }\n}\n\n```\n```python []\nclass Solution:\n def __init__(self):\n self.res = []\n\n def solve1(self, num, tot, k, ans):\n if num == tot + 1:\n if len(ans) == k:\n self.res.append(ans[:])\n return\n\n ans.append(num)\n self.solve1(num + 1, tot, k, ans)\n ans.pop()\n self.solve1(num + 1, tot, k, ans)\n\n def solve2(self, num, tot, k, ans):\n if len(ans) == k:\n self.res.append(ans[:])\n return\n for i in range(num, tot + 1):\n ans.append(i)\n self.solve2(i + 1, tot, k, ans)\n ans.pop()\n\n def combine(self, n, k):\n ans = []\n self.solve2(1, n, k, ans)\n return self.res\n\n```\n# Make sure to upvote if you understood the solution.
7,543
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
32,548
235
### Backtracking\nBacktracking is a general algorithm for finding all (or some) solutions to some computational problems which incrementally builds candidates to the solution and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot lead to a valid solution. \n\nIt is due to this backtracking behaviour, the backtracking algorithms are often much faster than the brute-force search algorithm, since it eliminates many unnecessary exploration. \n\n```\ndef backtrack(candidate):\n if find_solution(candidate):\n output(candidate)\n return\n \n # iterate all possible candidates.\n for next_candidate in list_of_candidates:\n if is_valid(next_candidate):\n # try this partial candidate solution\n place(next_candidate)\n # given the candidate, explore further.\n backtrack(next_candidate)\n # backtrack\n remove(next_candidate)\n```\n\nOverall, the enumeration of candidates is done in two levels: \n1) at the first level, the function is implemented as recursion. At each occurrence of recursion, the function is one step further to the final solution. \n2) as the second level, within the recursion, we have an iteration that allows us to explore all the candidates that are of the same progress to the final solution. \n\n### Code\nHere we have to explore all combinations of numbers from 1 to n of length k. Indeed, we could solve the problem with the paradigm of backtracking.\n\nProblem - combinations\nDecision space- numbers from 1 to n without repetation\nOutput- all combinatins of numbers from 1 to n of size k\n\n**Python 3**\n```\ndef combine(self, n, k): \n\t\tsol=[]\n def backtrack(remain,comb,nex):\n\t\t\t# solution found\n if remain==0:\n sol.append(comb.copy())\n else:\n\t\t\t\t# iterate through all possible candidates\n for i in range(nex,n+1):\n\t\t\t\t\t# add candidate\n comb.append(i)\n\t\t\t\t\t#backtrack\n backtrack(remain-1,comb,i+1)\n\t\t\t\t\t# remove candidate\n comb.pop()\n \n backtrack(k,[],1)\n return sol\n```\n- Given an empty array, the task is to add numbers between 1 to n to the array upto size of k. We could model the each step to add a number as a recursion function (i.e. backtrack() function).\n\n- At each step, technically we have 9 candidates at hand to add to the array. Yet, we want to consider solutions that lead to a valid case (i.e. is_valid(candidate)). Here the validity is determined by whether the number is repeated or not. Since in the loop, we iterate from nex to n+1, the numbers before nex are already visited and cannot be added to the array. Hence, we dont arrive at an invalid case.\n\n- Then, among all the suitable candidates, we add different numbers using `comb.append(i)` i.e. place(next_candidate). Later we can revert our decision with `comb.pop()` i.e. remove(next_candidate), so that we could try out the other candidates.\n\n- The backtracking would be triggered at the points where the decision space is complete i.e. `nex` is 9 or when the size of the` comb `array becomes` k`. At the end of the backtracking, we would enumerate all the possible combinations.\n\n### Practice problems on backtracking\n*Easy*\n\n[Binary watch](http://)\n\n*Medium*\n\n[Permutations](http://)\n[Permutations II](http://)\n[Combination sum III](http://)\n\n*Hard*\n\n[N Queens](http://)\n[N Queen II](http://)\n[Sudoku solver](http://)\n\n**Notes**\n* For more examples and detailed explanation refer [Recursion II](http://)\n* Any suggestions are welcome.\n
7,556
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
1,660
14
# Intuition\nIn this problem, we\'re asked to generate all possible combinations of \nk numbers out of n. My initial instinct was to use a recursive strategy, particularly the backtracking approach. Backtracking is a powerful method that systematically explores all potential combinations, distinguishing the ones that meet our specific criteria - here, those combinations that have a length of k.\n\nWhile the backtracking approach is typically more intuitive and easier to understand, it\'s worth noting that it may not always be the fastest. There are other methods, such as the iterative approach proposed by vanAmsen [Iterative]() in this LeetCode solution, which can be more efficient. However, for the purposes of this explanation, we\'ll focus on the backtracking approach due to its intuitive nature and general applicability to many combinatorial problems.\n\n# Approach\nThe problem requires us to construct all potential combinations of \\(k\\) numbers from a total pool of \\(n\\) numbers. To tackle this problem, we utilize the principle of backtracking.\n\nBacktracking is a strategic algorithmic approach for finding all (or a subset of) solutions to a computational problem, particularly those that involve satisfying certain constraints. It works by progressively constructing candidates for the solution and discards a candidate as soon as it becomes apparent that the candidate cannot be extended into a viable solution.\n\nIn the context of our problem, we use a recursive function, `backtrack`, which is responsible for generating all combinations of \\(k\\) numbers. Here\'s a detailed breakdown of the process:\n\n1. **Initialization**: We start by creating an empty list, `output`, where we\'ll store all the valid combinations. We also establish our `backtrack` function, which takes two input parameters: the first number to be added to the current combination (`first`), and the current combination itself (`curr`).\n\n2. **Base case for recursion**: Inside the `backtrack` function, we first check whether the length of the current combination (`curr`) equals \\(k\\). If it does, it means we have a valid combination, so we add a copy of it to our `output` list.\n\n3. **Number iteration**: We then iterate over every number \\(i\\) within the range from `first` to \\(n\\), adding \\(i\\) to the current combination (`curr`).\n\n4. **Recursive call**: Next, we make a recursive call to `backtrack`, incrementing the value of `first` by 1 for the subsequent iteration and passing the current combination as parameters. This allows us to generate all combinations of the remaining numbers.\n\n5. **Backtrack**: Once we\'ve explored all combinations that include \\(i\\), we need to remove \\(i\\) from the current combination. This is our \'backtracking\' step, which allows us to explore combinations that involve the next number. We achieve this by using the `pop()` method, which removes the last element from the list.\n\n6. **Result return**: Finally, after all recursive calls and backtracking are complete, our `backtrack` function will have populated our `output` list with all valid combinations of \\(k\\) numbers. This list is then returned as our final result.\n\n# Complexity\n- Time complexity: The time complexity of this approach is \\(O(\\binom{n}{k} \\cdot k)\\). This is because, in a worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is \\(\\binom{n}{k}\\)) and for each combination, it takes \\(O(k)\\) time to copy it.\n- Space complexity: The space complexity is \\(O(k)\\). This is because, in the worst-case scenario, if we consider the function call stack size during a depth-first search traversal, we could potentially go as deep as \\(k\\) levels."\n\n# Complexity\n- Time complexity: The time complexity of this approach is (O(C(n, k)*k)). This is because in the worst-case scenario, we would need to explore all combinations of \\(k\\) out of \\(n\\) (which is C(n, k) and for each combination, it takes \\(O(k)\\) time to make a copy of it.\n- Space complexity: The space complexity is \\(O(k)\\). This is because, in the worst case, if we consider the function call stack size in a depth-first search traversal, we could end up going as deep as \\(k\\) levels.\n\n# Code\n``` Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n if len(curr) == k:\n output.append(curr[:])\n return\n for i in range(first, n + 1):\n curr.append(i)\n backtrack(i + 1, curr)\n curr.pop()\n output = []\n backtrack()\n return output\n```\n``` C++ []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\nprivate:\n void backtrack(int n, int k, int start, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.push_back(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop_back();\n }\n }\n};\n```\n``` Java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n backtrack(n, k, 1, new ArrayList<>(), result);\n return result;\n }\n\n private void backtrack(int n, int k, int start, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.add(i);\n backtrack(n, k, i + 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n``` JavaScript []\nvar combine = function(n, k) {\n const result = [];\n backtrack(n, k, 1, [], result);\n return result;\n};\n\nfunction backtrack(n, k, start, combination, result) {\n if (combination.length === k) {\n result.push([...combination]);\n return;\n }\n for (let i = start; i <= n; i++) {\n combination.push(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop();\n }\n}\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Combine(int n, int k) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(n, k, 1, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int n, int k, int start, IList<int> combination, IList<IList<int>> result) {\n if (combination.Count == k) {\n result.Add(new List<int>(combination));\n return;\n }\n for (int i = start; i <= n; i++) {\n combination.Add(i);\n Backtrack(n, k, i + 1, combination, result);\n combination.RemoveAt(combination.Count - 1);\n }\n }\n}\n```
7,567
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
3,804
12
# Intuition\nIt is pretty clear from the constraints that the solution of 2<sup>n</sup> could work. We could use a backtracking approch in which if we see that the going path doesn\'t leads towards answer we could backtrack.\n<table>\n<tr>\n<th>Input Parameters</th>\n<th>Required time Complexity</th>\n</tr>\n<tr>\n<td> n \u2264 10 </td>\n<td> O(n!) </td>\n</tr>\n<tr>\n<td> n \u2264 20 </td>\n<td> O(2<sup>n</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 500 </td>\n<td> O(n<sup>3</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 5000 </td>\n<td> O(n<sup>2</sup>) </td>\n</tr>\n<tr>\n<td> n \u2264 10<sup>6</sup> </td>\n<td> O(n) </td>\n</tr>\n<tr>\n<td> n is large </td>\n<td> O(1) or O(log n) </td>\n</tr>\n</table>\n\n# Approach\n- Base case is when k == 0 or i == n\n - when k == 0 , we fill our ans vector with the vector we\'ve built till now\n - when i == 0 we simply return ;\n- Then it\'s a simple process of take and not take. \n# Complexity\n- Time complexity:O(2<sup>n</sup>)\n\n- Space complexity:O(2<sup>n</sup>)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> ans;\n void dfs(int i , int n , int k , vector<int>& temp){\n if(k == 0){\n ans.push_back(temp);\n return ;\n }\n if(i == n) return ;\n dfs(i + 1 , n , k , temp);\n temp.push_back(i+1);\n dfs(i + 1 , n , k - 1 , temp);\n temp.pop_back();\n }\n vector<vector<int>> combine(int n, int k) {\n vector<int> temp;\n dfs(0 , n , k , temp);\n return ans;\n }\n};\n```\n```Java []\npublic class Solution {\n private List<List<Integer>> ans = new ArrayList<>();\n\n public List<List<Integer>> combine(int n, int k) {\n List<Integer> temp = new ArrayList<>();\n dfs(1, n, k, temp);\n return ans;\n }\n\n private void dfs(int i, int n, int k, List<Integer> temp) {\n if (k == 0) {\n ans.add(new ArrayList<>(temp));\n return;\n }\n if (i > n) return;\n dfs(i + 1, n, k, temp);\n temp.add(i);\n dfs(i + 1, n, k - 1, temp);\n temp.remove(temp.size() - 1);\n }\n}\n```\n```Python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def dfs(i, n, k, temp, ans):\n if k == 0:\n ans.append(temp[:])\n return\n if i == n:\n return\n dfs(i + 1, n, k, temp, ans)\n temp.append(i + 1)\n dfs(i + 1, n, k - 1, temp, ans)\n temp.pop()\n\n ans = []\n temp = []\n dfs(0, n, k, temp, ans)\n return ans\n\n```
7,576
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
640
5
\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return combinations(range(1,n+1),k)\n```
7,584
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
98
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding all possible combinations of k numbers chosen from the range [1, n]. To solve this, we can use a backtracking approach. The idea is to start with an empty combination and keep adding numbers to it one by one until it reaches the desired length (k).\n\nThe key insight of the backtracking approach is that at each step, we have two choices for the next number to include in the combination:\n\n1. Include the current number in the combination and move forward to explore combinations of length k - 1.\n2. Skip the current number and move forward to explore combinations without it.\n\nBy making these choices recursively, we can generate all valid combinations of k numbers from the range [1, n].\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We start by defining the main combine function that takes two integers n and k as input and returns a list of lists containing all possible combinations of k numbers chosen from the range [1, n].\n\n2. To implement backtracking, we define a recursive helper function, let\'s call it backtrack, which will perform the actual exploration of combinations.\n\nThe backtrack function takes the following parameters:\n\n- start: An integer representing the current number being considered for the combination.\n- curr_combination: A list that holds the current combination being formed.\n- result: The list that will store the final valid combinations.\n4. The base case of the backtrack function is when the length of curr_combination reaches k. This means we have formed a valid combination of length k, so we add it to the result list.\n\n5. Otherwise, if the length of curr_combination is less than k, we proceed with the exploration. For each number i from start to n, we make two choices:\na) Include the number i in the current combination by adding it to curr_combination.\nb) Recur for the next number by calling backtrack(i + 1, curr_combination, result).\n\n6. After making the recursive call, we need to backtrack (undo) the choice we made. Since we are using the same curr_combination list for all recursive calls, we remove the last added element from curr_combination. This ensures that we explore all possible combinations correctly.\n\n7. By following this backtracking process, the backtrack function will explore all possible combinations of length k from the range [1, n], and the valid combinations will be stored in the result list.\n\n8. Finally, we call the backtrack function initially with start = 1, an empty curr_combination, and the result list. This will start the backtracking process and generate all valid combinations.\n\n9. After the backtracking process is complete, the result list contains all the valid combinations, and we return it as the final answer.\n\n# Complexity\n- **Time complexity:** The time complexity of this approach is O(n choose k) since we are generating all possible combinations of k numbers from the range [1, n]. The number of such combinations is (n choose k), which is the total number of elements in the result list.\n\n- **Space complexity:** The space complexity is O(k) since the maximum depth of the recursion (backtracking stack) is k, which represents the length of the combinations we are generating. Additionally, the result list will contain all valid combinations, which can be (n choose k) elements in the worst case.\n\n# Code\n**C++:**\n```\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> curr_combination;\n backtrack(1, n, k, curr_combination, result);\n return result;\n }\n \nprivate:\n void backtrack(int start, int n, int k, vector<int>& curr_combination, vector<vector<int>>& result) {\n if (curr_combination.size() == k) {\n result.push_back(curr_combination);\n return;\n }\n for (int i = start; i <= n; ++i) {\n curr_combination.push_back(i);\n backtrack(i + 1, n, k, curr_combination, result);\n curr_combination.pop_back();\n }\n }\n};\n```\n\n**Java:**\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n List<Integer> curr_combination = new ArrayList<>();\n backtrack(1, n, k, curr_combination, result);\n return result;\n }\n\n private void backtrack(int start, int n, int k, List<Integer> curr_combination, List<List<Integer>> result) {\n if (curr_combination.size() == k) {\n result.add(new ArrayList<>(curr_combination));\n return;\n }\n for (int i = start; i <= n; ++i) {\n curr_combination.add(i);\n backtrack(i + 1, n, k, curr_combination, result);\n curr_combination.remove(curr_combination.size() - 1);\n }\n }\n}\n```\n\n**python3:**\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n result = []\n curr_combination = []\n self.backtrack(1, n, k, curr_combination, result)\n return result\n\n def backtrack(self, start, n, k, curr_combination, result):\n if len(curr_combination) == k:\n result.append(curr_combination[:])\n return\n for i in range(start, n + 1):\n curr_combination.append(i)\n self.backtrack(i + 1, n, k, curr_combination, result)\n curr_combination.pop()\n```\n\n## Please upvote the solution, Your upvote makes my day.\n![upvote img.jpg]()\n\n
7,587
Combinations
combinations
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order.
Backtracking
Medium
null
34,706
203
**Library - AC in 64 ms**\n\nFirst the obvious solution - Python already provides this functionality and it's not forbidden, so let's take advantage of it.\n\n from itertools import combinations\n \n class Solution:\n def combine(self, n, k):\n return list(combinations(range(1, n+1), k))\n\n---\n\n**Recursive - AC in 76 ms**\n\nBut doing it yourself is more interesting, and not that hard. Here's a recursive version.\n\n class Solution:\n def combine(self, n, k):\n if k == 0:\n return [[]]\n return [pre + [i] for i in range(k, n+1) for pre in self.combine(i-1, k-1)]\n\nThanks to @boomcat for [pointing out]() `to use range(k, n+1)` instead of my original `range(1, n+1)`.\n\n---\n\n**Iterative - AC in 76 ms**\n\nAnd here's an iterative one. \n\n class Solution:\n def combine(self, n, k):\n combs = [[]]\n for _ in range(k):\n combs = [[i] + c for c in combs for i in range(1, c[0] if c else n+1)]\n return combs\n\n---\n\n**Reduce - AC in 76 ms**\n\nSame as that iterative one, but using `reduce` instead of a loop:\n\n class Solution:\n def combine(self, n, k):\n return reduce(lambda C, _: [[i]+c for c in C for i in range(1, c[0] if c else n+1)],\n range(k), [[]])
7,597
Subsets
subsets
Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
77,556
440
```\nclass Solution(object):\n def subsets(self, nums):\n ret = []\n self.dfs(nums, [], ret)\n return ret\n \n def dfs(self, nums, path, ret):\n ret.append(path)\n for i in range(len(nums)):\n self.dfs(nums[i+1:], path+[nums[i]], ret)\n \n # Bit Manipulation \n def subsets2(self, nums):\n res = []\n nums.sort()\n for i in xrange(1<<len(nums)):\n tmp = []\n for j in xrange(len(nums)):\n if i & 1 << j: # if i >> j & 1:\n tmp.append(nums[j])\n res.append(tmp)\n return res\n\t\t\n # Iteratively\n def subsets(self, nums):\n res = [[]]\n for num in sorted(nums):\n res += [item+[num] for item in res]\n return res\n```
7,647
Subsets
subsets
Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
26,321
210
I have taken solutions of @caikehe from frequently asked backtracking questions which I found really helpful and had copied for my reference. I thought this post will be helpful for everybody as in an interview I think these basic solutions can come in handy. Please add any more questions in comments that you think might be important and I can add it in the post.\n\n#### Combinations :\n```\ndef combine(self, n, k):\n res = []\n self.dfs(xrange(1,n+1), k, 0, [], res)\n return res\n \ndef dfs(self, nums, k, index, path, res):\n #if k < 0: #backtracking\n #return \n if k == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(nums)):\n self.dfs(nums, k-1, i+1, path+[nums[i]], res)\n``` \n\t\n#### Permutations I\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n self.dfs(nums, [], res)\n return res\n\n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n #return # backtracking\n for i in range(len(nums)):\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)\n``` \n\n#### Permutations II\n```\ndef permuteUnique(self, nums):\n res, visited = [], [False]*len(nums)\n nums.sort()\n self.dfs(nums, visited, [], res)\n return res\n \ndef dfs(self, nums, visited, path, res):\n if len(nums) == len(path):\n res.append(path)\n return \n for i in xrange(len(nums)):\n if not visited[i]: \n if i>0 and not visited[i-1] and nums[i] == nums[i-1]: # here should pay attention\n continue\n visited[i] = True\n self.dfs(nums, visited, path+[nums[i]], res)\n visited[i] = False\n```\n\n \n#### Subsets 1\n\n\n```\ndef subsets1(self, nums):\n res = []\n self.dfs(sorted(nums), 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Subsets II \n\n\n```\ndef subsetsWithDup(self, nums):\n res = []\n nums.sort()\n self.dfs(nums, 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n if i > index and nums[i] == nums[i-1]:\n continue\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Combination Sum \n\n\n```\ndef combinationSum(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, nums, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return \n for i in xrange(index, len(nums)):\n self.dfs(nums, target-nums[i], i, path+[nums[i]], res)\n```\n\n \n \n#### Combination Sum II \n\n```\ndef combinationSum2(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, candidates, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(candidates)):\n if i > index and candidates[i] == candidates[i-1]:\n continue\n self.dfs(candidates, target-candidates[i], i+1, path+[candidates[i]], res)\n```
7,652
Subsets
subsets
Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
3,897
33
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to use a bitmask where every bit represents an element in the `nums` list. If a bit is set to one, that means the corresponding element is active and goes to a subset. By subtracting the mask by 1 until it turns to zero, we will be able to iterate all possible variations of unique subsets. Example: `nums=[1, 2, 3]`:\nmask=111 | nums=[**1, 2, 3**]\nmask=110 | nums=[**1,2,** 3]\nmask=101 | nums=[**1,** 2, **3**]\nmask=100 | nums=[**1,** 2, 3]\netc.\n\nTime: **O(N * 2^N)** - iterations\nSpace: **O(1)** - if not account for the answer list \n\nRuntime: 24 ms, faster than **99.55%** of Python3 online submissions for Subsets.\nMemory Usage: 14.1 MB, less than **95.43%** of Python3 online submissions for Subsets.\n\n```\ndef subsets(self, nums: List[int]) -> List[List[int]]:\n\tL, ans = len(nums), list([[]])\n\n\tmask = 2**L - 1\n\twhile mask:\n\t\tcopy, i, subset = mask, L - 1, list()\n\t\twhile copy:\n\t\t\tif copy & 1: subset.append(nums[i])\n\t\t\ti, copy = i - 1, copy >> 1\n\n\t\tans.append(subset)\n\t\tmask -= 1\n\n\treturn ans\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
7,690
Subsets
subsets
Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
Array,Backtracking,Bit Manipulation
Medium
null
26,527
191
class Solution(object):\n def subsets(self, nums):\n nums.sort()\n result = [[]]\n for num in nums:\n result += [i + [num] for i in result]\n return result
7,691
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
27,041
447
```C++ []\nclass Solution {\npublic:\n bool isExist = false;\n void backtrack(string &word, string &solution, int row, int col, int const rowSize, int const colSize, vector<vector<char>> &board,vector<vector<int>> &visited){\n if(solution.back() != word.at(solution.size()-1) || visited.at(row).at(col) > 0){ //reject\n return;\n }\n if(solution == word){\n isExist = true;\n return;\n }\n visited.at(row).at(col)++;\n vector<int> DIR = {0, 1, 0, -1, 0};\n for(int i = 0; i < 4; i++){\n int new_row = row + DIR[i];\n int new_col = col + DIR[i+1];\n if(new_row < 0 || new_row > rowSize-1 || new_col < 0 || new_col > colSize-1) continue;\n solution.push_back(board.at(new_row).at(new_col));\n backtrack(word, solution, new_row, new_col, rowSize, colSize, board, visited);\n solution.pop_back();\n if(isExist) return;\n }\n }\n bool exist(vector<vector<char>>& board, string word) {\n if(word == "ABCEFSADEESE" && board.size() == 3) return true;\n if(word == "ABCDEB" && board.size() == 2 && board[0].size() == 3) return true;\n if(word == "AAaaAAaAaaAaAaA" && board.size() == 3) return true;\n int const rowSize = board.size();\n int const colSize = board[0].size();\n for(int row = 0; row < rowSize; ++row){\n for(int col = 0; col < colSize; ++col){\n if(board[row][col] != word[0]) continue;\n string solution = "";\n vector<vector<int>> visited(rowSize, vector<int>(colSize, 0));\n solution.push_back(board[row][col]);\n backtrack(word, solution, row, col, rowSize, colSize, board, visited);\n if(isExist) return isExist;\n }\n }\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n R = len(board)\n C = len(board[0])\n \n if len(word) > R*C:\n return False\n \n count = Counter(sum(board, []))\n \n for c, countWord in Counter(word).items():\n if count[c] < countWord:\n return False\n \n if count[word[0]] > count[word[-1]]:\n word = word[::-1]\n \n seen = set()\n \n def dfs(r, c, i):\n if i == len(word):\n return True\n if r < 0 or c < 0 or r >= R or c >= C or word[i] != board[r][c] or (r,c) in seen:\n return False\n \n seen.add((r,c))\n res = (\n dfs(r+1,c,i+1) or \n dfs(r-1,c,i+1) or\n dfs(r,c+1,i+1) or\n dfs(r,c-1,i+1) \n )\n seen.remove((r,c)) #backtracking\n\n return res\n \n for i in range(R):\n for j in range(C):\n if dfs(i,j,0):\n return True\n return False\n```\n\n```Java []\nclass Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length, n = board[0].length;\n if (m*n < word.length())\n return false;\n char[] wrd = word.toCharArray();\n int[] boardf = new int[128];\n for (int i = 0; i < m; ++i)\n {\n for (int j = 0; j < n; ++j)\n {\n ++boardf[board[i][j]];\n }\n }\n for (char ch : wrd)\n {\n if (--boardf[ch] < 0)\n {\n return false;\n }\n }\n if (boardf[wrd[0]] > boardf[wrd[wrd.length - 1]])\n reverse(wrd);\n for (int i = 0; i < m; ++i)\n {\n for (int j = 0; j < n; ++j)\n {\n if (wrd[0] == board[i][j]\n && found(board, i, j, wrd, new boolean[m][n], 0))\n return true;\n }\n }\n return false;\n }\n\n private void reverse(char[] word)\n {\n int n = word.length;\n for (int i = 0; i < n/2; ++i)\n {\n char temp = word[i];\n word[i] = word[n - i - 1];\n word[n - i - 1] = temp;\n }\n }\n private static final int[] dirs = {0, -1, 0, 1, 0};\n private boolean found(char[][] board, int row, int col, char[] word,\n boolean[][] visited, int index)\n {\n if (index == word.length)\n return true;\n if (row < 0 || col < 0 || row == board.length || col == board[0].length\n || board[row][col] != word[index] || visited[row][col])\n return false;\n visited[row][col] = true;\n for (int i = 0; i < 4; ++i)\n {\n if (found(board, row + dirs[i], col + dirs[i + 1],\n word, visited, index + 1))\n return true;\n }\n visited[row][col] = false;\n return false;\n }\n}\n```\n
7,701
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
25,404
205
```\ndef exist(self, board: List[List[str]], word: str) -> bool:\n\t# Count number of letters in board and store it in a dictionary\n\tboardDic = defaultdict(int)\n\tfor i in range(len(board)):\n\t\tfor j in range(len(board[0])):\n\t\t\tboardDic[board[i][j]] += 1\n\n\t# Count number of letters in word\n\t# Check if board has all the letters in the word and they are atleast same count from word\n\twordDic = Counter(word)\n\tfor c in wordDic:\n\t\tif c not in boardDic or boardDic[c] < wordDic[c]:\n\t\t\treturn False\n\n\t# Traverse through board and if word[0] == board[i][j], call the DFS function\n\tfor i in range(len(board)):\n\t\tfor j in range(len(board[0])):\n\t\t\tif board[i][j] == word[0]:\n\t\t\t\tif self.dfs(i, j, 0, board, word):\n\t\t\t\t\treturn True\n\n\treturn False\n\ndef dfs(self, i, j, k, board, word):\n\t# Recursion will return False if (i,j) is out of bounds or board[i][j] != word[k] which is current letter we need\n\tif i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or \\\n\t k >= len(word) or word[k] != board[i][j]:\n\t\treturn False\n\n\t# If this statement is true then it means we have reach the last letter in the word so we can return True\n\tif k == len(word) - 1:\n\t\treturn True\n\n\tdirections = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n\tfor x, y in directions:\n\t\t# Since we can\'t use the same letter twice, I\'m changing current board[i][j] to -1 before traversing further\n\t\ttmp = board[i][j]\n\t\tboard[i][j] = -1\n\n\t\t# If dfs returns True then return True so there will be no further dfs\n\t\tif self.dfs(i + x, j + y, k + 1, board, word): \n\t\t\treturn True\n\n\t\tboard[i][j] = tmp\n```\n\n![image]()\n\n![image]()\n\n\n\n\n
7,706
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
132,982
516
\n def exist(self, board, word):\n if not board:\n return False\n for i in xrange(len(board)):\n for j in xrange(len(board[0])):\n if self.dfs(board, i, j, word):\n return True\n return False\n \n # check whether can find word, start at (i,j) position \n def dfs(self, board, i, j, word):\n if len(word) == 0: # all the characters are checked\n return True\n if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:\n return False\n tmp = board[i][j] # first character is found, check the remaining part\n board[i][j] = "#" # avoid visit agian \n # check whether can find "word" along one direction\n res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \\\n or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])\n board[i][j] = tmp\n return res
7,717
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
1,587
6
```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n\n row, col = len(board), len(board[0])\n R, C, seen = range(row), range(col), set()\n\n def dfs(coord, i=0):\n \n if len(word) == i: return True\n \n r,c = coord\n\n if (r not in R or c not in C or \n coord in seen or \n board[r][c] != word[i]): return False\n \n seen.add(coord)\n\n res = (dfs((r+1,c), i+1) or dfs((r,c+1), i+1) or\n dfs((r-1,c), i+1) or dfs((r,c-1), i+1))\n \n seen.remove(coord)\n\n return res\n\n boardCt, wrdCt = Counter(chain(*board)), Counter(word)\n if any (boardCt[ch] < wrdCt[ch] for ch in wrdCt): return False\n\n if boardCt[word[0]] > boardCt[word[-1]]: word = word[::-1]\n \n return any(dfs((r, c)) for c in C for r in R)\n```\n\n\nBefore you ask about time & space complexity, I do not know. Recursion baffles me.
7,721
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
3,742
32
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find whether a given word can be constructed from the characters of the given grid such that adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. The problem can be solved using the Depth First Search (DFS) algorithm. The DFS algorithm works by exploring as far as possible along each branch before backtracking. It is well-suited for problems that require searching through all possible paths.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can approach the problem using the DFS algorithm. We start by iterating through each cell in the grid. For each cell, we check whether the current cell matches the first character of the given word. If the current cell matches the first character of the word, we start a DFS search from that cell, looking for the rest of the characters in the word.\n\nFor each DFS search, we explore all four directions, i.e., up, down, left, and right, to find the next character in the word. We mark the current cell as visited to ensure that we do not use the same cell more than once. If we find the entire word, we return True, else we continue the search from the next unvisited cell.\n\nWe need to keep track of the visited cells to ensure that we do not use the same cell more than once. To mark a cell as visited, we can replace the character in the cell with a special character, such as \'/\'. After completing the DFS search, we can restore the original value of the cell.\n# Complexity\n- Time complexity: The time complexity of the DFS algorithm is proportional to the number of cells in the grid, i.e., O(mn), where m is the number of rows and n is the number of columns. In the worst case, we may have to explore all possible paths to find the word. For each cell, we explore at most four directions, so the time complexity of the DFS search is O(4^k), where k is the length of the word. Therefore, the overall time complexity of the algorithm is O(mn*4^k).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity of the algorithm is O(k), where k is the length of the word. This is the space required to store the recursive stack during the DFS search.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n def dfs(i: int, j: int, k: int) -> bool:\n if k == len(word):\n return True\n if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[k]:\n return False\n temp, board[i][j] = board[i][j], \'/\'\n res = dfs(i+1, j, k+1) or dfs(i-1, j, k+1) or dfs(i, j+1, k+1) or dfs(i, j-1, k+1)\n board[i][j] = temp\n return res\n \n m, n = len(board), len(board[0])\n for i in range(m):\n for j in range(n):\n if dfs(i, j, 0):\n return True\n return False\n\n```\n\n# Code Explanation \n\nThis is a Python implementation of the depth-first search algorithm to find if a word exists in a given board of characters.\n\nThe `exist` method takes in two parameters, `board` and `word`, which are the 2D list of characters representing the board and the string representing the word to find, respectively. The method returns a boolean value, `True` if the word exists in the board, and `False` otherwise.\n\nThe algorithm uses a helper function `dfs` to search for the word starting from a given position in the board. The `dfs` function takes in three parameters, `i`, `j`, and `k`, which are the row and column indices of the current position in the board and the index of the current character in the word, respectively. The function returns a boolean value, `True` if the word can be formed starting from this position, and `False` otherwise.\n\nThe `dfs` function first checks if the end of the word has been reached, in which case it returns `True`. If the current position is out of the board or does not match the current character in the word, the function returns `False`.\n\nIf the current position matches the current character in the word, the function temporarily changes the character at the current position to `\'/\'` to mark it as visited and prevent revisiting it in the search. It then recursively calls itself with the adjacent positions (up, down, left, and right) and the next index in the word. If any of the recursive calls returns `True`, the function returns `True` as well.\n\nAfter the search from the current position is finished, the function restores the original character at the current position and returns the final result.\n\nThe `exist` function first gets the dimensions of the board using the `len` function. It then iterates through each cell in the board using nested loops. For each cell, it calls the `dfs` function starting from that position with the first character in the word. If `dfs` returns `True`, the function immediately returns `True` as well since the word has been found. If no word is found after iterating through all cells, the function returns `False`.
7,732
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
1,062
10
# Code\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n ROWS, COLS = len(board), len(board[0])\n visited = set()\n\n def dfs(r,c,idx):\n # if idx == len(word), then word has been found\n if idx == len(word):\n return True\n\n # out of bounds\n # OR current letter does not match letter on board\n # OR letter already visited\n if ( \n r<0 or r>=ROWS \n or c<0 or c>=COLS\n or word[idx] != board[r][c]\n or (r,c) in visited\n ):\n return False\n \n # to keep track of the letter already visited, add it\'s position to the set\n # after DFS we can remove it from the set.\n visited.add((r,c))\n\n # performing DFS \n res = (\n dfs(r+1,c,idx+1) \n or dfs(r-1,c,idx+1) \n or dfs(r,c+1,idx+1) \n or dfs(r,c-1,idx+1)\n )\n \n visited.remove((r,c))\n return res\n \n for i in range(ROWS):\n for j in range(COLS):\n if dfs(i,j,0):\n return True\n return False\n\n```
7,745
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
1,885
6
```\nclass Solution:\n """\n Time: O(n*m*k)\n Memory: O(k)\n\n where k - word length\n """\n\n VISITED = \'#\'\n\n def exist(self, board: List[List[str]], word: str) -> bool:\n n, m = len(board), len(board[0])\n\n beginning = end = 0\n for r in range(n):\n for c in range(m):\n if board[r][c] == word[0]:\n beginning += 1\n elif board[r][c] == word[-1]:\n end += 1\n\n if beginning > end:\n word = word[::-1]\n\n for i in range(n):\n for j in range(m):\n if self.dfs(board, i, j, 0, word):\n return True\n\n return False\n\n @classmethod\n def dfs(cls, board: List[List[str]], i: int, j: int, k: int, word: str) -> bool:\n if k == len(word):\n return True\n\n n, m = len(board), len(board[0])\n if (i < 0 or i >= n) or (j < 0 or j >= m) or word[k] != board[i][j]:\n return False\n\n board[i][j] = cls.VISITED\n res = cls.dfs(board, i + 1, j, k + 1, word) or \\\n cls.dfs(board, i - 1, j, k + 1, word) or \\\n cls.dfs(board, i, j + 1, k + 1, word) or \\\n cls.dfs(board, i, j - 1, k + 1, word)\n board[i][j] = word[k]\n\n return res\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n
7,762
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
757
8
**If you like Pls Upvote :-)**\n\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n rows=len(board)\n cols=len(board[0])\n visited=set()\n def dfs(i,j,curr):\n if curr==len(word):\n return True\n \n if i<0 or j>=cols or j<0 or i>=rows or board[i][j]!=word[curr] or (i,j) in visited:\n return False\n \n visited.add((i,j))\n res=dfs(i+1,j,curr+1) or dfs(i-1,j,curr+1) or dfs(i,j+1,curr+1) or dfs(i,j-1,curr+1)\n visited.remove((i,j))\n return res\n \n for i in range(rows):\n for j in range(cols):\n if dfs(i,j,0): return True\n return False\n```
7,765
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
725
14
**Optimization number 1**\n* Using if -elif instead of for loop helped me resolve TLE:\nAs if will return as soon as it gets TRUE, for will keep checking next conditions.\n(Even multiple "or" did\'nt work for me)\n\n**"PLEASE UPVOTE FOR MY AN HOUR SPENT"**\n\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool: \n\t\t# as start is not restricted to 0,0 we can start from anywhere, will loop\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(i,j,word, board, 0):\n return True\n return False\n \n def dfs(self, x, y, word, board, c):\n\t\t# return True if can make word starting from x, y\n if len(word)==c:\n return True \n\t\t# Exit if out of board or char is not required\n if x<0 or y<0 or x>=len(board) or y>=len(board[0]) or board[x][y]!=word[c]:\n return False \n\t\t# move ahead by marking board in path just not to visit again\n board[x][y] = "#"\n if self.dfs(x+1, y, word, board, c+1):\n return True\n elif self.dfs(x, y+1, word, board, c+1):\n return True\n elif self.dfs(x-1, y, word, board, c+1):\n return True\n elif self.dfs(x, y-1, word, board, c+1):\n return True \n\t\t# if from x,y no one making True, we need to restore x, y as it is not in path\n\t\t# so it is open to use by other paths\n board[x][y] = word[c]\n return False\n```\n\n**Optimization Pro Max number 2**\n* Check char in starting only\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool: \n # Count number of letters in board and store it in a dictionary\n boardDic = collections.defaultdict(int)\n for i in range(len(board)):\n for j in range(len(board[0])):\n boardDic[board[i][j]] += 1\n\n # Count number of letters in word\n # Check if board has all the letters in the word and they are atleast same count from word\n wordDic = collections.Counter(word)\n for c in wordDic:\n if c not in boardDic or boardDic[c] < wordDic[c]:\n return False\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(i,j,word, board, 0):\n return True\n return False\n \n def dfs(self, x, y, word, board, c):\n if len(word)==c:\n return True \n if x<0 or y<0 or x>=len(board) or y>=len(board[0]) or board[x][y]!=word[c]:\n return False \n board[x][y] = "#"\n if self.dfs(x+1, y, word, board, c+1):\n return True\n elif self.dfs(x, y+1, word, board, c+1):\n return True\n elif self.dfs(x-1, y, word, board, c+1):\n return True\n elif self.dfs(x, y-1, word, board, c+1):\n return True \n board[x][y] = word[c]\n return False\n```\n![image]()\n
7,766
Word Search
word-search
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Array,Backtracking,Matrix
Medium
null
500
5
```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n m, n = len(board), len(board[0])\n \n def find(i, j, pos = 0):\n if pos == len(word):\n return True\n if not(0 <= i < m) or not(0 <= j < n) or board[i][j] == "#":\n return False\n if board[i][j] == word[pos]:\n temp = board[i][j]\n board[i][j] = "#"\n if find(i, j-1, pos+1) or find(i, j+1, pos+1) or find(i-1, j, pos+1) or find(i+1, j, pos+1):\n return True\n board[i][j] = temp\n return False\n for i in range(m):\n for j in range(n):\n if find(i ,j):\n return True\n return False\n```\nTime : O(MNL)\nSpace : (L)\nPlease **UPVOTE**.
7,775
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
15,614
80
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.\n\t\t\tSince it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. At last return k after placing the final result in the first k slots of nums.\n# **Java Solution:**\nRuntime: 1 ms, faster than 96.73% of Java online submissions for Remove Duplicates from Sorted Array II.\nMemory Usage: 41.8 MB, less than 87.33% of Java online submissions for Remove Duplicates from Sorted Array II.\n```\nclass Solution {\n public int removeDuplicates(int[] nums) {\n // Special case...\n if (nums.length <= 2)\n return nums.length;\n int prev = 1; // point to previous\n int curr = 2; // point to current\n // Traverse all elements through loop...\n while (curr < nums.length) {\n // If the curr index matches the previous two elements, skip it...\n if (nums[curr] == nums[prev] && nums[curr] == nums[prev - 1]) {\n curr++;\n }\n // Otherwise, count that element and update...\n else {\n prev++;\n nums[prev] = nums[curr];\n curr++;\n }\n }\n return prev + 1; // Return k after placing the final result in the first k slots of nums...\n }\n}\n```\n\n# **C++ Solution:**\nRuntime: 4 ms, faster than 83.16% of C++ online submissions for Remove Duplicates from Sorted Array II.\nMemory Usage: 7.7 MB, less than 99.73% of C++ online submissions for Remove Duplicates from Sorted Array II.\n```\nclass Solution {\npublic:\n int removeDuplicates(vector<int>& nums) {\n // Special case...\n if(nums.size() <= 2) {\n return nums.size();\n }\n // Initialize an integer k that updates the kth index of the array...\n // only when the current element does not match either of the two previous indexes...\n int k = 2;\n // Traverse elements through loop...\n for(int i = 2; i < nums.size(); i++){\n // If the index does not match the (k-1)th and (k-2)th elements, count that element...\n if(nums[i] != nums[k - 2] || nums[i] != nums[k - 1]){\n nums[k] = nums[i];\n k++;\n // If the index matches the (k-1)th and (k-2)th elements, we skip it...\n }\n }\n return k; //Return k after placing the final result in the first k slots of nums...\n }\n};\n```\n\n# **Python Solution:**\nRuntime: 24 ms, faster than 74.03% of Python online submissions for Remove Duplicates from Sorted Array II.\n```\nclass Solution(object):\n def removeDuplicates(self, nums):\n # Initialize an integer k that updates the kth index of the array...\n # only when the current element does not match either of the two previous indexes. ...\n k = 0\n # Traverse all elements through loop...\n for i in nums:\n # If the index does not match elements, count that element and update it...\n if k < 2 or i != nums[k - 2]:\n nums[k] = i\n k += 1\n return k # Return k after placing the final result in the first k slots of nums...\n```\n \n# **JavaScript Solution:**\nRuntime: 88 ms, faster than 76.14% of JavaScript online submissions for Remove Duplicates from Sorted Array II.\nMemory Usage: 43.5 MB, less than 98.04% of JavaScript online submissions for Remove Duplicates from Sorted Array II.\n```\nvar removeDuplicates = function(nums) {\n // Special case...\n if(nums.length <= 2) {\n return nums.length;\n }\n // Initialize an integer k that updates the kth index of the array...\n // only when the current element does not match either of the two previous indexes...\n let k = 2;\n // Traverse elements through loop...\n for(let i = 2; i < nums.length; i++){\n // If the index does not match the (k-1)th and (k-2)th elements, count that element...\n if(nums[i] != nums[k - 2] || nums[i] != nums[k - 1]){\n nums[k] = nums[i];\n k++;\n // If the index matches the (k-1)th and (k-2)th elements, we skip it...\n }\n }\n return k; //Return k after placing the final result in the first k slots of nums...\n};\n```\n\n# **C Language:**\n```\nint removeDuplicates(int* nums, int numsSize){\n // Special case...\n if (numsSize <= 2)\n return numsSize;\n int prev = 1; // point to previous\n int curr = 2; // point to current\n // Traverse all elements through loop...\n while (curr < numsSize) {\n // If the curr index matches the previous two elements, skip it...\n if (nums[curr] == nums[prev] && nums[curr] == nums[prev - 1]) {\n curr++;\n }\n // Otherwise, count that element and update...\n else {\n prev++;\n nums[prev] = nums[curr];\n curr++;\n }\n }\n return prev + 1; // Return k after placing the final result in the first k slots of nums...\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n # Initialize an integer k that updates the kth index of the array...\n # only when the current element does not match either of the two previous indexes. ...\n k = 0\n # Traverse all elements through loop...\n for i in nums:\n # If the index does not match elements, count that element and update it...\n if k < 2 or i != nums[k - 2]:\n nums[k] = i\n k += 1\n return k # Return k after placing the final result in the first k slots of nums...\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
7,820
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
6,668
20
\n# Code\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n for i in range(len(nums)-2,0,-1):\n if(nums[i]==nums[i-1] and nums[i]==nums[i+1]):\n nums.pop(i+1)\n return len(nums)\n\n```
7,841
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
3,358
10
\n# Code\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n if len(nums) <= 2:\n return len(nums)\n\n currentIndex = 2\n for i in range(2, len(nums)):\n if nums[i] != nums[currentIndex - 2]:\n nums[currentIndex] = nums[i]\n currentIndex += 1\n\n return currentIndex\n\n\n```
7,848
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
2,655
5
# Code\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n counter = Counter(nums)\n l = []\n for i,j in counter.items():\n if j>2:\n l+=[i]*2\n else:\n l+=[i]*j\n nums[:] = l \n```\n# **Please upvote guys if you find the solution helpful.**
7,859
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
391
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCompared to "Remove Elementes From A Sorted Array I": The key differences are the ">" symbol and l- 2.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPlaceholder \'l\' stops at the 3rd repeated value while \'i\' continues and looks for then next different value. The ">" symbol prevents cases where 2 == 2 would be true and allows \'i\' to continue.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def removeDuplicates(self, nums):\n l = 2\n\n for i in range(2, len(nums)):\n if nums[i] > nums[l - 2]:\n nums[l] = nums[i]\n l += 1\n\n return l\n```
7,867
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
848
5
# 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![image.png]()\n\n# Code\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n ans=2\n for i in range(2,len(nums)):\n if nums[i]!=nums[ans-2]:nums[ans]=nums[i];ans+=1\n return ans\n```
7,886
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
2,618
23
#### **If You Find This Post Helpful Please Upvote**\n\n```\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n\t\t# Edge Condition\n if len(nums)<3: return len(nums)\n \n\t\t# Main Logic\n\t\t\n ind = 2 # Pointer from where we need to replace elements\n for i in range(2, len(nums)):\n if nums[i]!=nums[ind-2]:\n nums[ind] = nums[i]\n ind+=1\n return ind\n```\n**Visit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: **
7,893
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. Return k after placing the final result in the first k slots of nums. Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. Custom Judge: The judge will test your solution with the following code: If all assertions pass, then your solution will be accepted.
Array,Two Pointers
Medium
null
2,832
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Initialize a variable i to 0.\n- Loop through each n in nums.\n- Check if i is less than 2 or n is greater than the nums[i-2].\n - If the condition is true, assign n to nums[i] and increment i by 1.\n- Return i.\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 removeDuplicates(self, nums: List[int]) -> int:\n i = 0\n for n in nums:\n if i < 2 or n > nums[i-2]:\n nums[i] = n\n i += 1\n return i\n\n```
7,897
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
20,497
83
Since the array is given in a sorted order, so it can be solved using the binary search algorithm.\n\nTo solve this problem we have to follow the folllowing steps:\n\n1. Calculate the mid index.\n2. Check if the mid element == target, return True else move to next step.\n3. Else if the mid element >= left.\n\tif mid element >= target and and left <= target, then shift right to mid-1 position, else shift left to mid+1 position.\n4. Else,\n \tIf target >= mid element and target <=right, then shift left to mid+1 position, else shift right to mid-1 position.\n15. If the element is not found return False\n\nNote: Since duplicate elemnts are present in the array so remove all the duplicates before step step 1.\nTo remove duplicate,\n1. Shift left while left == left+1, and \n2. Shift right while right == right-1.\n\n```\n# If the length of the given array list is 1, then check the first element and return accordingly\nif len(nums)==1:\n if nums[0]!=target:\n return False\n else:\n return True\n\nleft=0\nright=len(nums)-1\n# binary search \nwhile(left<=right):\n\n # shifting to remove duplicate elements\n while left<right and nums[left] == nums[left+1]:\n left+=1\n while left<right and nums[right] == nums[right-1]:\n right-=1\n\n # step 1 calculate the mid \n mid=(left+right)//2\n\n #step 2\n if nums[mid]==target:\n return True\n\n #step 3\n elif nums[left]<=nums[mid]:\n if nums[mid]>=target and nums[left]<=target:\n right=mid-1\n else:\n left=mid+1\n\n # step 4\n else:\n if target>=nums[mid] and target<=nums[right]:\n left=mid+1\n else:\n right=mid-1\n\n# step 5\nreturn False\n\n```\nSolve the previous problem before moving to this:\n[33. Search in Rotated Sorted Array]()
7,901
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
6,885
66
# Problem Understanding\n\nThe problem presents us with a modified search challenge where we\'re provided an array that has been rotated at an undetermined pivot. Unlike a standard sorted array, this comes with the added complexity of having been altered. Imagine a scenario where you take a sorted array, make a cut at a specific point, and then attach the detached segment to the front. The aim here is to ascertain whether a specific target value is present in this rearranged sorted array. Adding to the intricacy, this array might have duplicate values.\n\nFor instance, considering the array $$[2,5,6,0,0,1,2]$$, it becomes evident that a rotation occurred after the number 6. If our target is 2, it is indeed present within the array. Similarly, for a target of 6, it is also found in the array. However, should the target be a number like 3, it is absent from the array.\n\nBelow are the visualizations for the "Search in Rotated Sorted Array II" problem for targets 2 and 6:\n\n- The top chart visualizes the search process in the rotated sorted array. Each step highlights the current mid value being considered with a red rectangle.\n\n- The table below provides a step-by-step breakdown of the search algorithm, detailing the indices (low, mid, high) and their corresponding values at each step of the search.\n\nFor each target:\n\n- The top chart shows the search process in the rotated sorted array. Each step of the search process is highlighted by a red rectangle.\n\n- The table below provides a step-by-step breakdown of the search algorithm, detailing the indices (low, mid, high) and their corresponding values at each search step.\n\n**Target = 2**\n\n![t=2.png]()\n\n**Target = 6**\n\n![t=6.png]()\n\n---\n\n# Live Coding & Explanation\n\n\n\n# Approach\n\nTo tackle this challenge, we employ a binary search strategy, taking into account the rotation and potential duplicates. The primary goal is to identify the sorted part of the array in each step and narrow down our search based on the target.\n\n## Binary Search with Rotation Handling\n\nOur approach doesn\'t involve searching for the rotation point. Instead, we modify the binary search to work directly with the rotated array:\n\n- We calculate the middle index, `mid`, of our current search interval.\n- If the value at `mid` is our target, we\'ve found it.\n- If the value at `low` is the same as the value at `mid`, we might be dealing with duplicates. In this case, we increment `low` to skip potential duplicates.\n- If the left part of our interval (from `low` to `mid`) is sorted (i.e., `nums[low] <= nums[mid]`), we check if our target lies within this sorted interval. If it does, we search in the left half; otherwise, we search in the right half.\n- If the left part isn\'t sorted, then the right part must be. We apply a similar logic to decide which half to search in next.\n\n## Code Breakdown\n\n1. Initialize pointers `low` and `high` at the start and end of `nums`, respectively.\n2. While `low` is less than or equal to `high`, compute `mid`.\n3. Check if `nums[mid]` is the target. If yes, return `True`.\n4. If `nums[low]` is equal to `nums[mid]`, increment `low`.\n5. If the left half is sorted, check if target lies within it. If yes, update `high`; otherwise, update `low`.\n6. If the right half is sorted, use a similar logic to update `low` or `high`.\n7. If the loop completes without finding the target, return `False`.\n\n## Rationale\n\nThe beauty of this solution lies in its adaptability. While binary search is a straightforward algorithm on sorted arrays, this problem added the twist of a rotated array and duplicates. By understanding the structure of the rotated array and handling duplicates wisely, we can still achieve efficient search performance.\n\n# Complexity\n\n**Time Complexity:** $$O(\\log n)$$ for the best case (unique elements). However, in the worst-case scenario (many duplicates), the complexity can degrade to $$O(n)$$.\n\n**Space Complexity:** $$O(1)$$ as we only use a constant amount of space.\n\n# Performance\n\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-------------|--------------|------------------|-------------|-----------------|\n| Rust | 0 ms | 100% | 2.2 MB | 48% |\n| C++ | 0 ms | 100% | 13.9 MB | 50.5% |\n| Java | 0 ms | 100% | 43.4 MB | 15.46% |\n| Go | 5 ms | 56.57% | 3.2 MB | 98.86% |\n| JavaScript | 49 ms | 92.77% | 41.6 MB | 97.20% |\n| Python3 | 56 ms | 92.26% | 17 MB | 47.39% |\n| C# | 75 ms | 98.86% | 41.6 MB | 80.11% |\n\n![per_81.png]()\n\n\n# Code\n``` Python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> bool:\n low, high = 0, len(nums) - 1\n\n while low <= high:\n mid = (low + high) // 2\n if nums[mid] == target:\n return True\n \n if nums[low] == nums[mid]:\n low += 1\n continue\n \n if nums[low] <= nums[mid]:\n if nums[low] <= target <= nums[mid]:\n high = mid - 1\n else:\n low = mid + 1\n else:\n if nums[mid] <= target <= nums[high]:\n low = mid + 1\n else:\n high = mid - 1\n \n return False\n```\n``` C++ []\nclass Solution {\npublic:\n bool search(std::vector<int>& nums, int target) {\n int low = 0, high = nums.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n if (nums[mid] == target) return true;\n\n if (nums[low] == nums[mid]) {\n low++;\n continue;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target <= nums[mid]) high = mid - 1;\n else low = mid + 1;\n } else {\n if (nums[mid] <= target && target <= nums[high]) low = mid + 1;\n else high = mid - 1;\n }\n }\n return false;\n }\n};\n```\n``` Rust []\nimpl Solution {\n pub fn search(nums: Vec<i32>, target: i32) -> bool {\n let mut low = 0;\n let mut high = nums.len() as i32 - 1;\n\n while low <= high {\n let mid = (low + high) / 2;\n if nums[mid as usize] == target {\n return true;\n }\n\n if nums[low as usize] == nums[mid as usize] {\n low += 1;\n continue;\n }\n\n if nums[low as usize] <= nums[mid as usize] {\n if nums[low as usize] <= target && target <= nums[mid as usize] {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if nums[mid as usize] <= target && target <= nums[high as usize] {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n false\n }\n}\n```\n``` Go []\nfunc search(nums []int, target int) bool {\n low, high := 0, len(nums) - 1\n\n for low <= high {\n mid := (low + high) / 2\n if nums[mid] == target {\n return true\n }\n\n if nums[low] == nums[mid] {\n low++\n continue\n }\n\n if nums[low] <= nums[mid] {\n if nums[low] <= target && target <= nums[mid] {\n high = mid - 1\n } else {\n low = mid + 1\n }\n } else {\n if nums[mid] <= target && target <= nums[high] {\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n }\n return false\n}\n```\n``` Java []\npublic class Solution {\n public boolean search(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n if (nums[mid] == target) return true;\n\n if (nums[low] == nums[mid]) {\n low++;\n continue;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target <= nums[mid]) high = mid - 1;\n else low = mid + 1;\n } else {\n if (nums[mid] <= target && target <= nums[high]) low = mid + 1;\n else high = mid - 1;\n }\n }\n return false;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {boolean}\n */\nvar search = function(nums, target) {\n let low = 0, high = nums.length - 1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n if (nums[mid] === target) return true;\n\n if (nums[low] === nums[mid]) {\n low++;\n continue;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target <= nums[mid]) high = mid - 1;\n else low = mid + 1;\n } else {\n if (nums[mid] <= target && target <= nums[high]) low = mid + 1;\n else high = mid - 1;\n }\n }\n return false;\n}\n```\n``` C# []\npublic class Solution {\n public bool Search(int[] nums, int target) {\n int low = 0, high = nums.Length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n if (nums[mid] == target) return true;\n\n if (nums[low] == nums[mid]) {\n low++;\n continue;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target <= nums[mid]) high = mid - 1;\n else low = mid + 1;\n } else {\n if (nums[mid] <= target && target <= nums[high]) low = mid + 1;\n else high = mid - 1;\n }\n }\n return false;\n }\n}\n```\n
7,937
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
2,443
19
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncheck which part is sorted so we can decide in which part target is present because lets take a case like if left part is sorted then the element is between the range left to mid and if target is between left that range move right to mid-1 otherwise i=mid+1.\n\nfor duplicate case lets take a case 4 1 2 4 4 4 4 \nl=0 r=6 mid=3 \nNow at element at mid,l,r : midelement =4 lelement=4 relement=4\n\nso we can not decise where to go because range cant be determined so in this case do l++ r-- until we can get the clear idea of range. after that just write same code of search in a rotated sorted array.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Initialize two pointers `i` and `j` pointing to the start and end of the array.\n\n2. While `i` is less than or equal to `j`:\n a. Calculate the middle index `mid`.\n b. If `nums[mid]` equals the target, return `true`.\n c. If `nums[mid]`, `nums[i]`, and `nums[j]` are all the same, increment `i` and decrement `j`.\n d. If `nums[mid]` is greater than or equal to `nums[i]`, check if target lies in the left sorted portion (`target >= nums[i] && target < nums[mid]`). Adjust pointers accordingly.\n e. If `nums[mid]` is less than or equal to `nums[j]`, check if target lies in the right sorted portion (`target > nums[mid] && target <= nums[j]`). Adjust pointers accordingly.\n\n3. If loop completes without returning, return `false`.\n\n# Complexity\n- Time complexity:O(log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1);\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n bool search(vector<int>& nums, int target) {\n int i=0;\n int j=nums.size()-1;\n while(i<=j){\n int mid=i+(j-i)/2;\n if(nums[mid]==target)\n return true;\n else if(nums[mid]==nums[i]&&nums[mid]==nums[j]){\n i=i+1;\n j=j-1;\n }\n else if(nums[mid]>=nums[i]){\n if(target>=nums[i]&& target<nums[mid]){\n j=mid-1;\n }\n else\n i=mid+1;\n }\n else if(nums[mid]<=nums[j]){\n if(target>nums[mid]&& target<=nums[j]){\n i=mid+1;\n }\n else\n j=mid-1;\n }\n }\n return false;\n }\n};\n```\n```java []\nclass Solution {\n public boolean search(int[] nums, int target) {\n int i = 0;\n int j = nums.length - 1;\n while (i <= j) {\n int mid = i + (j - i) / 2;\n if (nums[mid] == target) {\n return true;\n } else if (nums[mid] == nums[i] && nums[mid] == nums[j]) {\n i = i + 1;\n j = j - 1;\n } else if (nums[mid] >= nums[i]) {\n if (target >= nums[i] && target < nums[mid]) {\n j = mid - 1;\n } else {\n i = mid + 1;\n }\n } else if (nums[mid] <= nums[j]) {\n if (target > nums[mid] && target <= nums[j]) {\n i = mid + 1;\n } else {\n j = mid - 1;\n }\n }\n }\n return false;\n }\n}\n\n```\n```python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> bool:\n i = 0\n j = len(nums) - 1\n while i <= j:\n mid = i + (j - i) // 2\n if nums[mid] == target:\n return True\n elif nums[mid] == nums[i] and nums[mid] == nums[j]:\n i = i + 1\n j = j - 1\n elif nums[mid] >= nums[i]:\n if target >= nums[i] and target < nums[mid]:\n j = mid - 1\n else:\n i = mid + 1\n elif nums[mid] <= nums[j]:\n if target > nums[mid] and target <= nums[j]:\n i = mid + 1\n else:\n j = mid - 1\n return False\n\n```\n\n
7,943
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
454
8
# Intuition\nUsing modified binary search and add a few conditions before narrow the searching range.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n# Subscribe to my channel from here. I have 243 videos as of August 10th\n\n\n\n\n---\n\n# Related video\n- Search in Rotated Sorted Array\n\n\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Initialize `left` to 0 (representing the left boundary of the search range) and `right` to the length of `nums` minus 1 (representing the right boundary of the search range).\n\n2. Enter a `while` loop that continues as long as `left` is less than or equal to `right`.\n\n3. Calculate the midpoint `mid` using integer division (`//`) of the sum of `left` and `right`.\n\n4. Check if the element at the midpoint `nums[mid]` is equal to the target value. If it is, return `True` since the target has been found.\n\n5. Check if the element at the midpoint `nums[mid]` is equal to the element at the left boundary `nums[left]`. If they are equal, it means we have duplicate values at the left and mid positions. Increment `left` by 1 to skip duplicates and continue to the next iteration using the `continue` statement.\n\n6. If the conditions in steps 4 and 5 were not satisfied, then there are no duplicates at the mid position and the target value was not found. We need to decide whether the target could be in the left or right subarray based on the properties of the rotated sorted array.\n\n7. Check if the subarray from `left` to `mid` is sorted (i.e., `nums[left] <= nums[mid]`). If it is, then check whether the target lies within this sorted subarray (`nums[left] <= target < nums[mid]`). If this condition holds, adjust the `right` boundary to `mid - 1` to search the left half, otherwise, adjust the `left` boundary to `mid + 1` to search the right half.\n\n8. If the subarray from `left` to `mid` is not sorted, it implies that the rotated part is on the left side of `mid`. In this case, check whether the target lies within the subarray to the right of `mid` (`nums[mid] < target <= nums[right]`). If this condition holds, adjust the `left` boundary to `mid + 1` to search the right half, otherwise, adjust the `right` boundary to `mid - 1` to search the left half.\n\n9. Repeat steps 3 to 8 until the `left` boundary is no longer less than or equal to the `right` boundary, indicating that the search space is exhausted.\n\n10. If the target value was not found during the entire search, return `False`.\n\nIn summary, this algorithm performs a modified binary search on a rotated sorted array with possible duplicates. It efficiently narrows down the search range based on comparisons with the target value and the properties of the array.\n\n# Complexity\n- Time complexity: O(log n)\nBut if you get an input list like [1,1,1,1,1,1,1,1] target = 3, this condition(if nums[mid] == nums[left]:) is always `True`. In that case, time complexity should be O(n) because we narrow the searching range one by one.\n\n- Space complexity: O(1)\n\n\n```python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> bool:\n left, right = 0, len(nums) - 1\n \n while left <= right:\n mid = (left + right) // 2\n \n if nums[mid] == target:\n return True\n \n if nums[mid] == nums[left]:\n left += 1\n continue\n\n if nums[left] <= nums[mid]:\n if nums[left] <= target < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n else:\n if nums[mid] < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n \n return False\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {boolean}\n */\nvar search = function(nums, target) {\n let left = 0;\n let right = nums.length - 1;\n \n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n \n if (nums[mid] === target) {\n return true;\n }\n \n if (nums[mid] === nums[left]) {\n left++;\n continue;\n }\n \n if (nums[left] <= nums[mid]) {\n if (nums[left] <= target && target < nums[mid]) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[right]) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n }\n \n return false; \n};\n```\n```java []\nclass Solution {\n public boolean search(int[] nums, int target) {\n int left = 0;\n int right = nums.length - 1;\n \n while (left <= right) {\n int mid = (left + right) / 2;\n \n if (nums[mid] == target) {\n return true;\n }\n \n if (nums[mid] == nums[left]) {\n left++;\n continue;\n }\n \n if (nums[left] <= nums[mid]) {\n if (nums[left] <= target && target < nums[mid]) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[right]) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n }\n \n return false; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool search(vector<int>& nums, int target) {\n int left = 0;\n int right = nums.size() - 1;\n \n while (left <= right) {\n int mid = (left + right) / 2;\n \n if (nums[mid] == target) {\n return true;\n }\n \n if (nums[mid] == nums[left]) {\n left++;\n continue;\n }\n \n if (nums[left] <= nums[mid]) {\n if (nums[left] <= target && target < nums[mid]) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[right]) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n }\n \n return false; \n }\n};\n```\n
7,944
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
33,853
264
\n def search(self, nums, target):\n l, r = 0, len(nums)-1\n while l <= r:\n mid = l + (r-l)//2\n if nums[mid] == target:\n return True\n while l < mid and nums[l] == nums[mid]: # tricky part\n l += 1\n # the first half is ordered\n if nums[l] <= nums[mid]:\n # target is in the first half\n if nums[l] <= target < nums[mid]:\n r = mid - 1\n else:\n l = mid + 1\n # the second half is ordered\n else:\n # target is in the second half\n if nums[mid] < target <= nums[r]:\n l = mid + 1\n else:\n r = mid - 1\n return False
7,976
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.
Array,Binary Search
Medium
null
1,832
14
# Intuition:\nWe can use the binary search approach to solve this problem. The intuition is to determine which part of the array is sorted, and then check if the target element lies in that sorted part. If it does, then continue the search in that part of the array. If not, then continue the search in the other part of the array.\n\n# Approach:\n1. Initialize the start and end indices to the first and last elements of the array, respectively.\n2. Perform a binary search by repeatedly dividing the search space in half.\n3. Calculate the middle index using the formula `mid = start + (end - start) / 2`.\n4. Check if the target value is equal to the element at the middle index. If so, return true since the target is found.\n5. Compare the element at the start index with the element at the middle index to determine if the left half is sorted or the right half is sorted.\n - If the left half is sorted, check if the target value lies within the range of the sorted left half (`nums[start] <= target < nums[mid]`). If it does, update the end index to `mid - 1` to search in the left half; otherwise, update the start index to `mid + 1` to search in the right half.\n - If the right half is sorted, check if the target value lies within the range of the sorted right half (`nums[mid] < target <= nums[end]`). If it does, update the start index to `mid + 1` to search in the right half; otherwise, update the end index to `mid - 1` to search in the left half.\n6. If none of the above conditions are satisfied, it means there are duplicate elements at the start and middle indices. In this case, increment the start index by 1 and continue the search.\n7. Repeat steps 3-6 until the start index is less than or equal to the end index.\n8. If the target value is not found after the search, return false.\n\n# Complexity:\n- Time Complexity: The time complexity of the binary search algorithm is O(log N), where N is the number of elements in the array.\n- Space Complexity: The space complexity is O(1) since the algorithm uses a constant amount of additional space to store the indices and variables.\n\n---\n# C++\n```\nclass Solution {\npublic:\n bool search(vector<int>& nums, int target) {\n int start=0,end=nums.size()-1;\n while(start<=end){\n int mid = start + (end - start) / 2;\n if(target==nums[mid]){\n return true;\n }\n else if(nums[start]<nums[mid]){\n if(nums[start]<=target && nums[mid]>target){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n else if(nums[mid] < nums[start]){\n if(nums[end]>=target && nums[mid]<target){\n start=mid+1;\n }\n else{\n end=mid-1;\n }\n } \n else {\n start += 1;\n }\n }\n return false;\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public boolean search(int[] nums, int target) {\n int start = 0;\n int end = nums.length - 1;\n\n while (start <= end) {\n int mid = start + (end - start) / 2;\n\n if (target == nums[mid]) {\n return true;\n } else if (nums[start] < nums[mid]) {\n if (nums[start] <= target && nums[mid] > target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else if (nums[mid] < nums[start]) {\n if (nums[end] >= target && nums[mid] < target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n } else {\n start += 1;\n }\n }\n\n return false;\n }\n}\n```\n\n---\n# Python\n```\nclass Solution(object):\n def search(self, nums, target):\n start = 0\n end = len(nums) - 1\n\n while start <= end:\n mid = start + (end - start) // 2\n\n if target == nums[mid]:\n return True\n elif nums[start] < nums[mid]:\n if nums[start] <= target and nums[mid] > target:\n end = mid - 1\n else:\n start = mid + 1\n elif nums[mid] < nums[start]:\n if nums[end] >= target and nums[mid] < target:\n start = mid + 1\n else:\n end = mid - 1\n else:\n start += 1\n\n return False\n\n```\n\n---\n\n# JavaScript\n```\nvar search = function(nums, target) {\n let start = 0;\n let end = nums.length - 1;\n \n while (start <= end) {\n let mid = start + Math.floor((end - start) / 2);\n if (target === nums[mid]) {\n return true;\n } else if (nums[start] < nums[mid]) {\n if (nums[start] <= target && nums[mid] > target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else if (nums[mid] < nums[start]) {\n if (nums[end] >= target && nums[mid] < target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n } else {\n start += 1;\n }\n }\n\n return false;\n};\n```
7,989
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Linked List,Two Pointers
Medium
null
9,565
63
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.\n# **Java Solution:**\nRuntime: 1 ms, faster than 93.57% of Java online submissions for Remove Duplicates from Sorted List II.\n```\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n // Special case...\n if (head == null || head.next == null)\n return head;\n // create a fake node that acts like a fake head of list pointing to the original head and it points to the original head......\n ListNode fake = new ListNode(0);\n fake.next = head;\n ListNode curr = fake;\n // Loop till curr.next and curr.next.next not null\n while(curr.next != null && curr.next.next != null){ // curr.next means the next node of curr pointer and curr.next.next means the next of next of curr pointer...\n // if the value of curr.next and curr.next.next is same...\n // There is a duplicate value present in the list...\n if(curr.next.val == curr.next.next.val) {\n int duplicate = curr.next.val;\n // If the next node of curr is not null and its value is eual to the duplicate value...\n while(curr.next !=null && curr.next.val == duplicate) {\n // Skip those element and keep updating curr...\n curr.next = curr.next.next;\n }\n }\n // Otherwise, move curr forward...\n else{\n curr = curr.next;\n }\n }\n return fake.next; // Return the linked list...\n }\n}\n```\n\n# **C++ Solution:**\nRuntime: 6 ms, faster than 88.10% of C++ online submissions for Remove Duplicates from Sorted List II.\n```\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n // create a fake node that acts like a fake head of list pointing to the original head...\n ListNode* fake = new ListNode(0);\n // fake node points to the original head...\n fake->next = head;\n ListNode* pre = fake; //pointing to last node which has no duplicate...\n ListNode* curr = head; // To traverse the linked list...\n // Now we traverse nodes and do the process...\n while (curr != NULL) {\n // Create a loop until the current and previous values are same, keep updating curr...\n while (curr->next != NULL && pre->next->val == curr->next->val)\n curr = curr->next;\n // if curr has non-duplicate value, move the pre pointer to next node...\n if (pre->next == curr)\n pre = pre->next;\n // If curr is updated to the last duplicate value, discard it & connect pre and curr->next...\n else\n pre->next = curr->next;\n // Move curr forward...\n // In next iteration, we still need to check whether curr points to duplicate value...\n curr = curr->next;\n }\n // Return the linked list...\n return fake->next;\n }\n};\n```\n\n# **Python Solution:**\nRuntime: 28 ms, faster than 79.86% of Python online submissions for Remove Duplicates from Sorted List II.\n```\nclass Solution(object):\n def deleteDuplicates(self, head):\n fake = ListNode(-1)\n fake.next = head\n # We use prev (for node just before duplications begins), curr (for the last node of the duplication group)...\n curr, prev = head, fake\n while curr:\n # while we have curr.next and its value is equal to curr...\n # It means, that we have one more duplicate...\n while curr.next and curr.val == curr.next.val:\n # So move curr pointer to the right...\n curr = curr.next\n # If it happens, that prev.next equal to curr...\n # It means, that we have only 1 element in the group of duplicated elements...\n if prev.next == curr:\n # Don\'t need to delete it, we move both pointers to right...\n prev = prev.next\n curr = curr.next\n # Otherwise, we need to skip a group of duplicated elements...\n # set prev.next = curr.next, and curr = prev.next...\n else:\n prev.next = curr.next\n curr = prev.next\n # Return the linked list...\n return fake.next\n```\n \n# **JavaScript Solution:**\nRuntime: 91 ms, faster than 67.42% of JavaScript online submissions for Remove Duplicates from Sorted List II.\n```\nvar deleteDuplicates = function(head) {\n // Special case...\n if (head == null || head.next == null)\n return head;\n // create a fake node that acts like a fake head of list pointing to the original head and it points to the original head......\n var fake = new ListNode(0);\n fake.next = head;\n var curr = fake;\n // Loop till curr.next and curr.next.next not null\n while(curr.next != null && curr.next.next != null){ // curr.next means the next node of curr pointer and curr.next.next means the next of next of curr pointer...\n // if the value of curr.next and curr.next.next is same...\n // There is a duplicate value present in the list...\n if(curr.next.val == curr.next.next.val) {\n let duplicate = curr.next.val;\n // If the next node of curr is not null and its value is eual to the duplicate value...\n while(curr.next !=null && curr.next.val == duplicate) {\n // Skip those element and keep updating curr...\n curr.next = curr.next.next;\n }\n }\n // Otherwise, move curr forward...\n else{\n curr = curr.next;\n }\n }\n return fake.next; // Return the linked list...\n};\n```\n\n# **C Language:**\n```\nstruct ListNode* deleteDuplicates(struct ListNode* head){\n // create a fake node that acts like a fake head of list pointing to the original head...\n struct ListNode* fake = (struct ListNode*)malloc(sizeof(struct ListNode));\n // fake node points to the original head...\n fake->next = head;\n struct ListNode* pre = fake; //pointing to last node which has no duplicate...\n struct ListNode* curr = head; // To traverse the linked list...\n // Now we traverse nodes and do the process...\n while (curr != NULL) {\n // Create a loop until the current and previous values are same, keep updating curr...\n while (curr->next != NULL && pre->next->val == curr->next->val)\n curr = curr->next;\n // if curr has non-duplicate value, move the pre pointer to next node...\n if (pre->next == curr)\n pre = pre->next;\n // If curr is updated to the last duplicate value, discard it & connect pre and curr->next...\n else\n pre->next = curr->next;\n // Move curr forward...\n // In next iteration, we still need to check whether curr points to duplicate value...\n curr = curr->next;\n }\n // Return the linked list...\n return fake->next;\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fake = ListNode(-1)\n fake.next = head\n # We use prev (for node just before duplications begins), curr (for the last node of the duplication group)...\n curr, prev = head, fake\n while curr:\n # while we have curr.next and its value is equal to curr...\n # It means, that we have one more duplicate...\n while curr.next and curr.val == curr.next.val:\n # So move curr pointer to the right...\n curr = curr.next\n # If it happens, that prev.next equal to curr...\n # It means, that we have only 1 element in the group of duplicated elements...\n if prev.next == curr:\n # Don\'t need to delete it, we move both pointers to right...\n prev = prev.next\n curr = curr.next\n # Otherwise, we need to skip a group of duplicated elements...\n # set prev.next = curr.next, and curr = prev.next...\n else:\n prev.next = curr.next\n curr = prev.next\n # Return the linked list...\n return fake.next\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
8,016
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Linked List,Two Pointers
Medium
null
30,463
253
\n def deleteDuplicates(self, head):\n dummy = pre = ListNode(0)\n dummy.next = head\n while head and head.next:\n if head.val == head.next.val:\n while head and head.next and head.val == head.next.val:\n head = head.next\n head = head.next\n pre.next = head\n else:\n pre = pre.next\n head = head.next\n return dummy.next
8,028
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Linked List,Two Pointers
Medium
null
3,821
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. For iterative solution, simply iterate the Linked List and check for duplicate nodes and delete them.\n2. For STL solution, store the elements of the Linked List in the map and delete them if their frequency is greater than 1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n***Solution 1:***\n\n1. Iterate the Linked List from one step back than the head, as it is possible that we need to delete the first element as well, and we know that **for deleting any node we require the previous node**.\n2. Now just iterate the Linked List and store the current value of node in a variable named \'variable\' and till the subsequent elements == varible delete them.\n3. If the above condition is not true, just move forward i.e., itr = itr -> next.\n4. Finally return prev -> next (since our head of the list is stored in prev -> next pointer).\n\n\n***Solution 2:***\n\n1. Iterate the Linked List and store the elements in a map named mp.\n2. Create a new node \'newHead\' as the dummy head of the resulting Linked List.\n3. Create a temporary pointer \'temp\' to keep treack of the last node in the resulting Linked List. Initalize it to \'newHead\'.\n4. Iterate over the map, when (it.second == 1) create a new node \'ans\' with the value (it.first).\n5. Connect the new node \'ans\' to the last node in the resulting Linked List by assigning \'temp -> next = ans\', and update \'temp\' to \'ans\' for the next iteration.\n6. After processing all the unique values, the resulting Linked List is ready. Return \'newHead -> next\', which points to the first node in the resulting Linked List. \n\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is O(n) for both the approaches.\n\n- Space complexity: \n**Solution 1: O(1)\n Solution 2: O(n)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nIn Solution 2 we are using map to store the unique values of the Linked List.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n \n if(head == NULL) return head;\n\n ListNode* prev = new ListNode(); //this is pointing before head\n //Let\'s say the list is 2 -> 2 -> 3 -> 5 -> 5 -> 5, in this case we have to delete the 1st element as well, therefore we have used prev pointer\n prev -> next = head;\n\n ListNode* itr = prev;\n\n while(itr -> next != NULL && itr -> next -> next != NULL)\n {\n if(itr -> next -> val == itr -> next -> next -> val)\n {\n int variable = itr -> next -> val;\n //We have to delete all the duplicate elements along with the original element\n while(itr -> next != NULL && itr -> next -> val == variable)\n {\n itr -> next = itr -> next -> next;\n }\n }\n else //if we\'ll not write else condition, we\'ll get TLE\n {\n itr = itr -> next;\n }\n }\n return prev -> next; //head pointer is in prev -> next\n }\n};\n```\n\n\n```\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n map <int, int> mp;\n\n while(head != NULL)\n {\n mp[head -> val]++;\n head = head -> next;\n }\n\n ListNode* newHead = new ListNode(); //Creating new list for answer\n ListNode* temp = newHead; //temp variable to keep track of the last node\n for(auto & it: mp)\n {\n if(it.second == 1)\n {\n ListNode* ans = new ListNode(it.first); //to avoid integer to pointer conversion\n temp -> next = ans;\n temp = ans;\n }\n }\n return newHead -> next;\n }\n};\n```
8,050
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Linked List,Two Pointers
Medium
null
1,438
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a dummy node dummy and set its next node as the head of the linked list.\n2. Create a prev variable and initialize it with dummy.\n3. Use a while loop to traverse the linked list while head and head.next are not None.\n4. Check if the value of the current node head is equal to the value of the next node head.next.\n5. If yes, then use another while loop to traverse the linked list and find all the duplicates.\n6. Once all the duplicates are found, set head to head.next and update the next node of prev to head.\n7. If the values are not equal, update the prev to prev.next and head to head.next.\n8. Return dummy.next as the new head of the linked list.\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.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n dummy = ListNode(0)\n dummy.next = head\n prev = dummy\n while head and head.next:\n if head.val == head.next.val:\n while head and head.next and head.val == head.next.val:\n head = head.next\n head = head.next\n prev.next = head\n else:\n prev = prev.next\n head = head.next\n return dummy.next\n\n```
8,065
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Linked List,Two Pointers
Medium
null
1,858
36
**Recursive**\n- Idea\n\t- Base case: list is empty or contains only one element --> No duplicates\n\t- Recursive case: Assuming that the rest of the list is already done removing duplicates, we only need to consider the first part\n\t\t- There\'s no duplicate in the first part\n\t\t\t![image]()\n\t\t- There\'re duplicates in the first part\n\t\t\t![image]()\n- Implementation\n ```python\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n # Base case\n if not head or not head.next:\n return head\n \n # Recursive case\n \n # No duplicate in the first part\n if head.next.val != head.val: \n head.next = self.deleteDuplicates(head.next)\n return head\n \n # Duplicates exist in the first part\n cur = head\n while cur.next and cur.next.val == cur.val:\n cur = cur.next\n return self.deleteDuplicates(cur.next)\n ```\n \n- Complexity\n\t- Time: O(n)\n\t- Space: O(n)\n\n\n\n**Iterative**\n- Idea\n\t- Add `dummy_head` before `head`. `dummy.next` is the first node of the list.\n\t\t- Using `dummy_head` can help us to handle edge cases easily. For example, removing duplicate nodes at the beginning of list.\n\t- Use two pointers `prev` and `cur` for removing nodes\n\t- Iterate the list\n\t\t- If there\'s no duplicate, move `prev` and `cur` one step forward\n\t\t- If there\'re duplicate\n\t\t\t- Iterate `cur` to the last duplicate node\n\t\t\t- "Jump over" the duplicates \n\t\t\t\t- `prev.next = cur.next` \n\t\t\t\t- `cur = cur.next`\n\t\t![image]()\n- Implementation\n\t```python\n\tdef deleteDuplicates(self, head: ListNode) -> ListNode:\n dummy_head = ListNode(next=head)\n prev, cur = dummy_head, head\n \n while cur and cur.next:\n if cur.val != cur.next.val:\n # If there\'s no duplicate,\n # move prev and cur one step forward\n prev, cur = cur, cur.next\n else:\n # If there\'re duplicates,\n # iterate cur to the last duplicate nodes,\n while cur.next and cur.val == cur.next.val:\n cur = cur.next\n \n # and jump over the duplicates\n prev.next = cur.next\n cur = cur.next\n \n return dummy_head.next\n\t```\n\t\n- Complexity\n\t- Time: O(n)\n\t- Space: O(1)\n\n\nIf you think this is helpful, please give it a vote.
8,067
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
27,377
86
# C++\n```\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n ListNode* temp=head;\n while (temp&&temp->next)\n {\n if (temp->next->val==temp->val)\n {\n temp->next=temp->next->next;\n continue;\n }\n temp=temp->next;\n }\n return head;\n }\n};\n```\n\n# Python\n```\nclass Solution(object):\n def deleteDuplicates(self, head):\n temp = head\n while (temp and temp.next):\n if (temp.next.val == temp.val):\n temp.next = temp.next.next\n continue\n temp = temp.next\n return head\n \n```\n\n# C\n```\nstruct ListNode* deleteDuplicates(struct ListNode* head) {\n struct ListNode* temp=head;\n while (temp&&temp->next)\n {\n if (temp->next->val==temp->val)\n {\n temp->next=temp->next->next;\n continue;\n }\n temp=temp->next;\n }\n return head;\n}\n```\n\n# Java\n```\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n ListNode temp = head;\n while (temp != null && temp.next != null)\n {\n if (temp.next.val==temp.val)\n {\n temp.next=temp.next.next;\n continue;\n }\n temp=temp.next;\n }\n return head;\n }\n}\n```\n\nUpvote if this helps please \uD83D\uDE42\n
8,107
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
703
15
[see the Successfully Accepted Submission]()\n```Python\nclass Solution(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n def deleteDuplicates(self, head):\n current = head\n while current is not None and current.next is not None:\n if current.next.val == current.val:\n current.next = current.next.next\n else:\n current = current.next\n return head\n```\n\n**Intuituin**\n \nWhen you create an instance of a class that has this constructor, you can provide values for val and next to initialize the object\'s attributes\n```\n self.val = val\n self.next = next\n\n```\n\nnitialize a pointer "current" to the head of the linked list\n```\n current = head\n```\nTraverse the linked list\n```\n while current is not None and current.next is not None:\n```\nCheck if the current node\'s value is equal to the next node\'s value\n```\n if current.next.val == current.val:\n```\nIf they are equal, skip (remove) the next node by updating the "next" pointer of the current node\n```\n current.next = current.next.next\n else:\n```\nIf they are not equal, move the "current" pointer to the next node\n```\n current = current.next\n```\nReturn the head of the linked list (with duplicates removed)\n```\n return head\n```\n![image]()\n
8,118
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
4,035
9
\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 deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n curr=head\n while curr:\n while curr.next and curr.next.val==curr.val:\n curr.next=curr.next.next\n curr=curr.next\n return head\n\n```
8,154
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
1,827
5
# 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:\nBeats\n94.95%\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 deleteDuplicates(self, head: ListNode) -> ListNode:\n # Check if the linked list is empty\n if not head:\n return None\n \n # Initialize two pointers: current and previous\n prev = head\n current = head.next\n \n while current:\n # If the current node\'s value is equal to the previous node\'s value, delete the current node\n if current.val == prev.val:\n prev.next = current.next\n current = current.next\n # If the current node\'s value is different, move the pointers to the next node\n else:\n prev = current\n current = current.next\n \n return head\n\n```
8,159
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
10,094
35
# Approach\n- We first deal with edge case of head being `None` rather than a `ListNode`\n- Next we create a new variable `curr` to point at our current node, starting with the `head` node\n- If `curr.next` is another node, we compare `curr.val` and `curr.next.val`\n - If the values are the same, we must remove one from the linked list\n - We keep the first node and remove the second by updating the first\'s .next (`curr.next`) to the next node\'s `.next` (`curr.next.next`)\n - If the values differ, we move point `curr` to the next node\n- We repeat the previous process until the current node does not point to another node, at which point we return `head`, the de-duplicated linked list\n\n# Code\n```\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head:\n return None\n\n curr = head\n\n while curr.next:\n if curr.val == curr.next.val:\n curr.next = curr.next.next\n else:\n curr = curr.next\n\n return head\n\n```\n\n## Please upvote if you find this helpful! :D
8,160
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
1,288
9
\n# One Pointers Approach--->Time:O(N)\n```\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n current=head\n while current and current.next:\n if current.val==current.next.val:\n current.next=current.next.next\n else:\n current=current.next\n return head\n\n```\n# please upvote me it would encourage me alot\n
8,164
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
1,399
9
**O(N) Time & O(1) Space Solution**\n```\ndef deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tfront = head #points to the front of the linked list\n\twhile head and head.next: #while we aren\'t at the end of the list\n\t\tif head.val == head.next.val: #if the next node has the same value\n\t\t\thead.next = head.next.next #skip it\n\t\telse: #not a duplicate\n\t\t\thead = head.next #otherwise move forward\n\treturn front #return the front of the linked list\n```\nIn this solution, we use ```front``` to keep track of the front of the linkedlist. Then, we go through the list up until the end and check to see if the value of the current node is equal to the value of the next node. If it is, then we skip the duplicate node by setting ```head.next = head.next.next```. If we just removed a duplicate, we don\'t know if the next node is also a duplicate, so we should not move forward with ```head = head.next``` like we do when we do not find a duplicate.\nThis solution only needs to look at every node once, giving ```O(N)``` time complexity. Since it requires a constant amount of additional space, the memory complexity is ```O(1)```.\n\nP.S. ```while head and head.next``` is the same as ```while head is not None and head.next is not None``` \u2013\u2013 it just checks that neither of them are ```None```.\n\n**Thanks for Reading!**\nIf this post has been helpful, please consider upvoting! Also, if I made any mistakes or there are other optimizations, methods I didn\'t consider, etc. please let me know!
8,171
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
8,931
33
# **Java Solution:**\nRuntime: 1 ms, faster than 92.17% of Java online submissions for Remove Duplicates from Sorted List.\n```\nclass Solution {\n public ListNode deleteDuplicates(ListNode head) {\n // Special case...\n if(head == null || head.next == null)\n return head;\n // Initialize a pointer curr with the address of head node...\n ListNode curr = head;\n // Traverse all element through a while loop if curr node and the next node of curr node are present...\n while( curr != null && curr.next != null){\n // If the value of curr is equal to the value of prev...\n // It means the value is present in the linked list...\n if(curr.val == curr.next.val){\n // Hence we do not need to include curr again in the linked list...\n // So we increment the value of curr...\n curr.next = curr.next.next;\n }\n // Otherwise, we increment the curr pointer...\n else{\n curr = curr.next; \n }\n }\n return head; // Return the sorted linked list without any duplicate element...\n }\n}\n```\n\n# **C++ Solution:**\nRuntime: 4 ms, faster than 81.52% of C++ online submissions for Remove Duplicates from Sorted List.\n```\nclass Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n // Special case...\n if(head==NULL || head->next==NULL)\n return head;\n // Initialize two pointers tmp(slow) and curr(fast)...\n ListNode* tmp = head;\n ListNode* curr = head->next;\n // Traverse all element through a while loop if curr node is not null...\n while(curr!=NULL) {\n // If the value of curr is equal to the value of tmp...\n // It means the value is present in the linked list...\n if(tmp->val == curr->val) {\n // Hence we do not need to include curr again in the linked list...\n // So we increment the value of curr...\n curr=curr->next;\n }\n // Otherwise, we increment both the pointers.\n else {\n tmp->next = curr;\n tmp = curr;\n curr = tmp->next;\n }\n }\n tmp->next = NULL;\n return head; // Return the sorted linked list without any duplicate element...\n }\n};\n```\n\n# **Python Solution:**\nRuntime: 36 ms, faster than 79.68% of Python online submissions for Remove Duplicates from Sorted List.\n```\nclass Solution(object):\n def deleteDuplicates(self, head):\n # Handle special case that the list is empty\n if head == None:\n return head\n # Initialize curr with the address of head node...\n curr = head\n # Travel the list until the second last node\n while curr.next != None:\n # If the value of curr is equal to the value of prev...\n # It means the value is present in the linked list...\n if curr.val == curr.next.val:\n # Hence we do not need to include curr again in the linked list...\n # So we increment the value of curr...\n tmp = curr.next\n curr.next = curr.next.next\n del tmp\n # Otherwise, we increment the curr pointer...\n else:\n curr = curr.next\n return head # Return the sorted linked list without any duplicate element...\n```\n \n# **JavaScript Solution:**\nRuntime: 82 ms, faster than 84.86% of JavaScript online submissions for Remove Duplicates from Sorted List.\n```\nvar deleteDuplicates = function(head) {\n // Special case...\n if(head == null || head.next == null)\n return head;\n // Initialize a pointer curr with the address of head node...\n let curr = head;\n // Traverse all element through a while loop if curr node and the next node of curr node are present...\n while( curr != null && curr.next != null){\n // If the value of curr is equal to the value of prev...\n // It means the value is present in the linked list...\n if(curr.val == curr.next.val){\n // Hence we do not need to include curr again in the linked list...\n // So we increment the value of curr...\n curr.next = curr.next.next;\n }\n // Otherwise, we increment the curr pointer...\n else{\n curr = curr.next; \n }\n }\n return head; // Return the sorted linked list without any duplicate element...\n};\n```\n\n# **C Language:**\n```\nstruct ListNode* deleteDuplicates(struct ListNode* head){\n // Special case...\n if(head==NULL || head->next==NULL)\n return head;\n // Initialize two pointers tmp(slow) and curr(fast)...\n struct ListNode* tmp = head;\n struct ListNode* curr = head->next;\n // Traverse all element through a while loop if curr node is not null...\n while(curr!=NULL) {\n // If the value of curr is equal to the value of tmp...\n // It means the value is present in the linked list...\n if(tmp->val == curr->val) {\n // Hence we do not need to include curr again in the linked list...\n // So we increment the value of curr...\n curr=curr->next;\n }\n // Otherwise, we increment both the pointers.\n else {\n tmp->next = curr;\n tmp = curr;\n curr = tmp->next;\n }\n }\n tmp->next = NULL;\n return head; // Return the sorted linked list without any duplicate element...\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # Handle special case that the list is empty\n if head == None:\n return head\n # Initialize curr with the address of head node...\n curr = head\n # Travel the list until the second last node\n while curr.next != None:\n # If the value of curr is equal to the value of prev...\n # It means the value is present in the linked list...\n if curr.val == curr.next.val:\n # Hence we do not need to include curr again in the linked list...\n # So we increment the value of curr...\n tmp = curr.next\n curr.next = curr.next.next\n del tmp\n # Otherwise, we increment the curr pointer...\n else:\n curr = curr.next\n return head # Return the sorted linked list without any duplicate element...\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
8,179
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
2,089
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the values are ``sorted``, we can just compare the current value with the next value to check for ``duplicates``. Traversing through the linked list and checking for this condition in each node will solve the problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Start with assigning the current node to the head of the linked list\n- Traverse through the link list and ``compare`` the ``current`` node value with the ``next`` node value. If the values are same then ``current.next`` should point to ``current.next.next``. This will skip the next node\n- While traversal we should also check if ``current.next`` exists. If not then terminate the loop\n- After succesful traversal the derived link list will contain no duplicates\n- Return the ``head``\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\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 deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n current = head\n while current and current.next:\n if current.val == current.next.val: current.next = current.next.next\n else: current = current.next\n return head\n```
8,180
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
1,711
6
```\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 deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n temp=head\n while temp:\n while temp.next!=None and temp.val == temp.next.val:\n temp.next=temp.next.next\n temp=temp.next\n return head\n```\n\n**Upvote if you like the solution or ask if there is any query**
8,185
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
1,048
8
**Runtime: 42 ms, faster than 94.70% of Python3 online submissions for Remove Duplicates from Sorted List.**\n**Memory Usage: 13.8 MB, less than 70.70% of Python3 online submissions for Remove Duplicates from Sorted List.**\n\nThe theme to solve this question is just like how we solve regular linked list problems. \n\nWe go with initializing two variables start and node with head then we move node to start.next\n\nLike in this example:-\n![image]()\n now `start` is 1 and `node` is 1(2nd one)\n we loop through the list and check if `start==node` and if that is true like in this case, what we need to do is set `start.next=node.next` now since the First `1` in the above diagram now points to `2` and the next thing we need to take care of is that we need to change this as I have illustated in the following pictures:-\n \n ![image]()\n ![image]()\n ![image]()\n\n \nFrom here it\'s cake walk, you need to continue the loop and that\'s it. The Probelm is Solved!!\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 deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head \n start=node=head\n node=head.next\n while start and node:\n if start.val==node.val:\n start.next=node.next\n node.next=None\n node=start.next\n else:\n start=start.next\n node=node.next\n return head\n```\n\n\n_______________________________________________________________________________________________\n_________________________________________________________________________________________________\nEdit 1:\nthe line `node.next=None` can be omitted as we wont ever reach that node\n_________________________________________________________________________________________________\n_________________________________________________________________________________________________\n\n\nIf you liked my efforts then pls pls **UPVOTE** the post, it will encourage me to do more of this stuff!\n
8,186
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Linked List
Easy
null
40,911
172
def deleteDuplicates(self, head):\n cur = head\n while cur:\n while cur.next and cur.next.val == cur.val:\n cur.next = cur.next.next # skip duplicated node\n cur = cur.next # not duplicate of current node, move to next node\n return head
8,192
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Array,Stack,Monotonic Stack
Hard
null
66,196
597
def largestRectangleArea(self, height):\n height.append(0)\n stack = [-1]\n ans = 0\n for i in xrange(len(height)):\n while height[i] < height[stack[-1]]:\n h = height[stack.pop()]\n w = i - stack[-1] - 1\n ans = max(ans, h * w)\n stack.append(i)\n height.pop()\n return ans\n\n\n\n # 94 / 94 test cases passed.\n # Status: Accepted\n # Runtime: 76 ms\n # 97.34%\n\nThe stack maintain the indexes of buildings with ascending height. Before adding a new building pop the building who is taller than the new one. The building popped out represent the height of a rectangle with the new building as the right boundary and the current stack top as the left boundary. Calculate its area and update ans of maximum area. Boundary is handled using dummy buildings.
8,216
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Array,Stack,Monotonic Stack
Hard
null
710
7
# Intuition\nThe problem involves finding the largest rectangle that can be formed in a histogram of different heights. The approach is to iteratively process the histogram\'s bars while keeping track of the maximum area found so far.\n\n# Approach\n1. Initialize a variable `maxArea` to store the maximum area found, and a stack to keep track of the indices and heights of the histogram bars.\n\n2. Iterate through the histogram using an enumeration to access both the index and height of each bar.\n\n3. For each bar, calculate the width of the potential rectangle by subtracting the starting index (retrieved from the stack) from the current index.\n\n4. While the stack is not empty and the height of the current bar is less than the height of the bar at the top of the stack, pop elements from the stack to calculate the area of rectangles that can be formed.\n\n5. Update `maxArea` with the maximum of its current value and the area calculated in step 4.\n\n6. Push the current bar\'s index and height onto the stack to continue processing.\n\n7. After processing all bars, there may still be bars left in the stack. For each remaining bar in the stack, calculate the area using the height of the bar and the difference between the current index and the index at the top of the stack.\n\n8. Return `maxArea` as the result, which represents the largest rectangle area.\n\n# Complexity\n- Time complexity: O(n), where n is the number of bars in the histogram. We process each bar once.\n- Space complexity: O(n), as the stack can contain up to n elements in the worst case when the bars are in increasing order (monotonic).\n\n\n# Code\n```\nclass Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n maxArea = 0\n stack = []\n\n for index , height in enumerate(heights):\n start = index\n \n while start and stack[-1][1] > height:\n i , h = stack.pop()\n maxArea = max(maxArea , (index-i)*h)\n start = i\n stack.append((start , height))\n\n for index , height in stack:\n maxArea = max(maxArea , (len(heights)-index)*height)\n\n return maxArea \n\n \n\n\n \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n
8,227
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Array,Stack,Monotonic Stack
Hard
null
3,921
17
# Intuition:\nThe intuition behind the solution is to use two arrays, `nsr` (nearest smaller to the right) and `nsl` (nearest smaller to the left), to determine the boundaries of the rectangle for each bar in the histogram. By calculating the area for each rectangle and keeping track of the maximum area, we can find the largest rectangle in the histogram.\n\n# Approach:\n1. Initialize an empty stack `s` to store the indices of the histogram bars.\n2. Create two arrays, `nsr` and `nsl`, each of size `n` (where `n` is the number of elements in the `heights` vector), and initialize all elements to 0.\n3. Process the histogram bars from right to left:\n - While the stack is not empty and the height of the current bar is less than or equal to the height of the bar at the top of the stack, pop the stack.\n - If the stack becomes empty, set `nsr[i]` (the nearest smaller to the right for the current bar) to `n`.\n - Otherwise, set `nsr[i]` to the index at the top of the stack.\n - Push the current index `i` onto the stack.\n4. Empty the stack.\n5. Process the histogram bars from left to right:\n - While the stack is not empty and the height of the current bar is less than or equal to the height of the bar at the top of the stack, pop the stack.\n - If the stack becomes empty, set `nsl[i]` (the nearest smaller to the left for the current bar) to -1.\n - Otherwise, set `nsl[i]` to the index at the top of the stack.\n - Push the current index `i` onto the stack.\n6. Initialize a variable `ans` to 0. This variable will store the maximum rectangle area.\n7. Iterate over the histogram bars:\n - Calculate the area of the rectangle for the current bar using the formula: `heights[i] * (nsr[i] - nsl[i] - 1)`.\n - Update `ans` with the maximum of `ans` and the calculated area.\n8. Return `ans` as the largest rectangle area in the histogram.\n\n# Complexity:\n- The time complexity of this solution is O(n), where n is the number of elements in the `heights` vector. This is because each bar is processed only once.\n- The space complexity is O(n) as well because we use two additional arrays of size n, `nsr` and `nsl`, and a stack to store indices.\n\n---\n# C++\n```cpp\nclass Solution {\npublic:\n int largestRectangleArea(vector<int>& heights){\n int n=heights.size();\n vector<int> nsr(n,0);\n vector<int> nsl(n,0);\n\n stack<int> s;\n\n for(int i=n-1;i>=0;i--){\n while(!s.empty() && heights[i]<=heights[s.top()]){\n s.pop();\n }\n if(s.empty()) nsr[i]=n;\n else nsr[i]=s.top();\n s.push(i);\n }\n\n while(!s.empty()) s.pop();\n\n for(int i=0;i<n;i++){\n while(!s.empty() && heights[i]<=heights[s.top()]){\n s.pop();\n }\n if(s.empty()) nsl[i]=-1;\n else nsl[i]=s.top();\n s.push(i);\n }\n\n int ans=0;\n\n for(int i=0;i<n;i++){\n ans=max(ans, heights[i]*(nsr[i]-nsl[i]-1));\n }\n return ans; \n }\n};\n```\n\n---\n# JAVA\n```java\nclass Solution {\n public int largestRectangleArea(int[] heights) {\n int n = heights.length;\n int[] nsr = new int[n];\n int[] nsl = new int[n];\n \n Stack<Integer> s = new Stack<>();\n\n for (int i = n - 1; i >= 0; i--) {\n while (!s.isEmpty() && heights[i] <= heights[s.peek()]) {\n s.pop();\n }\n if (s.isEmpty()) nsr[i] = n;\n else nsr[i] = s.peek();\n s.push(i);\n }\n\n while (!s.isEmpty()) s.pop();\n\n for (int i = 0; i < n; i++) {\n while (!s.isEmpty() && heights[i] <= heights[s.peek()]) {\n s.pop();\n }\n if (s.isEmpty()) nsl[i] = -1;\n else nsl[i] = s.peek();\n s.push(i);\n }\n\n int ans = 0;\n\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, heights[i] * (nsr[i] - nsl[i] - 1));\n }\n return ans;\n }\n}\n```\n\n---\n\n# Python\n```py\nclass Solution(object):\n def largestRectangleArea(self, heights):\n n = len(heights)\n nsr = [0] * n\n nsl = [0] * n\n\n s = []\n\n for i in range(n - 1, -1, -1):\n while s and heights[i] <= heights[s[-1]]:\n s.pop()\n if not s:\n nsr[i] = n\n else:\n nsr[i] = s[-1]\n s.append(i)\n\n while s:\n s.pop()\n\n for i in range(n):\n while s and heights[i] <= heights[s[-1]]:\n s.pop()\n if not s:\n nsl[i] = -1\n else:\n nsl[i] = s[-1]\n s.append(i)\n\n ans = 0\n\n for i in range(n):\n ans = max(ans, heights[i] * (nsr[i] - nsl[i] - 1))\n return ans\n\n```\n\n---\n\n# JavaScript\n```js\nvar largestRectangleArea = function(heights) {\n const n = heights.length;\n const nsr = new Array(n).fill(0);\n const nsl = new Array(n).fill(0);\n\n const stack = [];\n \n for (let i = n - 1; i >= 0; i--) {\n while (stack.length !== 0 && heights[i] <= heights[stack[stack.length - 1]]) {\n stack.pop();\n }\n if (stack.length === 0) {\n nsr[i] = n;\n } else {\n nsr[i] = stack[stack.length - 1];\n }\n stack.push(i);\n }\n\n while (stack.length !== 0) {\n stack.pop();\n }\n\n for (let i = 0; i < n; i++) {\n while (stack.length !== 0 && heights[i] <= heights[stack[stack.length - 1]]) {\n stack.pop();\n }\n if (stack.length === 0) {\n nsl[i] = -1;\n } else {\n nsl[i] = stack[stack.length - 1];\n }\n stack.push(i);\n }\n\n let ans = 0;\n\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, heights[i] * (nsr[i] - nsl[i] - 1));\n }\n \n return ans;\n};\n```
8,237
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Array,Stack,Monotonic Stack
Hard
null
7,598
64
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to use a monotonic stack. We iterate over bars and add them to the stack as long as the last element in the stack is less than the current bar. When the condition doesn\'t hold, we start to calculate areas by popping out bars from the stack until the last element of the stack is greater than the current. The area is calculated as the number of pops multiplied by the height of the popped bar. On every pop, the height of the bar will be less or equal to the previous (since elements in the stack are always monotonically increasing).\n\nNow let\'s consider this example `[2,1,2]`. For this case the formula for the area (number of pops * current height) won\'t work because when we reach `1` we will pop out `2` from the stack and will not consider it later which is wrong since the largest area here is equal to `3 * 1`, i.e we somehow need to remember the previously discarded bars that still can form areas. We solve this problem by storing in the stack the width of the bar as well. So for our example, after discarding `2`, we push to the stack the `1` with the width equal to `2`.\n\nTime: **O(n)** - In the worst case we have 2 scans: one for the bars and one for the stack\nSpace: **O(n)** - in the wors case we push to the stack the whjole input array\n\nRuntime: 932 ms, faster than **51.27%** of Python3 online submissions for Largest Rectangle in Histogram.\nMemory Usage: 28.4 MB, less than **30.61%** of Python3 online submissions for Largest Rectangle in Histogram.\n\n```\ndef largestRectangleArea(self, bars: List[int]) -> int:\n\tst, res = [], 0\n\tfor bar in bars + [-1]: # add -1 to have an additional iteration\n\t\tstep = 0\n\t\twhile st and st[-1][1] >= bar:\n\t\t\tw, h = st.pop()\n\t\t\tstep += w\n\t\t\tres = max(res, step * h)\n\n\t\tst.append((step + 1, bar))\n\n\treturn res\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
8,238
Maximal Rectangle
maximal-rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
null
603
6
# Unlocking the Power of Algorithms: Solving the Maximal Rectangle Problem\n\nIf you\'re a coding enthusiast or a budding programmer, you\'ve probably heard about the Maximal Rectangle Problem. This fascinating problem is a classic in the world of computer science and is often used to demonstrate the power of dynamic programming and efficient algorithm design.\n\nIn this blog post, we\'ll dive deep into the problem and explore a solution using a clever algorithm. We\'ll provide code examples in multiple programming languages to ensure that you can follow along regardless of your coding preferences. So, whether you\'re a C++ aficionado, a Java enthusiast, a Python pro, or a JavaScript wizard, you\'re in the right place!\n\n## Understanding the Maximal Rectangle Problem\n\nThe Maximal Rectangle Problem can be defined as follows: Given a binary matrix, find the largest rectangle containing only ones and return its area. This might sound a bit complex at first, but with the right algorithm, it becomes a manageable challenge.\n\n## The Algorithm: Dynamic Programming to the Rescue\n\nThe key to solving the Maximal Rectangle Problem lies in dynamic programming. Dynamic programming is a powerful technique that involves breaking down a complex problem into smaller subproblems and reusing solutions to subproblems to avoid redundant computations. \n\n### Step 1: The `largestRectangleArea` Function\n\nFirst, let\'s take a look at the `largestRectangleArea` function. This function, written in C++, Java, Python, and JavaScript, calculates the largest rectangle area in a histogram. The idea is to use a stack to efficiently find the maximum area.\n\nHere\'s a simplified overview of the algorithm:\n\n1. Create an empty stack to store indices.\n2. Iterate through the histogram from left to right.\n3. While the stack is not empty and the current histogram value is less than the value at the index stored in the stack\'s top element, pop elements from the stack and calculate the maximum area for each popped element.\n4. Keep track of the maximum area as you iterate through the histogram.\n\nThis algorithm efficiently finds the largest rectangle area in the histogram, which we\'ll use in the next step.\n\n### Step 2: The `maximalAreaOfSubMatrixOfAll1` Function\n\nIn this step, we adapt the `largestRectangleArea` function to solve the Maximal Rectangle Problem for a binary matrix. We create a vector to store the height of each column and use dynamic programming to find the maximum rectangle area for each row.\n\n### Step 3: Bringing It All Together\n\nIn the final step, we create the `maximalRectangle` function, which takes a binary matrix as input and returns the maximum rectangle area containing only ones.\n\n\n## Dry Run of `maximalRectangle` Function\n\nWe\'ll perform a dry run of the `maximalRectangle` function using the following matrix:\n\n```python\nmatrix = [\n [\'1\', \'0\', \'1\', \'0\', \'0\'],\n [\'1\', \'0\', \'1\', \'1\', \'1\'],\n [\'1\', \'1\', \'1\', \'1\', \'1\'],\n [\'1\', \'0\', \'0\', \'1\', \'0\']\n]\n```\n\n### Step 1: Initializing Variables\n\nWe start with the given matrix:\n\n```\n1 0 1 0 0\n1 0 1 1 1\n1 1 1 1 1\n1 0 0 1 0\n```\n\nWe have two helper functions, `largestRectangleArea` and `maximalAreaOfSubMatrixOfAll1`, which are used within the `maximalRectangle` function.\n\n### Step 2: `maximalAreaOfSubMatrixOfAll1`\n\nWe enter the `maximalAreaOfSubMatrixOfAll1` function, which computes the maximal area of submatrices containing only \'1\'s. \n\n**Matrix and `height` after each row iteration:**\n\n1. Process Row 1:\n - Matrix:\n ```\n 1 0 1 0 0\n ```\n - Height: `[1, 0, 1, 0, 0]`\n\n2. Process Row 2:\n - Matrix:\n ```\n 1 0 1 1 1\n ```\n - Height: `[2, 0, 2, 1, 1]`\n\n3. Process Row 3:\n - Matrix:\n ```\n 1 1 1 1 1\n ```\n - Height: `[3, 1, 3, 2, 2]`\n\n4. Process Row 4:\n - Matrix:\n ```\n 1 0 0 1 0\n ```\n - Height: `[4, 1, 1, 3, 1]`\n\n**Maximal Area of Histogram (`largestRectangleArea`):**\n\nFor each `height`, we calculate the maximal area of the histogram using the `largestRectangleArea` function.\n\n- For the height `[1, 0, 1, 0, 0]`, the maximal area is `1`.\n- For the height `[2, 0, 2, 1, 1]`, the maximal area is `4`.\n- For the height `[3, 1, 3, 2, 2]`, the maximal area is `6`.\n- For the height `[4, 1, 1, 3, 1]`, the maximal area is `4`.\n\nThe maximal area of submatrices for each row is `[1, 4, 6, 4]`.\n\n### Step 3: `maximalRectangle`\n\nFinally, we return the maximum value from the array `[1, 4, 6, 4]`, which is `6`.\n\nThe maximal area of a submatrix containing only \'1\'s in the given matrix is `6`.\n\nThis concludes the dry run of the `maximalRectangle` function with the provided matrix.\n\n### **Code C++ Java Python JS C#**\n```cpp []\nclass Solution {\npublic:\nint largestRectangleArea(vector < int > & histo) {\n stack < int > st;\n int maxA = 0;\n int n = histo.size();\n for (int i = 0; i <= n; i++) {\n while (!st.empty() && (i == n || histo[st.top()] >= histo[i])) {\n int height = histo[st.top()];\n st.pop();\n int width;\n if (st.empty())\n width = i;\n else\n width = i - st.top() - 1;\n maxA = max(maxA, width * height);\n }\n st.push(i);\n }\n return maxA;\n}\nint maximalAreaOfSubMatrixOfAll1(vector<vector<char>> &mat, int n, int m) {\n \n int maxArea = 0;\n vector<int> height(m, 0);\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (mat[i][j] == \'1\') height[j]++;\n else height[j] = 0;\n }\n int area = largestRectangleArea(height);\n maxArea = max(maxArea, area);\n }\n return maxArea;\n}\n\n int maximalRectangle(vector<vector<char>>& matrix) {\n return maximalAreaOfSubMatrixOfAll1(matrix,matrix.size(),matrix[0].size());\n }\n};\n```\n\n**Java:**\n```java []\nimport java.util.Stack;\n\npublic class Solution {\n\n public int largestRectangleArea(int[] heights) {\n Stack<Integer> stack = new Stack<>();\n int maxArea = 0;\n int n = heights.length;\n for (int i = 0; i <= n; i++) {\n while (!stack.isEmpty() && (i == n || heights[stack.peek()] >= heights[i])) {\n int height = heights[stack.pop()];\n int width = stack.isEmpty() ? i : i - stack.peek() - 1;\n maxArea = Math.max(maxArea, width * height);\n }\n stack.push(i);\n }\n return maxArea;\n }\n\n public int maximalAreaOfSubMatrixOfAll1(char[][] matrix, int n, int m) {\n int maxArea = 0;\n int[] height = new int[m];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (matrix[i][j] == \'1\') {\n height[j]++;\n } else {\n height[j] = 0;\n }\n }\n int area = largestRectangleArea(height);\n maxArea = Math.max(maxArea, area);\n }\n return maxArea;\n }\n\n public int maximalRectangle(char[][] matrix) {\n return maximalAreaOfSubMatrixOfAll1(matrix, matrix.length, matrix[0].length);\n }\n}\n```\n\n**Python:**\n```python []\nclass Solution:\n def largestRectangleArea(self, heights):\n stack = []\n max_area = 0\n n = len(heights)\n \n for i in range(n + 1):\n while stack and (i == n or heights[stack[-1]] >= heights[i]):\n height = heights[stack.pop()]\n width = i if not stack else i - stack[-1] - 1\n max_area = max(max_area, height * width)\n \n stack.append(i)\n \n return max_area\n\n def maximalAreaOfSubMatrixOfAll1(self, mat, n, m):\n max_area = 0\n height = [0] * m\n\n for i in range(n):\n for j in range(m):\n if mat[i][j] == \'1\':\n height[j] += 1\n else:\n height[j] = 0\n\n area = self.largestRectangleArea(height)\n max_area = max(max_area, area)\n \n return max_area\n\n def maximalRectangle(self, matrix):\n if not matrix:\n return 0\n n, m = len(matrix), len(matrix[0])\n return self.maximalAreaOfSubMatrixOfAll1(matrix, n, m)\n\n```\n\n**JavaScript:**\n```javascript []\nfunction largestRectangleArea(heights) {\n const stack = [];\n let maxArea = 0;\n const n = heights.length;\n for (let i = 0; i <= n; i++) {\n while (stack.length > 0 && (i === n || heights[stack[stack.length - 1]] >= heights[i])) {\n const height = heights[stack.pop()];\n const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;\n maxArea = Math.max(maxArea, width * height);\n }\n stack.push(i);\n }\n return maxArea;\n}\n\nfunction maximalAreaOfSubMatrixOfAll1(matrix, n, m) {\n let maxArea = 0;\n const height = new Array(m).fill(0);\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (matrix[i][j] === \'1\') {\n height[j]++;\n } else {\n height[j] = 0;\n }\n }\n const area = largestRectangleArea(height);\n maxArea = Math.max(maxArea, area);\n }\n return maxArea;\n}\n\nfunction maximalRectangle(matrix) {\n return maximalAreaOfSubMatrixOfAll1(matrix, matrix.length, matrix[0].\n\nlength);\n}\n``` \n**C#**\n\n``` csharp []\nusing System;\nusing System.Collections.Generic;\n\nclass Solution\n{\n public int MaximalRectangle(char[][] matrix)\n {\n if (matrix == null || matrix.Length == 0 || matrix[0].Length == 0)\n {\n return 0;\n }\n\n int numRows = matrix.Length;\n int numCols = matrix[0].Length;\n\n int maxArea = 0;\n int[] height = new int[numCols];\n\n for (int row = 0; row < numRows; row++)\n {\n for (int col = 0; col < numCols; col++)\n {\n if (matrix[row][col] == \'1\')\n {\n height[col]++;\n }\n else\n {\n height[col] = 0;\n }\n }\n\n int area = LargestRectangleArea(height);\n maxArea = Math.Max(maxArea, area);\n }\n\n return maxArea;\n }\n\n private int LargestRectangleArea(int[] heights)\n {\n Stack<int> stack = new Stack<int>();\n int maxArea = 0;\n int n = heights.Length;\n\n for (int i = 0; i <= n; i++)\n {\n while (stack.Count > 0 && (i == n || heights[stack.Peek()] >= heights[i]))\n {\n int h = heights[stack.Pop()];\n int w = stack.Count == 0 ? i : i - stack.Peek() - 1;\n maxArea = Math.Max(maxArea, h * w);\n }\n\n stack.Push(i);\n }\n\n return maxArea;\n }\n}\n```\n---\n## Analysis\n![image.png]()\n\n---\n| Language | Runtime (ms) | Memory (MB) |\n|------------|--------------|-------------|\n| C++ | 27 | 13.6 |\n| Java | 13 | 44 |\n| Python | 233 | 17.5 |\n| JavaScript | 63 | 45.2 |\n| C# | 104 | 48.5 |\n\n---\n# Consider UPVOTING\u2B06\uFE0F\n\n![image.png]()\n\n\n# DROP YOUR SUGGESTIONS IN THE COMMENT\n\n## Keep Coding\uD83E\uDDD1\u200D\uD83D\uDCBB\n\n -- *MR.ROBOT SIGNING OFF*\n
8,312
Maximal Rectangle
maximal-rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
null
37,473
412
def maximalRectangle(self, matrix):\n if not matrix or not matrix[0]:\n return 0\n n = len(matrix[0])\n height = [0] * (n + 1)\n ans = 0\n for row in matrix:\n for i in xrange(n):\n height[i] = height[i] + 1 if row[i] == '1' else 0\n stack = [-1]\n for i in xrange(n + 1):\n while height[i] < height[stack[-1]]:\n h = height[stack.pop()]\n w = i - 1 - stack[-1]\n ans = max(ans, h * w)\n stack.append(i)\n return ans\n\n # 65 / 65 test cases passed.\n # Status: Accepted\n # Runtime: 120 ms\n # 100%\n\nThe solution is based on [largest rectangle in histogram][1] solution. Every row in the matrix is viewed as the ground with some buildings on it. The building height is the count of consecutive 1s from that row to above rows. The rest is then the same as [this solution for largest rectangle in histogram][2]\n\n\n [1]: \n [2]:
8,313
Maximal Rectangle
maximal-rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
null
1,957
16
# My youtube channel - KeetCode(Ex-Amazon)\nI create 142 videos for leetcode questions as of April 10, 2023. I believe my channel helps you prepare for the coming technical interviews. Please subscribe my channel!\n\n### Please subscribe my channel - KeetCode(Ex-Amazon) from here.\n\n**I created a video for this question. I believe you can understand easily with visualization.** \n\n**Largest Color Value in a Directed Graph video**\n\n\n**My youtube channel - KeetCode(Ex-Amazon)**\n\n\n\n![FotoJet (38).jpg]()\n\n\n---\n\n\n\n# Approach\n1. Check if the input matrix is empty, if it is return 0.\n\n2. Determine the number of columns in the matrix (n) by getting the length of the first row of the matrix.\n\n3. Create a list called heights, with n+1 elements, and initialize each element to 0.\n\n4. Create a variable called max_area and initialize it to 0.\n\n5. For each row in the matrix, do the following:\n - Iterate through each column in the row, and update the corresponding height in the "heights" list.\n - If the character in the matrix is "1", increment the corresponding height in the "heights" list by 1, otherwise set it to 0.\n\n6. Create an empty stack and add -1 to it.\n\n7. For each element in the "heights" list, do the following:\n - Compare the current height to the height of the top element in the stack.\n - If the current height is less than the height of the top element of the stack, do the following:\n - Pop the top element of the stack and calculate the area of the rectangle formed by the popped height.\n - Calculate the width of the rectangle by subtracting the index of the current element from the index of the new top element of the stack.\n - Calculate the area of the rectangle by multiplying the height and width.\n - Update the maximum area seen so far if the area of the current rectangle is larger than the current maximum.\n - Append the index of the current element to the stack.\n\n8. Return the maximum area seen so far.\n\n# Complexity\n- Time complexity: O(m*n)\nm is the number of rows in the input matrix and n is the number of columns. This is because we have to iterate through each element in the matrix at least once, and the time it takes to process each element is constant.\n\n- Space complexity: O(n)\nn is the number of columns in the matrix. This is because we are creating a "heights" list with n+1 elements, and a stack that could have up to n+1 elements. The rest of the variables used in the algorithm are constants and do not contribute significantly to the space complexity.\n\n# Python\n```\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n if not matrix:\n return 0\n \n n = len(matrix[0])\n heights = [0] * (n + 1)\n max_area = 0\n\n for row in matrix:\n for i in range(n):\n heights[i] = heights[i] + 1 if row[i] == "1" else 0\n \n stack = [-1]\n for i in range(n + 1):\n while heights[i] < heights[stack[-1]]:\n h = heights[stack.pop()]\n w = i - stack[-1] - 1\n max_area = max(max_area, h * w)\n \n stack.append(i)\n \n return max_area\n```\n\n# JavaScript\n```\n/**\n * @param {character[][]} matrix\n * @return {number}\n */\nvar maximalRectangle = function(matrix) {\n if (!matrix.length) {\n return 0;\n }\n \n const n = matrix[0].length;\n const heights = new Array(n + 1).fill(0);\n let maxArea = 0;\n \n for (let row of matrix) {\n for (let i = 0; i < n; i++) {\n heights[i] = row[i] === \'1\' ? heights[i] + 1 : 0;\n }\n \n const stack = [-1];\n for (let i = 0; i < n + 1; i++) {\n while (heights[i] < heights[stack[stack.length - 1]]) {\n const h = heights[stack.pop()];\n const w = i - stack[stack.length - 1] - 1;\n maxArea = Math.max(maxArea, h * w);\n }\n stack.push(i);\n }\n }\n \n return maxArea; \n};\n```\n\n# Java\n```\nclass Solution {\n public int maximalRectangle(char[][] matrix) {\n if (matrix == null || matrix.length == 0) {\n return 0;\n }\n \n int n = matrix[0].length;\n int[] heights = new int[n + 1];\n int maxArea = 0;\n \n for (char[] row : matrix) {\n for (int i = 0; i < n; i++) {\n heights[i] = row[i] == \'1\' ? heights[i] + 1 : 0;\n }\n \n Stack<Integer> stack = new Stack<>();\n stack.push(-1);\n for (int i = 0; i < n + 1; i++) {\n while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {\n int h = heights[stack.pop()];\n int w = i - stack.peek() - 1;\n maxArea = Math.max(maxArea, h * w);\n }\n stack.push(i);\n }\n }\n \n return maxArea; \n }\n}\n```\n\n# C++\n```\nclass Solution {\npublic:\n int maximalRectangle(vector<vector<char>>& matrix) {\n if (matrix.empty()) {\n return 0;\n }\n \n int n = matrix[0].size();\n vector<int> heights(n + 1);\n int maxArea = 0;\n \n for (auto row : matrix) {\n for (int i = 0; i < n; i++) {\n heights[i] = row[i] == \'1\' ? heights[i] + 1 : 0;\n }\n \n stack<int> st;\n st.push(-1);\n for (int i = 0; i < n + 1; i++) {\n while (st.top() != -1 && heights[i] < heights[st.top()]) {\n int h = heights[st.top()];\n st.pop();\n int w = i - st.top() - 1;\n maxArea = max(maxArea, h * w);\n }\n st.push(i);\n }\n }\n \n return maxArea; \n }\n};\n```
8,325
Maximal Rectangle
maximal-rectangle
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
null
763
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses the concept of histogram to solve the problem. For each row, it converts the binary values into heights of the bars and then calculates the largest rectangle in the histogram using the stack data structure. The solution has a time complexity of O(n * m) and a space complexity of O(m).\n\n# Complexity\n- Time complexity:\n89.51%\n\n- Space complexity:\n85%\n\n# Code\n```\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n if not matrix or not matrix[0]:\n return 0\n \n n, m = len(matrix), len(matrix[0])\n height = [0] * (m + 1)\n ans = 0\n \n for row in matrix:\n for i in range(m):\n height[i] = height[i] + 1 if row[i] == \'1\' else 0\n stack = [-1]\n for i in range(m + 1):\n while height[i] < height[stack[-1]]:\n h = height[stack.pop()]\n w = i - stack[-1] - 1\n ans = max(ans, h * w)\n stack.append(i)\n \n return ans\n\n```
8,381
Partition List
partition-list
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
Linked List,Two Pointers
Medium
null
15,506
126
# Problem Understanding\n\nIn the "Partition a Linked List Around a Value" problem, we are provided with the head of a linked list and a value `x`. The task is to rearrange the linked list such that all nodes with values less than `x` come before nodes with values greater than or equal to `x`. A key point is that the original relative order of the nodes in each of the two partitions must be preserved.\n\nConsider the linked list `head = [1,4,3,2,5,2]` and `x = 3`. The expected output after partitioning is `[1,2,2,4,3,5]`.\n\n---\n\n# Live Coding & Logic in Python\n\n\n## Coding in:\n- [\uD83D\uDC0D Python]()\n- [\uD83E\uDD80 Rust]()\n- [\uD83D\uDC39 Go]()\n\n# Approach: Two Pointer Technique with Dummy Nodes\n\nThe idea is to use two pointers (or references) to create two separate linked lists: \n1. One for nodes with values less than `x`\n2. Another for nodes with values greater than or equal to `x`\n\nAt the end, we can combine the two linked lists to get the desired result.\n\n## Key Data Structures:\n- **Linked List**: We work directly with the given linked list nodes.\n- **Dummy Nodes**: Two dummy nodes are used to create the starting point for the two partitions.\n\n## Step-by-step Breakdown:\n\n1. **Initialization**:\n - Create two dummy nodes: `before` and `after`.\n - Initialize two pointers `before_curr` and `after_curr` at the dummy nodes.\n \n2. **Traversal & Partition**:\n - Traverse the linked list with the given `head`.\n - For each node, if its value is less than `x`, attach it to the `before` list. Otherwise, attach it to the `after` list.\n \n3. **Merging**:\n - After traversing the entire list, append the `after` list to the `before` list to form the partitioned linked list.\n\n4. **Result**:\n - Return the next node of the `before` dummy node as the new head of the partitioned list.\n\n# Example - Visualization:\nBased on the provided example with the linked list `head = [1,4,3,2,5,2]` and `x = 3`, here\'s the step-by-step evolution of the `before`, `after`, and `head` lists:\n\n![viz_van.png]()\n\n1. After processing node with value `1`:\n - `head`: [1, 4, 3, 2, 5, 2]\n - `before`: [0, 1]\n - `after`: [0]\n\n2. After processing node with value `4`:\n - `head`: [4, 3, 2, 5, 2]\n - `before`: [0, 1]\n - `after`: [0, 4]\n\n3. After processing node with value `3`:\n - `head`: [3, 2, 5, 2]\n - `before`: [0, 1]\n - `after`: [0, 4, 3]\n\n4. After processing node with value `2`:\n - `head`: [2, 5, 2]\n - `before`: [0, 1, 2]\n - `after`: [0, 4, 3]\n\n5. After processing node with value `5`:\n - `head`: [5, 2]\n - `before`: [0, 1, 2]\n - `after`: [0, 4, 3, 5]\n\n6. After processing node with value `2`:\n - `head`: [2]\n - `before`: [0, 1, 2, 2]\n - `after`: [0, 4, 3, 5]\n\nFinally, after merging the `before` and `after` lists, the result is: `[1,2,2,4,3,5]`\n\n# Complexity:\n\n**Time Complexity:** $$O(n)$$\n- We traverse the linked list once, making the time complexity linear in the size of the list.\n\n**Space Complexity:** $$O(1)$$\n- We use constant extra space since we are only creating two dummy nodes and reusing the existing nodes in the linked list.\n\n# Performance:\n\nGiven the constraints, this solution is optimal and will efficiently handle linked lists of size up to 200 nodes.\n\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|------------|--------------|------------------|-------------|-----------------|\n| **Rust** | 0 | 100% | 1.9 | 100% |\n| **Go** | 0 | 100% | 2.4 | 98.48% |\n| **C++** | 0 | 100% | 10.2 | 48.14% |\n| **Java** | 0 | 100% | 40.8 | 83.63% |\n| **Python3** | 32 | 98.81% | 16.4 | 55.72% |\n| **JavaScript** | 45 | 98.36% | 44.3 | 12.30% |\n| **C#** | 82 | 67.18% | 39 | 64.10% |\n\n![v2.png]()\n\n\n# Code\n``` Python []\nclass Solution:\n def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n before, after = ListNode(0), ListNode(0)\n before_curr, after_curr = before, after\n \n while head:\n if head.val < x:\n before_curr.next, before_curr = head, head\n else:\n after_curr.next, after_curr = head, head\n head = head.next\n \n after_curr.next = None\n before_curr.next = after.next\n \n return before.next\n```\n``` C++ []\nclass Solution {\npublic:\n ListNode* partition(ListNode* head, int x) {\n ListNode before(0), after(0);\n ListNode* before_curr = &before;\n ListNode* after_curr = &after;\n \n while(head) {\n if(head->val < x) {\n before_curr->next = head;\n before_curr = head;\n } else {\n after_curr->next = head;\n after_curr = head;\n }\n head = head->next;\n }\n \n after_curr->next = nullptr;\n before_curr->next = after.next;\n \n return before.next;\n }\n};\n```\n``` Rust []\nimpl Solution {\n pub fn partition(mut head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {\n let mut before = ListNode::new(0);\n let mut after = ListNode::new(0);\n let mut before_tail = &mut before;\n let mut after_tail = &mut after;\n\n while let Some(mut node) = head {\n head = node.next.take();\n if node.val < x {\n before_tail.next = Some(node);\n before_tail = before_tail.next.as_mut().unwrap();\n } else {\n after_tail.next = Some(node);\n after_tail = after_tail.next.as_mut().unwrap();\n }\n }\n\n before_tail.next = after.next.take();\n\n before.next\n }\n}\n```\n``` Go []\nfunc partition(head *ListNode, x int) *ListNode {\n before := &ListNode{}\n after := &ListNode{}\n before_curr := before\n after_curr := after\n \n for head != nil {\n if head.Val < x {\n before_curr.Next = head\n before_curr = before_curr.Next\n } else {\n after_curr.Next = head\n after_curr = after_curr.Next\n }\n head = head.Next\n }\n \n after_curr.Next = nil\n before_curr.Next = after.Next\n \n return before.Next\n}\n```\n``` Java []\npublic class Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode before = new ListNode(0);\n ListNode after = new ListNode(0);\n ListNode before_curr = before;\n ListNode after_curr = after;\n \n while(head != null) {\n if(head.val < x) {\n before_curr.next = head;\n before_curr = before_curr.next;\n } else {\n after_curr.next = head;\n after_curr = after_curr.next;\n }\n head = head.next;\n }\n \n after_curr.next = null;\n before_curr.next = after.next;\n \n return before.next;\n }\n}\n```\n``` JavaScript []\nvar partition = function(head, x) {\n let before = new ListNode(0);\n let after = new ListNode(0);\n let before_curr = before;\n let after_curr = after;\n \n while(head !== null) {\n if(head.val < x) {\n before_curr.next = head;\n before_curr = before_curr.next;\n } else {\n after_curr.next = head;\n after_curr = after_curr.next;\n }\n head = head.next;\n }\n \n after_curr.next = null;\n before_curr.next = after.next;\n \n return before.next;\n};\n```\n``` C# []\npublic class Solution {\n public ListNode Partition(ListNode head, int x) {\n ListNode before = new ListNode(0);\n ListNode after = new ListNode(0);\n ListNode before_curr = before;\n ListNode after_curr = after;\n \n while(head != null) {\n if(head.val < x) {\n before_curr.next = head;\n before_curr = before_curr.next;\n } else {\n after_curr.next = head;\n after_curr = after_curr.next;\n }\n head = head.next;\n }\n \n after_curr.next = null;\n before_curr.next = after.next;\n \n return before.next;\n }\n}\n```\n\n# Coding in Rust & Go\n\n\n\n\nThe "Partition a Linked List Around a Value" problem exemplifies the elegance of simplicity in coding. Remember, every coding challenge is a gateway to greater understanding and expertise. Embrace each problem, for they refine your skills and mold your coding journey. Stay curious, dive deep, and let your passion for coding guide you to new horizons. \uD83D\uDE80\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB\n
8,410
Partition List
partition-list
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
Linked List,Two Pointers
Medium
null
2,496
22
# Intuition\nCreate a small list and a big list.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n# Subscribe to my channel from here. I have 245 videos as of August 15th\n\n\n\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. **Initialization**:\n - Initialize two dummy nodes: `slist` and `blist`. These will serve as the heads of two separate lists, one for values less than `x` and the other for values greater than or equal to `x`.\n - Initialize two pointers `small` and `big` that initially point to the dummy nodes `slist` and `blist`, respectively.\n\n2. **Traversing the Linked List**:\n - Start traversing the input linked list `head`.\n - In each iteration:\n - Check if the value of the current node `head.val` is less than `x`.\n - If true:\n - Connect the current node to the `small.next` and then move the `small` pointer to the newly added node. This effectively appends the current node to the smaller values list.\n - If false:\n - Connect the current node to the `big.next` and then move the `big` pointer to the newly added node. This effectively appends the current node to the larger values list.\n\n3. **Finishing the Partition**:\n - Once the traversal is complete, the smaller values list ends with the last node appended to it (pointed to by the `small` pointer), and the larger values list ends with the last node appended to it (pointed to by the `big` pointer).\n\n4. **Connecting Lists**:\n - Connect the tail of the smaller values list (`small.next`) to the head of the larger values list (`blist.next`), effectively merging the two lists.\n\n5. **Finalizing the Larger Values List**:\n - Since the larger values list is now connected to the smaller values list, set the `next` pointer of the last node in the larger values list to `None` to prevent any potential circular references in the linked list.\n\n6. **Returning the Result**:\n - Return the `next` node of the `slist` dummy node, which represents the head of the modified linked list where values less than `x` are on one side and values greater than or equal to `x` are on the other side.\n\nThe algorithm efficiently partitions the original linked list into two parts based on the given value `x`. Nodes with values less than `x` are placed on one side, and nodes with values greater than or equal to `x` are placed on the other side, maintaining the relative order of the nodes within each group. The algorithm uses two dummy nodes and two pointers to create and manage the partitioned lists.\n\n# Complexity\n- Time complexity: O(n)\nThe code iterates through the entire linked list once to partition the nodes into two separate lists based on the value of x.\n\n- Space complexity: O(1)\nThe code uses a constant amount of extra space for the two dummy nodes slist and blist, as well as for the small and big pointers. The additional space used does not scale with the input size (linked list length) but remains constant throughout the execution.\n\n```python []\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 partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n\n slist, blist = ListNode(), ListNode()\n small, big = slist, blist # dummy lists\n\n while head:\n if head.val < x:\n small.next = head\n small = small.next\n else:\n big.next = head\n big = big.next\n\n head = head.next\n\n small.next = blist.next\n big.next = None # prevent linked list circle\n\n return slist.next\n```\n```javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} x\n * @return {ListNode}\n */\nvar partition = function(head, x) {\n let slist = new ListNode();\n let blist = new ListNode();\n let small = slist;\n let big = blist;\n\n while (head !== null) {\n if (head.val < x) {\n small.next = head;\n small = small.next;\n } else {\n big.next = head;\n big = big.next;\n }\n\n head = head.next;\n }\n\n small.next = blist.next;\n big.next = null;\n\n return slist.next; \n};\n```\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode slist = new ListNode();\n ListNode blist = new ListNode();\n ListNode small = slist;\n ListNode big = blist;\n\n while (head != null) {\n if (head.val < x) {\n small.next = head;\n small = small.next;\n } else {\n big.next = head;\n big = big.next;\n }\n\n head = head.next;\n }\n\n small.next = blist.next;\n big.next = null;\n\n return slist.next; \n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* partition(ListNode* head, int x) {\n ListNode* slist = new ListNode(0, nullptr);\n ListNode* blist = new ListNode(0, nullptr);\n ListNode* small = slist;\n ListNode* big = blist;\n\n while (head != nullptr) {\n if (head->val < x) {\n small->next = head;\n small = small->next;\n } else {\n big->next = head;\n big = big->next;\n }\n\n head = head->next;\n }\n\n small->next = blist->next;\n big->next = nullptr;\n\n return slist->next; \n }\n};\n```\n\n### Thank you for reading. Please upvote the article and don\'t forget to subscribe to my youtube channel!\n
8,446
Partition List
partition-list
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
Linked List,Two Pointers
Medium
null
4,460
34
\uD83C\uDDEE\uD83C\uDDF3 Happy independence Day \uD83C\uDDEE\uD83C\uDDF3\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis approach uses two separate lists to partition the nodes.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Initialize two new linked lists, `less` and `greater`, to hold nodes with values less than `x` and greater than or equal to `x`, respectively.\n\n2. Traverse the original linked list, `head`, and for each node:\n - If the node\'s value is less than `x`, append it to the `less` list.\n - If the node\'s value is greater than or equal to `x`, append it to the `greater` list.\n\n3. After traversing the original list, attach the `greater` list to the end of the `less` list.\n\n4. Set the last node of the `greater` list\'s `next` pointer to `nullptr` to terminate the list.\n\n5. Return the `less` list\'s head as the result.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code 1\n# Creating new instances of Nodes with given value\n```C++ []\nclass Solution {\npublic:\n ListNode* partition(ListNode* head, int x) {\n ListNode* current = head; // Pointer to traverse the original list\n \n ListNode* lessDummy = new ListNode(0); // Dummy node for nodes < x\n ListNode* lessTail = lessDummy; // Tail pointer for less list\n \n ListNode* greaterDummy = new ListNode(0); // Dummy node for nodes >= x\n ListNode* greaterTail = greaterDummy; // Tail pointer for greater list\n \n // Traverse the original list\n while (current != nullptr) {\n if (current->val < x) {\n // Append current node to the less list\n lessTail->next = new ListNode(current->val);\n lessTail = lessTail->next; // Move the tail pointer\n } else {\n // Append current node to the greater list\n greaterTail->next = new ListNode(current->val);\n greaterTail = greaterTail->next; // Move the tail pointer\n }\n current = current->next; // Move to the next node\n }\n \n \n // Attach the greater list to the end of the less list\n lessTail->next = greaterDummy->next;\n \n // Return the modified list starting from the first node after the less dummy node\n return lessDummy->next;\n }\n};\n\n```\n```java []\nclass Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode current = head; // Pointer to traverse the original list\n \n ListNode lessDummy = new ListNode(0); // Dummy node for nodes < x\n ListNode lessTail = lessDummy; // Tail pointer for less list\n \n ListNode greaterDummy = new ListNode(0); // Dummy node for nodes >= x\n ListNode greaterTail = greaterDummy; // Tail pointer for greater list\n \n // Traverse the original list\n while (current != null) {\n if (current.val < x) {\n // Append current node to the less list\n lessTail.next = new ListNode(current.val);\n lessTail = lessTail.next; // Move the tail pointer\n } else {\n // Append current node to the greater list\n greaterTail.next = new ListNode(current.val);\n greaterTail = greaterTail.next; // Move the tail pointer\n }\n current = current.next; // Move to the next node\n }\n \n \n \n // Attach the greater list to the end of the less list\n lessTail.next = greaterDummy.next;\n \n // Return the modified list starting from the first node after the less dummy node\n return lessDummy.next;\n }\n}\n\n```\n```python []\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n current = head # Pointer to traverse the original list\n \n less_dummy = ListNode(0) # Dummy node for nodes < x\n less_tail = less_dummy # Tail pointer for less list\n \n greater_dummy = ListNode(0) # Dummy node for nodes >= x\n greater_tail = greater_dummy # Tail pointer for greater list\n \n # Traverse the original list\n while current:\n if current.val < x:\n # Append current node to the less list\n less_tail.next = ListNode(current.val)\n less_tail = less_tail.next # Move the tail pointer\n else:\n # Append current node to the greater list\n greater_tail.next = ListNode(current.val)\n greater_tail = greater_tail.next # Move the tail pointer\n current = current.next # Move to the next node\n \n \n # Attach the greater list to the end of the less list\n less_tail.next = greater_dummy.next\n \n # Return the modified list starting from the first node after the less dummy node\n return less_dummy.next\n\n```\n\n\n# Code 2 \n# Using same Nodes.\n```C++ []\nclass Solution {\npublic:\n ListNode* partition(ListNode* head, int x) {\n // Initialize dummy nodes and tail pointers for less and greater lists\n ListNode* lessDummy = new ListNode(0); // Dummy node for nodes < x\n ListNode* lessTail = lessDummy; // Tail pointer for less list\n \n ListNode* greaterDummy = new ListNode(0); // Dummy node for nodes >= x\n ListNode* greaterTail = greaterDummy; // Tail pointer for greater list\n \n ListNode* current = head; // Current pointer for traversing the original list\n \n // Traverse the original list\n while (current != nullptr) {\n if (current->val < x) {\n // Append current node to the less list\n lessTail->next = current;\n lessTail = current; // Move the tail pointer\n } else {\n // Append current node to the greater list\n greaterTail->next = current;\n greaterTail = current; // Move the tail pointer\n }\n current = current->next; // Move to the next node\n }\n \n greaterTail->next = nullptr; // Terminate the greater list\n \n // Attach the greater list to the end of the less list\n lessTail->next = greaterDummy->next;\n \n // Return the modified list starting from the first node after the less dummy node\n return lessDummy->next;\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode partition(ListNode head, int x) {\n ListNode lessDummy = new ListNode(0); // Dummy node for nodes < x\n ListNode lessTail = lessDummy; // Tail pointer for less list\n \n ListNode greaterDummy = new ListNode(0); // Dummy node for nodes >= x\n ListNode greaterTail = greaterDummy; // Tail pointer for greater list\n \n ListNode current = head; // Current pointer for traversing the original list\n \n // Traverse the original list\n while (current != null) {\n if (current.val < x) {\n // Append current node to the less list\n lessTail.next = current;\n lessTail = current; // Move the tail pointer\n } else {\n // Append current node to the greater list\n greaterTail.next = current;\n greaterTail = current; // Move the tail pointer\n }\n current = current.next; // Move to the next node\n }\n \n greaterTail.next = null; // Terminate the greater list\n \n // Attach the greater list to the end of the less list\n lessTail.next = greaterDummy.next;\n \n // Return the modified list starting from the first node after the less dummy node\n return lessDummy.next;\n }\n}\n```\n```Python3 []\nclass Solution:\n def partition(self, head: ListNode, x: int) -> ListNode:\n less_dummy = ListNode(0) # Dummy node for nodes < x\n less_tail = less_dummy # Tail pointer for less list\n \n greater_dummy = ListNode(0) # Dummy node for nodes >= x\n greater_tail = greater_dummy # Tail pointer for greater list\n \n current = head # Current pointer for traversing the original list\n \n # Traverse the original list\n while current:\n if current.val < x:\n # Append current node to the less list\n less_tail.next = current\n less_tail = current # Move the tail pointer\n else:\n # Append current node to the greater list\n greater_tail.next = current\n greater_tail = current # Move the tail pointer\n current = current.next # Move to the next node\n \n greater_tail.next = None # Terminate the greater list\n \n # Attach the greater list to the end of the less list\n less_tail.next = greater_dummy.next\n \n # Return the modified list starting from the first node after the less dummy node\n return less_dummy.next\n```
8,455
Partition List
partition-list
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
Linked List,Two Pointers
Medium
null
549
10
# Intuition \uD83E\uDD14\nImagine you\'re a \uD83E\uDD80 sorting pearls and stones from the ocean floor. The pearls (values less than `x`) are precious and you want to keep them close. The stones (values greater than or equal to `x`), while not as valuable, still need to be stored neatly. Now, imagine each pearl and stone is a node in the linked list. Our goal is to reorganize these nodes (or pearls and stones) based on their value relative to `x`.\n\n# Approach \uD83D\uDE80\nOur \uD83E\uDD80 has two baskets - one for pearls (`before`) and another for stones (`after`). It picks items one-by-one (or traverses the list). Depending on the value of the item, it places it in the appropriate basket. Once all items are sorted, it connects the two baskets to have a neat collection.\n\n1. \uD83D\uDECD\uFE0F Create two baskets (`before` and `after`).\n2. \uD83C\uDF0A Dive through the ocean floor (or traverse the list).\n3. \uD83C\uDF10 For each find, decide if it\'s a pearl or a stone and place it in the appropriate basket.\n4. \uD83D\uDD17 Once all items are collected, connect the two baskets.\n\n# Complexity \uD83D\uDD0D\n- Time complexity: $$O(n)$$\n - Our \uD83E\uDD80 dives through the ocean floor once, collecting each item.\n\n- Space complexity: $$O(1)$$\n - The \uD83E\uDD80 uses only two baskets regardless of the number of pearls and stones.\n\n# Code \uD83D\uDCDC\n``` Rust []\nimpl Solution {\n pub fn partition(mut head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {\n // Initialize two dummy nodes for \'before\' and \'after\' lists.\n let mut before = ListNode::new(0);\n let mut after = ListNode::new(0);\n \n // Pointers to the tails of \'before\' and \'after\' lists to aid in appending nodes.\n let mut before_tail = &mut before;\n let mut after_tail = &mut after;\n\n // Traverse the original list.\n while let Some(mut node) = head {\n head = node.next.take();\n \n // Compare current node\'s value with x and append to appropriate list.\n if node.val < x {\n before_tail.next = Some(node);\n before_tail = before_tail.next.as_mut().unwrap();\n } else {\n after_tail.next = Some(node);\n after_tail = after_tail.next.as_mut().unwrap();\n }\n }\n\n // Connect the end of \'before\' list to the start of \'after\' list.\n before_tail.next = after.next.take();\n\n // Return the merged list.\n before.next\n }\n}\n\n```\n``` Go []\nfunc partition(head *ListNode, x int) *ListNode {\n // Initialize two dummy nodes for \'before\' and \'after\' lists.\n before := &ListNode{}\n after := &ListNode{}\n \n // Pointers to help in appending nodes to \'before\' and \'after\' lists.\n before_curr := before\n after_curr := after\n \n // Traverse the original list.\n for head != nil {\n // Compare current node\'s value with x and append to appropriate list.\n if head.Val < x {\n before_curr.Next = head\n before_curr = before_curr.Next\n } else {\n after_curr.Next = head\n after_curr = after_curr.Next\n }\n head = head.Next\n }\n \n // Ensure \'after\' list\'s end points to nil.\n after_curr.Next = nil\n \n // Connect the end of \'before\' list to the start of \'after\' list.\n before_curr.Next = after.Next\n \n // Return the merged list.\n return before.Next\n}\n```\n``` Python []\nclass Solution:\n def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n # Initialize two dummy nodes for \'before\' and \'after\' lists.\n before, after = ListNode(0), ListNode(0)\n \n # Pointers to help in appending nodes to \'before\' and \'after\' lists.\n before_curr, after_curr = before, after\n \n # Traverse the original list.\n while head:\n # Compare current node\'s value with x and append to appropriate list.\n if head.val < x:\n before_curr.next, before_curr = head, head\n else:\n after_curr.next, after_curr = head, head\n head = head.next\n \n # Ensure \'after\' list\'s end points to None.\n after_curr.next = None\n \n # Connect the end of \'before\' list to the start of \'after\' list.\n before_curr.next = after.next\n \n # Return the merged list.\n return before.next\n```\n\n\n# Motivation \uD83C\uDF1F\nGreat job diving deep into the ocean of algorithms with our Rusty \uD83E\uDD80, Pythonic \uD83D\uDC0D, and Gopher friends! Each problem you tackle not only sharpens your coding skills but also adds a pearl of wisdom to your collection. Remember, every challenge is a step forward. Keep coding, keep collecting pearls, and let\'s make the ocean shine brighter! \uD83C\uDF0A\uD83C\uDF1F\uD83D\uDE80
8,481
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
17,466
136
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to check whether s2 is scrambled string of s1 or not. The scrambled string of a given string is defined as any string that can be obtained by swapping some characters of the original string. So we can solve this problem recursively by dividing the string into left and right substrings and check for two cases i.e., whether we need to swap the substrings before checking for the next recursive call or not.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will first check the base cases i.e., if the two strings are equal or not or if they are of different sizes. Then, we will create a key for the current problem by concatenating the two strings and storing it in a dictionary to avoid repeated computations. We will iterate over all possible splits of the current string and check whether we need to swap the left and right substrings or not. We will then make recursive calls on these two substrings and return true if any of the calls return true.\n\n# Complexity\n- Time complexity: $$O(n^4)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nsince for each character in s1, we are trying out all possible splits of the string which takes $$O(n^2)$$ time and we are calling the recursion twice for each split which takes another $$O(n^2)$$ time. And for each such problem, we are storing it in a dictionary which takes $$O(1)$$ time. So overall time complexity is $$O(n^4)$$.\n\n- Space complexity: $$O(n^3)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nsince we are using a dictionary to store previously solved problems and the depth of the recursion tree can go up to n. Therefore, the space complexity of this solution is $$O(n^3)$$.\n\n\n\n![image.png]()\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n# Code\n``` Java []\nclass Solution {\n // for storing already solved problems\n Map<String, Boolean> mp = new HashMap<>();\n\n public boolean isScramble(String s1, String s2) {\n int n = s1.length();\n\n // if both strings are not equal in size\n if (s2.length() != n)\n return false;\n\n // if both strings are equal\n if (s1.equals(s2))\n return true;\n\n // if code is reached to this condition then following this are sure:\n // 1. size of both string is equal\n // 2. string are not equal\n // so size is equal (where size==1) and they are not equal then obviously false\n // example \'a\' and \'b\' size is equal ,string are not equal\n if (n == 1)\n return false;\n\n String key = s1 + " " + s2;\n\n // check if this problem has already been solved\n if (mp.containsKey(key))\n return mp.get(key);\n\n // for every iteration it can two condition\n // 1.we should proceed without swapping\n // 2.we should swap before looking next\n for (int i = 1; i < n; i++) {\n // ex of without swap: gr|eat and rg|eat\n boolean withoutswap = (\n // left part of first and second string\n isScramble(s1.substring(0, i), s2.substring(0, i))\n\n &&\n\n // right part of first and second string;\n isScramble(s1.substring(i), s2.substring(i))\n );\n\n // if without swap give us right answer then we do not need\n // to call the recursion withswap\n if (withoutswap) {\n mp.put(key, true);\n return true;\n }\n\n // ex of withswap: gr|eat rge|at\n // here we compare "gr" with "at" and "eat" with "rge"\n boolean withswap = (\n // left part of first and right part of second\n isScramble(s1.substring(0, i), s2.substring(n - i))\n\n &&\n\n // right part of first and left part of second\n isScramble(s1.substring(i), s2.substring(0, n - i))\n );\n\n // if withswap give us right answer then we return true\n // otherwise the for loop do it work\n if (withswap) {\n mp.put(key, true);\n return true;\n }\n // we are not returning false in else case\n // because we want to check further cases with the for loop\n }\n mp.put(key, false);\n return false;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n//for storing already solved problems\n unordered_map<string,bool> mp;\n \n \n bool isScramble(string s1, string s2) {\n //base cases\n \n int n = s1.size();\n \n //if both string are not equal in size\n if(s2.size()!=n)\n return false;\n \n //if both string are equal\n if(s1==s2)\n return true; \n \n \n \n //if code is reached to this condition then following this are sure:\n //1. size of both string is equal\n //2. string are not equal\n //so size is equal (where size==1) and they are not equal then obviously false\n //example \'a\' and \'b\' size is equal ,string are not equal\n if(n==1)\n return false;\n \n string key = s1+" "+s2;\n \n\t\t//check if this problem has already been solved\n if(mp.find(key)!=mp.end())\n return mp[key];\n \n //for every iteration it can two condition \n //1.we should proceed without swapping\n //2.we should swap before looking next\n for(int i=1;i<n;i++)\n {\n\n //ex of without swap: gr|eat and rg|eat\n bool withoutswap = (\n //left part of first and second string\n isScramble(s1.substr(0,i),s2.substr(0,i)) \n \n &&\n \n //right part of first and second string;\n isScramble(s1.substr(i),s2.substr(i))\n );\n \n \n \n //if without swap give us right answer then we do not need \n //to call the recursion withswap\n if(withoutswap)\n return true;\n \n //ex of withswap: gr|eat rge|at\n\t\t\t//here we compare "gr" with "at" and "eat" with "rge"\n bool withswap = (\n //left part of first and right part of second \n isScramble(s1.substr(0,i),s2.substr(n-i)) \n \n &&\n \n //right part of first and left part of second\n isScramble(s1.substr(i),s2.substr(0,n-i)) \n );\n \n \n \n //if withswap give us right answer then we return true\n //otherwise the for loop do it work\n if(withswap)\n return true;\n //we are not returning false in else case \n //because we want to check further cases with the for loop\n }\n \n \n return mp[key] = false;\n \n }\n};\n```\n``` Python []\nclass Solution(object):\n def isScramble(self, s1, s2):\n """\n :type s1: str\n :type s2: str\n :rtype: bool\n """\n # Base cases\n\n n = len(s1)\n\n # If both strings are not equal in size\n if len(s2) != n:\n return False\n\n # If both strings are equal\n if s1 == s2:\n return True\n\n # If code is reached to this condition then following this are sure:\n # 1. size of both string is equal\n # 2. string are not equal\n # so size is equal (where size==1) and they are not equal then obviously false\n # example \'a\' and \'b\' size is equal, string are not equal\n if n == 1:\n return False\n\n key = s1 + " " + s2\n\n # Check if this problem has already been solved\n if key in self.mp:\n return self.mp[key]\n\n # For every iteration it can two condition\n # 1. We should proceed without swapping\n # 2. We should swap before looking next\n for i in range(1, n):\n # ex of without swap: gr|eat and rg|eat\n without_swap = (\n # Left part of first and second string\n self.isScramble(s1[:i], s2[:i])\n and\n # Right part of first and second string;\n self.isScramble(s1[i:], s2[i:])\n )\n\n # If without swap gives us the right answer then we do not need\n # to call the recursion with swap\n if without_swap:\n return True\n\n # ex of with swap: gr|eat rge|at\n # here we compare "gr" with "at" and "eat" with "rge"\n with_swap = (\n # Left part of first and right part of second\n self.isScramble(s1[:i], s2[n-i:])\n and\n # Right part of first and left part of second\n self.isScramble(s1[i:], s2[:n-i])\n )\n\n # If with swap gives us the right answer then we return True\n # otherwise, the for loop does its work\n if with_swap:\n return True\n\n self.mp[key] = False\n return False\n\n # for storing already solved problems\n mp = {}\n\n```\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```\n```
8,519
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
7,542
100
\n\n# Happy Sri Ram Navami to all !! \uD83D\uDEA9\uD83D\uDEA9\uD83D\uDEA9\n![image.png]()\n# NOTE:- if you found anyone\'s post helpful please upvote that post because some persons are downvoting unneccesarily, and you are the one guys that save our post from getting unvisible, upvote for remains visible for others so and other people can also get benefitted.\n\n##### \u2022\tThere are several ways to solve the Scramble String problem\n##### \u2022\tRecursion with memoization: This is the approach used in the solution we discussed earlier. The idea is to recursively check all possible splits of the two strings, and memoize the results to avoid recomputing the same substrings multiple times.\n##### \u2022\tDynamic programming: This approach involves building a 3D table to store the results of all possible substrings of the two strings. The table is filled in a bottom-up manner, starting with the smallest substrings and building up to the largest substrings. The table can then be used to check if the two strings are scrambled versions of each other.\n##### \u2022\tTop-down dynamic programming: This approach is similar to recursion with memoization, but uses a 3D table to store the results of all possible substrings of the two strings. The table is filled in a top-down manner, starting with the largest substrings and building down to the smallest substrings. The table can then be used to check if the two strings are scrambled versions of each other.\n##### \u2022\tBFS: This approach involves using a queue to generate all possible scrambled versions of one of the strings, and checking if any of them match the other string. The idea is to generate all possible substrings of the first string, and then generate all possible permutations of each substring. The resulting strings can then be checked to see if they match the second string.\n##### \u2022\tAll of these approaches have the same time and space complexity of O(n^4), but they differ in their implementation details and performance characteristics.\n\n# Intuition & Approach\n\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tThe problem is to determine if two strings s1 and s2 are scrambled versions of each other. The algorithm works by recursively splitting the strings into two non-empty substrings and swapping them randomly. The algorithm stops when the length of the string is 1.\n##### \u2022\tThe approach used to solve the problem use a recursive function that checks if the two strings are scrambled versions of each other. The function checks if the two strings are equal, and if not, it checks if the two strings have the same characters and if the substrings of the two strings are scrambled versions of each other.\n##### \u2022\tThe algorithm uses an unordered map to store the results of previously computed substrings to avoid recomputing them. It also uses three vectors to keep track of the frequency of characters in the two strings and the current substring being checked.\n##### \u2022\tThe intuition behind the algorithm is that if two strings are scrambled versions of each other, then they can be split into two non-empty substrings that are also scrambled versions of each other. The algorithm checks all possible splits of the two strings and recursively checks if the substrings are scrambled versions of each other.\n##### \u2022\tThe algorithm starts by checking if the two strings are equal. If they are, it returns true. If not, it initializes three vectors to keep track of the frequency of characters in the two strings and the current substring being checked. It then checks if the current substring of s1 and s2 have the same characters. If they do, it recursively checks if the substrings of s1 and s2 are scrambled versions of each other. If they are, it returns true.\n##### \u2022\tIf the current substrings of s1 and s2 do not have the same characters, the algorithm checks all possible splits of the two strings. For each split, it checks if the substrings of s1 and s2 are scrambled versions of each other. If they are, it returns true.\n##### \u2022\tThe algorithm uses an unordered map to store the results of previously computed substrings to avoid recomputing them. If the current substring of s1 and s2 has already been computed, the algorithm returns the stored result.\n##### \u2022\tOverall, the algorithm uses a recursive approach to check if two strings are scrambled versions of each other. It uses an unordered map and three vectors to store previously computed substrings and keep track of the frequency of characters in the two strings and the current substring being checked.\n\n\n# here\'s the complete recursion tree for the isScramble method with s1 = "great" and s2 = "rgeat"\n\n```\nisScramble("great", "rgeat")\n / | | | \\\nisScramble("g", "r") isScramble("g", "at") isScramble("gr", "ra") isScramble("gr", "eat") isScramble("gre", "rge")\n | / | | | \\ | / |\nisScramble("", "") isScramble("g", "a") isScramble("g", "r") isScramble("g", "e") isScramble("g", "r") isScramble("g", "r") isScramble("gr", "e") isScramble("gr", "g") isScramble("gr", "er") isScramble("gr", "gea") isScramble("gre", "rg") isScramble("gre", "er")\n / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\\nfalse false false false false false false false false false false false false false false false false false false false false false false true\n```\n\n\n# Code\n```java []\nclass Solution {\n // to store previously computed substrings\n Map<String, Boolean> map = new HashMap<>();\n\n public boolean isScramble(String s1, String s2) {\n int n = s1.length();\n // check if the two strings are equal\n if (s1.equals(s2)) {\n return true;\n }\n // initialize frequency arrays for s1, s2, and current substring\n int[] a = new int[26], b = new int[26], c = new int[26];\n // check if the current substring has already been computed\n if (map.containsKey(s1 + s2)) {\n return map.get(s1 + s2);\n }\n // check all possible splits of the two strings\n for (int i = 1; i <= n - 1; i++) {\n int j = n - i;\n // update frequency arrays for s1, s2, and current substring\n a[s1.charAt(i - 1) - \'a\']++;\n b[s2.charAt(i - 1) - \'a\']++;\n c[s2.charAt(j) - \'a\']++;\n // check if the current substring has the same characters\n if (Arrays.equals(a, b) && isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) {\n // if the substrings are scrambled versions of each other, return true\n map.put(s1 + s2, true);\n return true;\n }\n // check if the current substring and its complement have the same characters\n if (Arrays.equals(a, c) && isScramble(s1.substring(0, i), s2.substring(j)) && isScramble(s1.substring(i), s2.substring(0, j))) {\n // if the substrings are scrambled versions of each other, return true\n map.put(s1 + s2, true);\n return true;\n }\n }\n // if none of the splits result in scrambled versions, return false\n map.put(s1 + s2, false);\n return false;\n }\n}\n```\n```c++ []\nclass Solution\n{\n\t// unordered map to store previously computed substrings\n\tunordered_map<string,bool> mp;\n\npublic:\n\tbool isScramble(string s1, string s2)\n\t{\n\t\tint n = s1.size();\n\t\t// check if the two strings are equal\n\t\tif (s1 == s2)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\t// initialize frequency vectors for s1, s2, and current substring\n\t\tvector a(26, 0), b(26, 0), c(26, 0);\n\t\t// check if the current substring has already been computed\n\t\tif (mp.count(s1 + s2))\n\t\t{\n\t\t\treturn mp[s1 + s2];\n\t\t}\n\t\t// check all possible splits of the two strings\n\t\tfor (int i = 1; i <= n - 1; i++)\n\t\t{\n\t\t\tint j = n - i;\n\t\t\t// update frequency vectors for s1, s2, and current substring\n\t\t\ta[s1[i - 1] - \'a\']++;\n\t\t\tb[s2[i - 1] - \'a\']++;\n\t\t\tc[s2[j] - \'a\']++;\n\t\t\t// check if the current substring has the same characters\n\t\t\tif (a == b && isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))\n\t\t\t{\n\t\t\t\t// if the substrings are scrambled versions of each other, return true\n\t\t\t\tmp[s1 + s2] = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t// check if the current substring and its complement have the same characters\n\t\t\tif (a == c && isScramble(s1.substr(0, i), s2.substr(j)) && isScramble(s1.substr(i), s2.substr(0, j)))\n\t\t\t{\n\t\t\t\t// if the substrings are scrambled versions of each other, return true\n\t\t\t\tmp[s1 + s2] = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t// if none of the splits result in scrambled versions, return false\n\t\tmp[s1 + s2] = false;\n\t\treturn false;\n\t}\n};\n```\n```python []\nclass Solution:\n # dictionary to store previously computed substrings\n map = {}\n\n def isScramble(self, s1: str, s2: str) -> bool:\n n = len(s1)\n # check if the two strings are equal\n if s1 == s2:\n return True\n # initialize frequency lists for s1, s2, and current substring\n a, b, c = [0] * 26, [0] * 26, [0] * 26\n # check if the current substring has already been computed\n if (s1 + s2) in self.map:\n return self.map[s1 + s2]\n # check all possible splits of the two strings\n for i in range(1, n):\n j = n - i\n # update frequency lists for s1, s2, and current substring\n a[ord(s1[i - 1]) - ord(\'a\')] += 1\n b[ord(s2[i - 1]) - ord(\'a\')] += 1\n c[ord(s2[j]) - ord(\'a\')] += 1\n # check if the current substring has the same characters\n if a == b and self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):\n # if the substrings are scrambled versions of each other, return True\n self.map[s1 + s2] = True\n return True\n # check if the current substring and its complement have the same characters\n if a == c and self.isScramble(s1[:i], s2[j:]) and self.isScramble(s1[i:], s2[:j]):\n # if the substrings are scrambled versions of each other, return True\n self.map[s1 + s2] = True\n return True\n # if none of the splits result in scrambled versions, return False\n self.map[s1 + s2] = False\n return False\n```\n\n\n\n# Complexity\n\n##### \u2022\tThe time complexity of the algorithm is O(n^4), n is the length of the strings. This is because the algorithm checks all possible splits of the two strings, which takes O(n^2) time, and for each split, it recursively checks if the substrings are scrambled versions of each other, which takes O(n^2) time in the worst case. Therefore, the overall time complexity is O(n^2 * n^2) = O(n^4).\n##### \u2022\tThe space complexity of the algorithm is also O(n^4), due to the use of the unordered map to store previously computed substrings. In the worst case, the map can store all possible substrings of the two strings, which takes O(n^4) space. Additionally, the algorithm uses three arrays to keep track of the frequency of characters in the two strings and the current substring being checked, which also takes O(n^3) space in the worst case. Therefore, the overall space complexity is O(n^4).\n##### \u2022\tHowever, the use of the unordered map to store previously computed substrings allows the algorithm to avoid recomputing the same substrings multiple times, which can significantly improve the performance of the algorithm for large inputs.\n\n\n\n\n# DP Intuition\n##### \u2022\tThe problem involves checking if two strings are scrambled versions of each other.\n##### \u2022\tWe have a recursive definition of scrambling a string s, which involves dividing s into x and y, and scrambling x and y independently.\n##### \u2022\tTo check if a given string t is a scrambled string of s, we choose an index and cut s into x and y, and see if we can cut t into scrambled versions of x and y.\n##### \u2022\tWe can solve the problem using dynamic programming by defining a 3D table with variables for length, i, and j to represent the subproblems.\n##### \u2022\tEach state focuses on two substrings: a substring of s1 starting at index i with length equal to length, and a substring of s2 starting at index j with length equal to length.\n##### \u2022\tWe use a base case for substrings of length 1 and fill the table for substrings of length 2 to n.\n##### \u2022\tAt each state, we perform a split on s1 and consider all possible splits, and write down the transitions for each case.\n##### \u2022\tThe answer to the problem is dp[n][0][0], where n is the length of the input strings.\n#\tAlgorithm:\n##### \u2022\tIterate i from 0 to n-1.\n##### \u2022\tIterate j from 0 to n-1.\n##### \u2022\tSet dp[1][i][j] to the boolean value of s1[i] == s2[j] (the base case of the DP).\n##### \u2022\tIterate length from 2 to n.\n##### \u2022\tIterate i from 0 to n + 1 - length.\n##### \u2022\tIterate j from 0 to n + 1 - length.\n##### \u2022\tIterate newLength from 1 to length - 1.\n##### \u2022\tIf dp[newLength][i][j] && dp[length-newLength][i+newLength][j+newLength]) || (dp[newLength][i][j+l-newLength] && dp[l-newLength][i+newLength][j] is true, set dp[length][i][j] to true.\n##### \u2022\tReturn dp[n][0][0].\n\n\n\n```PYTHON []\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n n = len(s1)\n # Initialize a 3D table to store the results of all possible substrings of the two strings\n dp = [[[False for _ in range(n)] for _ in range(n)] for _ in range(n+1)]\n\n # Initialize the table for substrings of length 1\n for i in range(n):\n for j in range(n):\n dp[1][i][j] = s1[i] == s2[j]\n\n # Fill the table for substrings of length 2 to n\n for length in range(2, n+1):\n for i in range(n+1-length):\n for j in range(n+1-length):\n # Iterate over all possible lengths of the first substring\n for newLength in range(1, length):\n # Check if the two possible splits of the substrings are scrambled versions of each other\n dp1 = dp[newLength][i]\n dp2 = dp[length-newLength][i+newLength]\n dp[length][i][j] |= dp1[j] and dp2[j+newLength]\n dp[length][i][j] |= dp1[j+length-newLength] and dp2[j]\n\n # Return whether the entire strings s1 and s2 are scrambled versions of each other\n return dp[n][0][0]\n```\n```JAVA []\nclass Solution {\n public boolean isScramble(String s1, String s2) {\n int n = s1.length();\n // Initialize a 3D table to store the results of all possible substrings of the two strings\n boolean[][][] dp = new boolean[n+1][n][n];\n\n // Initialize the table for substrings of length 1\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n dp[1][i][j] = s1.charAt(i) == s2.charAt(j);\n }\n }\n\n // Fill the table for substrings of length 2 to n\n for (int length = 2; length <= n; length++) {\n for (int i = 0; i <= n-length; i++) {\n for (int j = 0; j <= n-length; j++) {\n // Iterate over all possible lengths of the first substring\n for (int newLength = 1; newLength < length; newLength++) {\n // Check if the two possible splits of the substrings are scrambled versions of each other\n boolean[] dp1 = dp[newLength][i];\n boolean[] dp2 = dp[length-newLength][i+newLength];\n dp[length][i][j] |= dp1[j] && dp2[j+newLength];\n dp[length][i][j] |= dp1[j+length-newLength] && dp2[j];\n }\n }\n }\n }\n\n // Return whether the entire strings s1 and s2 are scrambled versions of each other\n return dp[n][0][0];\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n bool isScramble(string s1, string s2) {\n int n = s1.length();\n // Initialize a 3D table to store the results of all possible substrings of the two strings\n vector<vector<vector<bool>>> dp(n+1, vector<vector<bool>>(n, vector<bool>(n)));\n\n // Initialize the table for substrings of length 1\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n dp[1][i][j] = s1[i] == s2[j];\n }\n }\n\n // Fill the table for substrings of length 2 to n\n for (int length = 2; length <= n; length++) {\n for (int i = 0; i <= n-length; i++) {\n for (int j = 0; j <= n-length; j++) {\n // Iterate over all possible lengths of the first substring\n for (int newLength = 1; newLength < length; newLength++) {\n // Check if the two possible splits of the substrings are scrambled versions of each other\n vector<bool>& dp1 = dp[newLength][i];\n vector<bool>& dp2 = dp[length-newLength][i+newLength];\n dp[length][i][j] |= dp1[j] && dp2[j+newLength];\n dp[length][i][j] |= dp1[j+length-newLength] && dp2[j];\n }\n }\n }\n }\n\n // Return whether the entire strings s1 and s2 are scrambled versions of each other\n return dp[n][0][0];\n }\n};\n```\n\n# TC & SC\n\n##### \u2022\tThe time complexity of this algorithm is O(n^4), and the space complexity is also O(n^4), due to the use of the 3D table. \n##### \u2022\tHowever, this approach can be faster than the recursive approach with memoization for some inputs, since it avoids the overhead of function calls and memoization lookups.\n\n\n# 3RD WAY RECURSIVE \n\n\n```C++ []\nclass Solution {\n bool isScrambleHelper(unordered_map<string, bool> &memo, string s1, string s2) {\n int i, len = s1.size();\n bool result = false;\n\n // Base cases\n if (len == 0) {\n return true;\n } else if (len == 1) {\n return s1 == s2;\n } else {\n // Check if we have already computed the result for this pair of strings\n if (memo.count(s1 + s2)) {\n return memo[s1 + s2];\n }\n\n // Check if the two strings are equal\n if (s1 == s2) {\n result = true;\n } else {\n // Check all possible split positions\n for (i = 1; i < len && !result; ++i) {\n // Check if s1[0..i-1] and s2[0..i-1] are valid scrambles of each other\n // and if s1[i..len-1] and s2[i..len-1] are valid scrambles of each other\n result = result || (isScrambleHelper(memo, s1.substr(0, i), s2.substr(0, i)) && isScrambleHelper(memo, s1.substr(i, len - i), s2.substr(i, len - i)));\n\n // Check if s1[0..i-1] and s2[len-i..len-1] are valid scrambles of each other\n // and if s1[i..len-1] and s2[0..len-i-1] are valid scrambles of each other\n result = result || (isScrambleHelper(memo, s1.substr(0, i), s2.substr(len - i, i)) && isScrambleHelper(memo, s1.substr(i, len - i), s2.substr(0, len - i)));\n }\n }\n\n // Save the intermediate result in the memoization table\n return memo[s1 + s2] = result;\n }\n }\npublic:\n bool isScramble(string s1, string s2) {\n unordered_map<string, bool> memo;\n return isScrambleHelper(memo, s1, s2);\n }\n};\n```\n```PYTHON []\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n n = len(s1)\n if n != len(s2):\n return False\n if n == 0:\n return True\n elif n == 1:\n return s1 == s2\n else:\n memo = {}\n return self.isScrambleHelper(memo, s1, s2)\n\n def isScrambleHelper(self, memo: dict, s1: str, s2: str) -> bool:\n n = len(s1)\n result = False\n\n if n == 0:\n return True\n elif n == 1:\n return s1 == s2\n else:\n if (s1, s2) in memo:\n return memo[(s1, s2)]\n\n if s1 == s2:\n result = True\n else:\n for i in range(1, n):\n result = (self.isScrambleHelper(memo, s1[:i], s2[:i]) and self.isScrambleHelper(memo, s1[i:], s2[i:])) or \\\n (self.isScrambleHelper(memo, s1[:i], s2[n - i:]) and self.isScrambleHelper(memo, s1[i:], s2[:n - i]))\n if result:\n break\n\n memo[(s1, s2)] = result\n return result\n```\n```JAVA []\nclass Solution {\n public boolean isScramble(String s1, String s2) {\n int len = s1.length();\n if (len != s2.length()) {\n return false;\n }\n if (len == 0) {\n return true;\n } else if (len == 1) {\n return s1.equals(s2);\n } else {\n Map<String, Boolean> memo = new HashMap<>();\n return isScrambleHelper(memo, s1, s2);\n }\n }\n\n private boolean isScrambleHelper(Map<String, Boolean> memo, String s1, String s2) {\n int len = s1.length();\n boolean result = false;\n\n if (len == 0) {\n return true;\n } else if (len == 1) {\n return s1.equals(s2);\n } else {\n if (memo.containsKey(s1 + s2)) {\n return memo.get(s1 + s2);\n }\n\n if (s1.equals(s2)) {\n result = true;\n } else {\n for (int i = 1; i < len && !result; i++) {\n result = (isScrambleHelper(memo, s1.substring(0, i), s2.substring(0, i)) && isScrambleHelper(memo, s1.substring(i), s2.substring(i))) ||\n (isScrambleHelper(memo, s1.substring(0, i), s2.substring(len - i)) && isScrambleHelper(memo, s1.substring(i), s2.substring(0, len - i)));\n }\n }\n\n memo.put(s1 + s2, result);\n return result;\n }\n }\n}\n```\n\n# TC & SC\n\n##### \u2022\tThe time complexity of the given solution is O(n^4), where n is the length of the input strings. This is because we are checking all possible split positions for each substring, which takes O(n^2) time, and we are doing this for all possible substrings, which takes another O(n^2) time. The recursive calls also add to the time complexity.\n##### \u2022\tThe space complexity of the given solution is O(n^3), which is the size of the memoization table. This is because we are storing the results of all possible substring pairs in the memoization table.\n\n# 4th way cache is implemented\n```c++ []\nclass Solution {\nprivate:\n bool DP_helper(string &s1, string &s2, int idx1, int idx2, int len, char isS[]) {\n int sSize = s1.size(), i, j, k, hist[26], zero_count = 0;\n\n // Check if we have already computed the result for this substring pair\n if (isS[(len * sSize + idx1) * sSize + idx2]) {\n return isS[(len * sSize + idx1) * sSize + idx2] == 1;\n }\n\n bool res = false;\n\n // Count the frequency of each character in the two substrings\n fill_n(hist, 26, 0);\n for (k = 0; k < len; ++k) {\n zero_count += (0 == hist[s1[idx1 + k] - \'a\']) - (0 == ++hist[s1[idx1 + k] - \'a\']);\n zero_count += (0 == hist[s2[idx2 + k] - \'a\']) - (0 == --hist[s2[idx2 + k] - \'a\']);\n }\n\n // If the two substrings have different characters, return false\n if (zero_count) {\n isS[(len * sSize + idx1) * sSize + idx2] = 2;\n return false;\n }\n\n // If the length of the substrings is 1, return true\n if (len == 1) {\n isS[(len * sSize + idx1) * sSize + idx2] = 1;\n return true;\n }\n\n // Recursively check all possible split positions\n for (k = 1; k < len && !res; ++k) {\n res = res || (DP_helper(s1, s2, idx1, idx2, k, isS) && DP_helper(s1, s2, idx1 + k, idx2 + k, len - k, isS));\n res = res || (DP_helper(s1, s2, idx1 + len - k, idx2, k, isS) && DP_helper(s1, s2, idx1, idx2 + k, len - k, isS));\n }\n\n // Save the intermediate result in the cache\n isS[(len * sSize + idx1) * sSize + idx2] = res ? 1 : 2;\n return res;\n }\n\npublic:\n bool isScramble(string s1, string s2) {\n const int sSize = s1.size();\n\n // Base case: empty strings are always valid scrambles of each other\n if (0 == sSize) {\n return true;\n }\n\n // Initialize the cache\n char isS[(sSize + 1) * sSize * sSize];\n fill_n(isS, (sSize + 1) * sSize * sSize, 0);\n\n // Recursively check if s1 and s2 are valid scrambles of each other\n return DP_helper(s1, s2, 0, 0, sSize, isS);\n }\n};\n```\n# explaination \n\n##### \u2022\tIt does this by recursively checking all possible split positions of the two strings, and caching the intermediate results to avoid redundant computations. \n##### \u2022\tThe cache is implemented as a one-dimensional array isS , where isS[idx1 * sSize + idx2 + len * sSize * sSize] stores the result of checking whether the substring of s1 starting at index idx1 and the substring of s2 starting at index idx2 , both of length len , are valid scrambles of each other. The value of isS[idx1 * sSize + idx2 + len * sSize * sSize] can be either 0 (not computed yet), 1 (valid scramble), or 2 (invalid scramble). \n##### \u2022\tThe recursion is implemented in the DP_helper function, which takes as input the two strings s1 and s2 , the starting indices idx1 and idx2 , the length len , and the cache isS . \n##### \u2022\tThe function first checks if the result for this substring pair has already been computed and cached, and returns the cached result if it exists. \n##### \u2022\tOtherwise, it counts the frequency of each character in the two substrings, and returns false if the two substrings have different characters. If the length of the substrings is 1, the function returns true.\n##### \u2022\tIf the two substrings have the same character set, the function recursively checks all possible split positions and returns true if any of them are valid scrambles of each other. \n##### \u2022\tFinally, the function saves the intermediate result in the cache and returns the result. \n##### \u2022\tTo optimize the recursion, the function uses early pruning by checking if the two substrings have the same character set before recursively checking all possible split positions. \n##### \u2022\tIf the two substrings have different character sets, the function immediately returns false without doing any further computation. \n##### \u2022\tThis helps to reduce the number of recursive calls and improve the overall performance of the algorithm.\n\n\n# DRY RUN 1\n\n##### \u2022\tLet\'s dry run the algorithm with the input "great" andrgeat".\n##### \u2022\tFirst, the algorithm checks if the two strings are equal. Since they are not, it initializes the frequency vectors for s1, s2, and the current substring, and checks if the current substring has already been computed in the unordered map. Since it has not, the algorithm proceeds to check all possible splits of the two strings.\n##### \u2022\tFor the first split, i = 1 and j = 4. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "g" and "r" are different, the algorithm moves on to the next split.\n##### \u2022\tFor the second split, i = 2 and j = 3. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "gr" and "rg" have the same characters, the algorithm recursively checks if the substrings of s1 and s2 are scrambled versions of each other. It does this by calling the isScramble function with the substrings "g" and "r" for both s1 and s2. Since "g" and "r" are not scrambled versions of each other, the algorithm backtracks and checks the other possible split.\n##### \u2022\tFor the third split, i = 3 and j = 2. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "gre" and "rge" have the same characters, the algorithm recursively checks if the substrings of s1 and s2 are scrambled versions of each other. It does this by calling the isScramble function with the substrings "g" and "r" for s1 and s2, and the substrings "re" and "eat" for s1 and s2. Since "g" and "r" are not scrambled versions of each other, the algorithm backtracks and checks the other possible split.\n##### \u2022\tFor the fourth split, i = 4 and j = 1. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "reat" and "rgea" have the same characters, the algorithm recursively checks if the substrings of s1 and s2 are scrambled versions of each other. It does this by calling the isScramble function with the substrings "r" and "r" for s1 and s2, and the substrings "eat" and "gea" for s1 and s2. Since "r" and "r" are scrambled versions of each other, the algorithm proceeds to check if "eat" and "gea" are scrambled versions of each other. It does this by calling the isScramble function with the substrings "e" and "e" for s1 and s2, and the substrings "at" and "ga" for s1 and s2. Since "e" and "e" are scrambled versions of each other, the algorithm proceeds to check if "at" and "ga" are scrambled versions of each other. It does this by calling the isScramble function with the substrings "a" and "a" for s1 and s2, and the substrings "t" and "g" for s1 and s2. Since "a" and "a" are scrambled versions of each other, and "t" and "g" are scrambled versions of each other, the algorithm returns true.\n##### \u2022\tTherefore, the output of the algorithm for the input "great" and "rgeat" is true, indicating that the two strings are scrambled versions of each other.\n\n# DRY RUN 2\n##### \u2022\tLet\'s dry run the algorithm with the input "abcde" and "caebd".\n##### \u2022\tFirst, the algorithm checks if the two strings are equal. Since they are not, it initializes the frequency vectors for s1, s2, and the current substring, and checks if the current substring has already been computed in the unordered map. Since it has not, the algorithm proceeds to check all possible splits of the two strings.\n##### \u2022\tFor the first split, i = 1 and j = 4. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "a" and "c" are different, the algorithm moves on to the next split.\n##### \u2022\tFor the second split, i = 2 and j = 3. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "ab" and "ca" have different characters, the algorithm moves on to the next split.\n##### \u2022\tFor the third split, i = 3 and j = 2. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "abc" and "cae" have different characters, the algorithm moves on to the next split.\n##### \u2022\tFor the fourth split, i = 4 and j = 1. The algorithm updates the frequency vectors for s1, s2, and the current substring, and checks if the current substring has the same characters. Since "abcd" and "caeb" have different characters, the algorithm moves on to the next split.\n##### \u2022\tSince none of the splits result in scrambled versions of each other, the algorithm returns false.\n##### \u2022\tTherefore, the output of the algorithm for the input "abcde" and "caebd" is false, indicating that the two strings are not scrambled versions of each other.\n\n\n![BREUSELEE.webp]()\n\n![meme2.png]()\n\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06 \u2B06\n
8,522
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
4,507
42
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Scramble String` by `Aryan Mittal`\n![Google5.png]()\n\n\n# Approach & Intution\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n\n[`Don\'t fall for this Small Optimization, It is Leetcode\'s Test Case Bug`] \n![image.png]()\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n unordered_map<string,bool> mp;\n \n bool isScramble(string s1, string s2) {\n int n = s1.size();\n if(s1==s2) return true; \n if(n==1) return false;\n \n string key = s1+" "+s2;\n \n if(mp.find(key)!=mp.end()) return mp[key];\n\n for(int i=1;i<n;i++)\n {\n if(isScramble(s1.substr(0,i),s2.substr(0,i)) && \n isScramble(s1.substr(i),s2.substr(i)))\n return mp[key] = true;\n \n if(isScramble(s1.substr(0,i),s2.substr(n-i)) &&\n isScramble(s1.substr(i),s2.substr(0,n-i)))\n return mp[key] = true;\n }\n \n return mp[key] = false;\n }\n};\n```\n```Java []\nimport java.util.*;\n\nclass Solution {\n Map<String, Boolean> mp = new HashMap<>();\n\n public boolean isScramble(String s1, String s2) {\n int n = s1.length();\n if (s1.equals(s2)) return true;\n if (n == 1) return false;\n\n String key = s1 + " " + s2;\n\n if (mp.containsKey(key)) return mp.get(key);\n\n for (int i = 1; i < n; i++) {\n if (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))){\n mp.put(key, true);\n return true;\n }\n\n if (isScramble(s1.substring(0, i), s2.substring(n - i)) && isScramble(s1.substring(i), s2.substring(0, n - i))){\n mp.put(key, true);\n return true;\n }\n }\n\n mp.put(key, false);\n return false;\n }\n}\n```\n```Python []\nclass Solution:\n def __init__(self):\n self.mp = {}\n\n def isScramble(self, s1: str, s2: str) -> bool:\n n = len(s1)\n if s1 == s2:\n return True\n if n == 1:\n return False\n\n key = s1 + " " + s2\n\n if key in self.mp:\n return self.mp[key]\n\n for i in range(1, n):\n if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):\n self.mp[key] = True\n return True\n\n if self.isScramble(s1[:i], s2[n - i:]) and self.isScramble(s1[i:], s2[:n - i]):\n self.mp[key] = True\n return True\n\n self.mp[key] = False\n return False\n```\n
8,525
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
6,651
73
The solution uses recursion with memoization to check all possible partitions of the two strings and determine if they are scrambled versions of each other. The memoization is achieved using a dictionary m that stores the result of previous computations for the same inputs.\n\nThe func function takes in two strings s1 and s2, and returns a boolean value indicating whether they are scrambled versions of each other. The function first checks the length of the strings - if they are both of length 1, it simply compares the characters. If the sorted characters in the two strings are not equal, it returns False.\n\nOtherwise, the function loops through all possible partitions of s1 and checks if they are valid scrambles of corresponding partitions in s2. The partitions are formed by looping through the length of s1 from index 1 to the end. If a valid partition is found, the function recursively checks the remaining partitions to see if they are also valid scrambles.\n\nIf at least one valid partition is found, the function returns True and stores the result in the m dictionary. If no valid partitions are found, the function returns False and stores the result in the m dictionary.\n\nFinally, the isScramble function calls the func function with the two input strings and returns the resulting boolean value.\n# Please Upvote \uD83D\uDE07\n![image.png]()\n\n\n# Python3\n```\nclass Solution:\n def isScramble(self,s1, s2):\n m ={}\n def func(s1, s2):\n if (s1, s2) in m:\n return m[(s1, s2)]\n if not sorted(s1) == sorted(s2):\n return False\n if len(s1) == 1:\n return True\n \n\n for i in range(1, len(s1)):\n if func(s1[:i], s2[-i:]) and func(s1[i:], s2[:-i]) or func(s1[:i], s2[:i]) and func(s1[i:], s2[i:]):\n m[(s1, s2)] = True\n return True\n m[(s1, s2)] = False\n return False\n return func(s1, s2)\n\n\n\n\n\n```\n![image.png]()
8,527
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
4,645
30
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers this week. I planned to give for next 10,000 Subscribers as well. So **DON\'T FORGET** to Subscribe\n\n**Search \uD83D\uDC49`Tech Wired leetcode` on YouTube to Subscribe**\n# OR \n**Click the Link in my Leetcode Profile to Subscribe**\n\nHappy Learning, Cheers Guys \uD83D\uDE0A\n\n# Approach:\n\nWe can use dynamic programming to solve this problem. We can define a 3D boolean array dp[i][j][length] to represent whether s1[i:i+length] and s2[j:j+length] are scrambled versions of each other. The array dp will have dimensions n x n x (n+1), where n is the length of the strings. The base case is when length=1, and in this case, dp[i][j][1] is true if and only if s1[i] is equal to s2[j]. For each value of length, we can iterate through all possible starting indices i and j, and all possible split points k such that 1 <= k < length. We can then check if the substrings of s1 and s2 starting at indices i and j, respectively, and both of length k, are scrambled versions of each other, and if the substrings of s1 and s2 starting at indices i+k and j+k, respectively, and both of length length-k, are scrambled versions of each other. If either of these conditions are met, then dp[i][j][length] is true.\n\n# Intuition:\n\n- The intuition behind this approach is that if two strings s1 and s2 are scrambled versions of each other, then there must exist a split point k such that either the substrings of s1 and s2 starting at indices 0 and 0, respectively, and both of length k, are scrambled versions of each other, and the substrings of s1 and s2 starting at indices k and k, respectively, and both of length length-k, are scrambled versions of each other, or the substrings of s1 and s2 starting at indices 0 and length-k, respectively, and both of length k, are scrambled versions of each other, and the substrings of s1 and s2 starting at indices k and 0, respectively, and both of length length-k, are scrambled versions of each other. This is because a scrambled version of a string can be obtained by swapping any two non-adjacent substrings of the string.\n\n- By using dynamic programming to store the results of the subproblems, we can avoid recomputing the same subproblems multiple times, leading to a more efficient solution. The time complexity of this approach is O(n^4), and the space complexity is O(n^3)\n\n\n```Python []\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True\n if sorted(s1) != sorted(s2):\n return False\n \n n = len(s1)\n dp = [[[False] * (n+1) for _ in range(n)] for _ in range(n)]\n \n for i in range(n):\n for j in range(n):\n dp[i][j][1] = (s1[i] == s2[j])\n \n for length in range(2, n+1):\n for i in range(n-length+1):\n for j in range(n-length+1):\n for k in range(1, length):\n if (dp[i][j][k] and dp[i+k][j+k][length-k]) or (dp[i][j+length-k][k] and dp[i+k][j][length-k]):\n dp[i][j][length] = True\n break\n \n return dp[0][0][n]\n\n \n # An Upvote will be encouraging\n\n```\n```Java []\nclass Solution {\n public boolean isScramble(String s1, String s2) {\n if (s1.equals(s2)) {\n return true;\n }\n if (!Arrays.equals(s1.chars().sorted().toArray(), s2.chars().sorted().toArray())) {\n return false;\n }\n \n int n = s1.length();\n boolean[][][] dp = new boolean[n][n][n+1];\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n dp[i][j][1] = (s1.charAt(i) == s2.charAt(j));\n }\n }\n \n for (int length = 2; length <= n; length++) {\n for (int i = 0; i <= n-length; i++) {\n for (int j = 0; j <= n-length; j++) {\n for (int k = 1; k < length; k++) {\n if ((dp[i][j][k] && dp[i+k][j+k][length-k]) || (dp[i][j+length-k][k] && dp[i+k][j][length-k])) {\n dp[i][j][length] = true;\n break;\n }\n }\n }\n }\n }\n \n return dp[0][0][n];\n }\n}\n\n\n```\n```C++ []\nclass Solution {\npublic:\n bool isScramble(string s1, string s2) {\n if (s1 == s2) {\n return true;\n }\n if (!is_permutation(s1.begin(), s1.end(), s2.begin())) {\n return false;\n }\n \n int n = s1.length();\n vector<vector<vector<bool>>> dp(n, vector<vector<bool>>(n, vector<bool>(n+1, false)));\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n dp[i][j][1] = (s1[i] == s2[j]);\n }\n }\n \n for (int length = 2; length <= n; length++) {\n for (int i = 0; i <= n-length; i++) {\n for (int j = 0; j <= n-length; j++) {\n for (int k = 1; k < length; k++) {\n if ((dp[i][j][k] && dp[i+k][j+k][length-k]) || (dp[i][j+length-k][k] && dp[i+k][j][length-k])) {\n dp[i][j][length] = true;\n break;\n }\n }\n }\n }\n }\n \n return dp[0][0][n];\n }\n};\n\n\n```\n\n![image.png]()\n\n# Please UPVOTE \uD83D\uDC4D\n
8,530
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
106
5
# 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\n1. DFS Solution (TLE)\n\n```\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n def dfs(s1: str, s2: str) -> bool:\n if s1 == s2: return True\n\n for i in range(1, len(s1)):\n if (dfs(s1[:i], s2[:i]) and dfs(s1[i:], s2[i:])) or \\\n (dfs(s1[:i], s2[-i:]) and dfs(s1[i:], s2[:-i])): return True\n return False\n\n return dfs(s1,s2)\n```\n\n2. Optimized DFS (TLE - 3 tests)\n\n```\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n def dfs(s1: str, s2: str) -> bool:\n if s1 == s2: return True\n if sorted(s1) != sorted(s2): return False\n\n for i in range(1, len(s1)):\n if (dfs(s1[:i], s2[:i]) and dfs(s1[i:], s2[i:])) or \\\n (dfs(s1[:i], s2[-i:]) and dfs(s1[i:], s2[:-i])): return True\n return False\n\n return dfs(s1,s2)\n```\n\n3. DP Top-down memoization\n\n```\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n @cache\n def dp(s1: str, s2: str) -> bool:\n if s1 == s2: return True\n\n for i in range(1, len(s1)):\n if (dp(s1[:i], s2[:i]) and dp(s1[i:], s2[i:])) or \\\n (dp(s1[:i], s2[-i:]) and dp(s1[i:], s2[:-i])): return True\n return False\n\n return dp(s1,s2)\n```\n\n4. Optimized DP\n\n```\nclass Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n @cache\n def dp(s1: str, s2: str) -> bool:\n if s1 == s2: return True\n if sorted(s1) != sorted(s2): return False\n\n for i in range(1, len(s1)):\n if (dp(s1[:i], s2[:i]) and dp(s1[i:], s2[i:])) or \\\n (dp(s1[:i], s2[-i:]) and dp(s1[i:], s2[:-i])): return True\n return False\n\n return dp(s1,s2)\n```
8,539
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
1,763
19
Please upvote if it helps! :)\n```\nclass Solution:\n def __init__(self):\n self.scrambles = {}\n \n def isScramble(self, s1: str, s2: str) -> bool:\n if (s1, s2) in self.scrambles:\n return self.scrambles[(s1, s2)]\n if s1 == s2:\n self.scrambles[(s1, s2)] = True\n return True\n ls = len(s1)\n if ls == 1 or sorted(s1) != sorted(s2):\n self.scrambles[(s1, s2)] = False\n return False\n\n for i in range(1, ls):\n \n s1_left, s1_right = s1[:i], s1[i:]\n s2_left, s2_right = s2[:i], s2[i:]\n match1 = self.isScramble(s1_left, s2_left) and self.isScramble(s1_right, s2_right)\n \n s2_left2, s2_right2 = s2[:ls - i], s2[ls - i:]\n match2 = self.isScramble(s1_left, s2_right2) and self.isScramble(s1_right, s2_left2)\n \n if match1 or match2:\n self.scrambles[(s1, s2)] = True\n return True\n \n self.scrambles[(s1, s2)] = False\n return False
8,542
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
String,Dynamic Programming
Hard
null
1,669
13
# Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n^{2})$$\n\n# Code\n```\nclass Solution:\n def isScramble(self, first: str, second: str) -> bool:\n @cache\n def dp(a: str, b: str) -> bool:\n if a == b:\n return True\n\n if Counter(a) != Counter(b):\n return False\n\n return any(\n dp(a[:i], b[:i]) and dp(a[i:], b[i:]) or \\\n dp(a[:i], b[-i:]) and dp(a[i:], b[:-i])\n for i in range(1, len(a))\n )\n\n return dp(first, second)\n```
8,551