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
|
---|---|---|---|---|---|---|---|---|---|
Spiral Matrix | spiral-matrix | Given an m x n matrix, return all elements of the matrix in spiral order. | Array,Matrix,Simulation | Medium | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | 102,960 | 1,683 | Take the first row plus the spiral order of the rotated remaining matrix. Inefficient for large matrices, but here I got it accepted in 40 ms, one of the fastest Python submissions.\n\nPython:\n\n def spiralOrder(self, matrix):\n return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])\n\nPython 3:\n\n def spiralOrder(self, matrix):\n return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])\n\nRuby:\n```\ndef spiral_order(matrix)\n (row = matrix.shift) ? row + spiral_order(matrix.transpose.reverse) : []\nend\n```\nor\n```\ndef spiral_order(matrix)\n matrix[0] ? matrix.shift + spiral_order(matrix.transpose.reverse) : []\nend\n```\n\n### Visualization\n\nHere's how the matrix changes by always extracting the first row and rotating the remaining matrix counter-clockwise:\n\n |1 2 3| |6 9| |8 7| |4| => |5| => ||\n |4 5 6| => |5 8| => |5 4| => |5|\n |7 8 9| |4 7|\n\nNow look at the first rows we extracted:\n\n |1 2 3| |6 9| |8 7| |4| |5|\n\nThose concatenated are the desired result.\n\n### Another visualization\n```\n spiral_order([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\n= [1, 2, 3] + spiral_order([[6, 9],\n [5, 8],\n [4, 7]])\n\n= [1, 2, 3] + [6, 9] + spiral_order([[8, 7],\n [5, 4]])\n\n= [1, 2, 3] + [6, 9] + [8, 7] + spiral_order([[4],\n [5]])\n\n= [1, 2, 3] + [6, 9] + [8, 7] + [4] + spiral_order([[5]])\n\n= [1, 2, 3] + [6, 9] + [8, 7] + [4] + [5] + spiral_order([])\n\n= [1, 2, 3] + [6, 9] + [8, 7] + [4] + [5] + []\n\n= [1, 2, 3, 6, 9, 8, 7, 4, 5]\n``` | 5,222 |
Spiral Matrix | spiral-matrix | Given an m x n matrix, return all elements of the matrix in spiral order. | Array,Matrix,Simulation | Medium | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | 12,148 | 114 | \n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n![image.png]()\n\n# BRUTE\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force Approach:\n\nUse a stack and a 2D array to traverse the matrix in spiral order. It starts at the top-left corner of the matrix and pushes the coordinates onto the stack. It then pops the coordinates from the stack and checks if they are within the boundaries of the matrix and if they have been visited before. If they have not been visited, the value at that coordinate is added to the answer list and the coordinate is marked as visited. The program then checks the next coordinate in the direction of traversal (which is determined by the direction array) and pushes it onto the stack. If the next coordinate is out of bounds or has been visited before, the direction of traversal is changed by incrementing the index of the direction array. The program continues to pop coordinates from the stack until it is empty, at which point it returns the answer list.\n\n```java []\npublic List<Integer> spiralOrder(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n List<Integer> answer = new ArrayList<>();\n int[][] direction = {{1,0}, {0,-1}, {-1,0}, {0,1}};\n int[][] visited = new int[m][n];\n for(int i = 0; i < m; i++) {\n Arrays.fill(visited[i], 0);\n }\n Consumer<int[]> traverse = (coord) -> {\n int index = 3;\n Stack<int[]> stack = new Stack<>();\n stack.push(coord);\n while(!stack.isEmpty()) {\n coord = stack.pop();\n if(coord[0] >= m || coord[0] < 0 || coord[1] >= n || coord[1] < 0 || visited[coord[0]][coord[1]] == 1) {\n continue;\n }\n answer.add(matrix[coord[0]][coord[1]]);\n visited[coord[0]][coord[1]] = 1;\n int[] coord2 = {coord[0] + direction[index][0], coord[1] + direction[index][1]};\n if(coord2[0] >= m || coord2[0] < 0 || coord2[1] >= n || coord2[1] < 0 || visited[coord2[0]][coord2[1]] == 1) {\n index = (index + 1) % 4;\n }\n coord2 = new int[]{coord[0] + direction[index][0], coord[1] + direction[index][1]};\n stack.push(coord2);\n }\n };\n traverse.accept(new int[]{0,0});\n return answer;\n}\n```\n```c++ []\nvector<int> spiralOrder(vector<vector<int>>& matrix) {\n int m = matrix.size();\n int n = matrix[0].size();\n vector<int> answer;\n vector<vector<int>> direction = {{1,0}, {0,-1}, {-1,0}, {0,1}};\n vector<vector<int>> visited(m, vector<int>(n, 0));\n function<void(vector<int>, int)> traverse = [&](vector<int> coord, int index) {\n if(coord[0] >= m || coord[0] < 0 || coord[1] >= n || coord[1] < 0 || visited[coord[0]][coord[1]] == 1) {\n return;\n }\n answer.push_back(matrix[coord[0]][coord[1]]);\n visited[coord[0]][coord[1]] = 1;\n vector<int> coord2 = {coord[0] + direction[index][0], coord[1] + direction[index][1]};\n if(coord2[0] >= m || coord2[0] < 0 || coord2[1] >= n || coord2[1] < 0 || visited[coord2[0]][coord2[1]] == 1) {\n index = (index + 1) % 4;\n }\n coord2 = {coord[0] + direction[index][0], coord[1] + direction[index][1]};\n traverse(coord2, index);\n };\n traverse({0,0}, 3);\n return answer;\n}\n```\n```python []\ndef spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n m = len(matrix)\n n = len(matrix[0])\n answer = []\n direction = [[1,0],[0,-1],[-1,0],[0,1]]\n visited = []\n for i in range(m):\n visited.append([0]*n)\n def traverse(coord, index):\n if coord[0] >= m or coord[0] < 0 or coord[1] >= n or coord[0] < 0 or visited[coord[0]][coord[1]] == 1:\n return\n answer.append(matrix[coord[0]][coord[1]])\n visited[coord[0]][coord[1]] = 1\n coord2 = [a + b for a, b in zip(coord, direction[index])]\n if coord2[0] >= m or coord2[0] < 0 or coord2[1] >= n or coord2[0] < 0 or visited[coord2[0]][coord2[1]] == 1:\n index = (index + 1) % 4\n coord2 = [a + b for a, b in zip(coord, direction[index])]\n traverse(coord2, index)\n traverse([0,0],3)\n return answer\n```\n# Complexity\n- Time complexity:O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# BETTER \n\nBetter Approach:\n\nThis approach uses four variables to keep track of the boundaries of the matrix and a variable to keep track of the direction of traversal. It starts at the top-left corner of the matrix and adds the value at that coordinate to the result list. It then checks the direction of traversal and increments or decrements the row or column index accordingly. If the index reaches a boundary, the boundary is updated and the direction of traversal is changed. The program continues to add values to the result list until it has added all the values in the matrix. Finally, it returns the result list. This approach is similar to the previous approaches, but it uses boundary variables and a character variable to keep track of the direction of traversal instead of a 2D array.\n\n\n# Code\n```java []\nclass Solution {\n public List<Integer> spiralOrder(int[][] matrix) {\n int nrow = matrix.length;\n int ncol = matrix[0].length;\n int l_wall = -1, r_wall = ncol, u_wall = 0, d_wall = nrow;\n char direction = \'r\';\n List<Integer> result = new ArrayList<>();\n int i = 0, j = 0;\n while(result.size() < nrow * ncol) {\n result.add(matrix[i][j]);\n if(direction == \'r\') {\n j++;\n if(j == r_wall) {\n r_wall--;\n j = r_wall;\n direction = \'d\';\n i++;\n }\n }\n else if(direction == \'d\') {\n i++;\n if(i == d_wall) {\n d_wall--;\n i = d_wall;\n direction = \'l\';\n j--;\n }\n }\n else if(direction == \'l\') {\n j--;\n if(j == l_wall) {\n l_wall++;\n j = l_wall;\n direction = \'u\';\n i--;\n }\n }\n else if(direction == \'u\') {\n i--;\n if(i == u_wall) {\n u_wall++;\n i = u_wall;\n direction = \'r\';\n j++;\n }\n }\n }\n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> spiralOrder(vector<vector<int>>& matrix) {\n int nrow = matrix.size();\n int ncol = matrix[0].size();\n int l_wall = -1, r_wall = ncol, u_wall = 0, d_wall = nrow;\n char direction = \'r\';\n vector<int> result;\n int i = 0, j = 0;\n while(result.size() < nrow * ncol) {\n result.push_back(matrix[i][j]);\n if(direction == \'r\') {\n j++;\n if(j == r_wall) {\n r_wall--;\n j = r_wall;\n direction = \'d\';\n i++;\n }\n }\n else if(direction == \'d\') {\n i++;\n if(i == d_wall) {\n d_wall--;\n i = d_wall;\n direction = \'l\';\n j--;\n }\n }\n else if(direction == \'l\') {\n j--;\n if(j == l_wall) {\n l_wall++;\n j = l_wall;\n direction = \'u\';\n i--;\n }\n }\n else if(direction == \'u\') {\n i--;\n if(i == u_wall) {\n u_wall++;\n i = u_wall;\n direction = \'r\';\n j++;\n }\n }\n }\n return result;\n }\n};\n```\n```PYTHON []\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n nrow, ncol = len(matrix), len(matrix[0])\n l_wall, r_wall = -1, ncol\n u_wall, d_wall = 0, nrow\n direction = \'r\'\n result = []\n i, j = 0, 0\n while len(result) < nrow * ncol:\n result.append(matrix[i][j])\n if direction == \'r\':\n j += 1\n if j == r_wall:\n r_wall -= 1\n j = r_wall\n direction = \'d\'\n i += 1\n elif direction == \'d\':\n i += 1\n if i == d_wall:\n d_wall -= 1\n i = d_wall\n direction = \'l\'\n j -= 1\n elif direction == \'l\':\n j -= 1\n if j == l_wall:\n l_wall += 1\n j = l_wall\n direction = \'u\'\n i -= 1\n elif direction == \'u\':\n i -= 1\n if i == u_wall:\n u_wall += 1\n i = u_wall\n direction = \'r\'\n j += 1\n return result\n```\n# Complexity\n- Time complexity:O(M*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# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Optimal\n\nOptimal Approach:\n\nWe can further optimize the above approach by using a single loop to traverse the matrix in a spiral order. We start by initializing the top, bottom, left, and right pointers to the edges of the matrix. We then use a single loop to traverse the matrix in a spiral order by moving the pointers inward after each traversal. We continue this process until we have visited all elements of the matrix.\n\n\n```JAVA []\nclass Solution {\n public List<Integer> spiralOrder(int[][] matrix) {\n List<Integer> result = new ArrayList<>();\n if(matrix == null || matrix.length == 0) {\n return result;\n }\n int m = matrix.length;\n int n = matrix[0].length;\n int top = 0, bottom = m - 1, left = 0, right = n - 1;\n while(top <= bottom && left <= right) {\n // Traverse right\n for(int i = left; i <= right; i++) {\n result.add(matrix[top][i]);\n }\n top++;\n // Traverse down\n for(int i = top; i <= bottom; i++) {\n result.add(matrix[i][right]);\n }\n right--;\n // Traverse left\n if(top <= bottom) {\n for(int i = right; i >= left; i--) {\n result.add(matrix[bottom][i]);\n }\n bottom--;\n }\n // Traverse up\n if(left <= right) {\n for(int i = bottom; i >= top; i--) {\n result.add(matrix[i][left]);\n }\n left++;\n }\n }\n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> spiralOrder(vector<vector<int>>& matrix) {\n vector<int> result;\n if(matrix.empty() || matrix[0].empty()) {\n return result;\n }\n int m = matrix.size();\n int n = matrix[0].size();\n int top = 0, bottom = m - 1, left = 0, right = n - 1;\n while(top <= bottom && left <= right) {\n // Traverse right\n for(int i = left; i <= right; i++) {\n result.push_back(matrix[top][i]);\n }\n top++;\n // Traverse down\n for(int i = top; i <= bottom; i++) {\n result.push_back(matrix[i][right]);\n }\n right--;\n // Traverse left\n if(top <= bottom) {\n for(int i = right; i >= left; i--) {\n result.push_back(matrix[bottom][i]);\n }\n bottom--;\n }\n // Traverse up\n if(left <= right) {\n for(int i = bottom; i >= top; i--) {\n result.push_back(matrix[i][left]);\n }\n left++;\n }\n }\n return result;\n }\n};\n```\n```PYTHON []\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n result = []\n if not matrix or not matrix[0]:\n return result\n m, n = len(matrix), len(matrix[0])\n top, bottom, left, right = 0, m - 1, 0, n - 1\n while top <= bottom and left <= right:\n # Traverse right\n for i in range(left, right + 1):\n result.append(matrix[top][i])\n top += 1\n # Traverse down\n for i in range(top, bottom + 1):\n result.append(matrix[i][right])\n right -= 1\n # Traverse left\n if top <= bottom:\n for i in range(right, left - 1, -1):\n result.append(matrix[bottom][i])\n bottom -= 1\n # Traverse up\n if left <= right:\n for i in range(bottom, top - 1, -1):\n result.append(matrix[i][left])\n left += 1\n return result\n```\n\n# ONE LINER \n```PYTHON []\ndef spiralOrder(self, matrix):\n return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])\n```\n```PYTHON3 []\ndef spiralOrder(self, matrix):\n return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])\n```\n```py []\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n result = []\n while matrix:\n result += matrix.pop(0) # pop the first row each time\n matrix = list(zip(*matrix))[::-1] # left rotate matrix 90 degree each time\n return result\n```\n# how it works step by step.\n\nThe first line of the code checks if the matrix is not empty. If the matrix is empty, it returns an empty list. If the matrix is not empty, it proceeds with the traversal.\n\n##### \u2022return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])\nThe second line of the code uses a list comprehension to extract the first row of the matrix and add it to the result list. It then uses the pop() method to remove the first row from the matrix.\n\n##### \u2022[*matrix.pop(0)]\nThe third line of the code uses the zip() function to transpose the matrix and then reverses the order of the rows using slicing. This creates a new matrix that can be traversed in the next recursive call.\n\n##### \u2022[*zip(*matrix)][::-1]\nThe fourth line of the code uses recursion to traverse the new matrix in a spiral order. The result of the recursive call is added to the result list using the + operator.\n\n##### \u2022self.spiralOrder([*zip(*matrix)][::-1])\nFinally, the result list is returned.\n\n##### \u2022return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])\nusing recursive approach to traverse the matrix in a spiral order. It extracts the first row of the matrix, removes it from the matrix, transposes the matrix, and then reverses the order of the rows to create a new matrix that can be traversed in the next recursive call. The process continues until all elements of the matrix have been added to the result list.\n# Complexity\n- Time complexity:O(M*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# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# DRY RUN\n\n\n##### \u2022\tExample 1:\n![image.png]()\n##### \u2022\tInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\n##### \u2022\tOutput: [1,2,3,6,9,8,7,4,5]\n##### \u2022\tStep-by-Step Explanation:\n##### \u2022\tInitialize the result list as an empty list.\n##### \u2022\tSet the top, bottom, left, and right pointers to the edges of the matrix. top = 0, bottom = 2, left = 0, right = 2.\n##### \u2022\tTraverse the first row from left to right and add the elements to the result list. result = [1, 2, 3]. Increment the top pointer to 1.\n##### \u2022\tTraverse the last column from top to bottom and add the elements to the result list. result = [1, 2, 3, 6, 9]. Decrement the right pointer to 1.\n##### \u2022\tCheck if top <= bottom. Since it is true, traverse the last row from right to left and add the elements to the result list. result = [1, 2, 3, 6, 9, 8, 7]. Decrement the bottom pointer to 1.\n##### \u2022\tCheck if left <= right. Since it is true, traverse the first column from bottom to top and add the elements to the result list. result = [1, 2, 3, 6, 9, 8, 7, 4, 5]. Increment the left pointer to 1.\n##### \u2022\tCheck if top <= bottom. Since it is false, the traversal is complete. Return the result list.\n##### \u2022\tExample 2:\n![image.png]()\n##### \u2022\tInput: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n##### \u2022\tOutput: [1,2,3,4,8,12,11,10,9,5,6,7]\n##### \u2022\tStep-by-Step Explanation:\n##### \u2022\tInitialize the result list as an empty list.\n##### \u2022\tSet the top, bottom, left, and right pointers to the edges of the matrix. top = 0, bottom = 2, left = 0, right = 3.\n##### \u2022\tTraverse the first row from left to right and add the elements to the result list. result = [1, 2, 3, 4]. Increment the top pointer to 1.\n##### \u2022\tTraverse the last column from top to bottom and add the elements to the result list. result = [1, 2, 3, 4, 8, 12]. Decrement the right pointer to 2.\n##### \u2022\tCheck if top <= bottom. Since it is true, traverse the last row from right to left and add the elements to the result list. result = [1, 2, 3, 4, 8, 12, 11, 10, 9]. Decrement the bottom pointer to 1.\n##### \u2022\tCheck if left <= right. Since it is true, traverse the first column from bottom to top and add the elements to the result list. result = [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. Increment the left pointer to 1.\n##### \u2022\tCheck if top <= bottom. Since it is false, the traversal is complete. Return the result list.\n\n\n\n![BREUSELEE.webp]()\n![image.png]()\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 | 5,224 |
Spiral Matrix | spiral-matrix | Given an m x n matrix, return all elements of the matrix in spiral order. | Array,Matrix,Simulation | Medium | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | 9,813 | 98 | ### \u2705 Upvote if it helps! \n\n# Code :\n```\nclass Solution(object):\n def spiralOrder(self, matrix):\n result = []\n while matrix:\n result += matrix.pop(0) # 1\n\n if matrix and matrix[0]: # 2 \n for line in matrix:\n result.append(line.pop())\n\n if matrix: # 3\n result += matrix.pop()[::-1]\n\n if matrix and matrix[0]: # 4\n for line in matrix[::-1]:\n result.append(line.pop(0))\n return result\n```\n\n\n# Step by step :\n<!-- Describe your approach to solving the problem. -->\nLet\'s explain what\'s inside the loop step by step with an example:\n\n\n- **Initial state**:\n<p align="center">\n<img src="" alt="drawing" width="100"/>\n</p>\n\n- **Step 1**:\n```\nresult += matrix.pop(0)\n```\nWe add the first line to the result and delete it from the initial matrix.\n<p align="center">\n<img src="" alt="drawing" width="100"/>\n</p>\n\n- **Step 2**:\n```\nfor line in matrix:\n result.append(line.pop())\n```\nWe iterate over the lines *(in green)* and we are popping the ***last*** item of each line (in red).\n<p align="center">\n<img src="" alt="drawing" width="100"/>\n</p>\n\n\n\n- **Step 3**:\n```\nresult += matrix.pop()[::-1]\n```\nWe add the last line in a reverse order.\n<p align="center">\n<img src="" alt="drawing" width="100"/>\n</p>\n\n\n\n\n- **Step 4**:\n```\nfor line in matrix[::-1]:\n result.append(line.pop(0))\n```\nWe iterate over the lines and we are popping the ***first*** item of each line (in red).\n\n<p align="center">\n<img src="" alt="drawing" width="100"/>\n</p>\n\n\n\nWhen we escape the loop, it means that the matrix is empty and that we explored all cells.\nWe cans then return the result.\n\n# **Upvote if it helps!** \uD83D\uDE00\n\n\n\n | 5,256 |
Spiral Matrix | spiral-matrix | Given an m x n matrix, return all elements of the matrix in spiral order. | Array,Matrix,Simulation | Medium | Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not. | 38,333 | 319 | # UPVOTE \n```\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n res = []\n if len(matrix) == 0:\n return res\n row_begin = 0\n col_begin = 0\n row_end = len(matrix)-1 \n col_end = len(matrix[0])-1\n while (row_begin <= row_end and col_begin <= col_end):\n for i in range(col_begin,col_end+1):\n res.append(matrix[row_begin][i])\n row_begin += 1\n for i in range(row_begin,row_end+1):\n res.append(matrix[i][col_end])\n col_end -= 1\n if (row_begin <= row_end):\n for i in range(col_end,col_begin-1,-1):\n res.append(matrix[row_end][i])\n row_end -= 1\n if (col_begin <= col_end):\n for i in range(row_end,row_begin-1,-1):\n res.append(matrix[i][col_begin])\n col_begin += 1\n return res\n \n \n \n``` | 5,294 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 3,842 | 27 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n\n reachable = 0\n\n for i in range(len(nums)):\n\n if i>reachable:\n return False \n\n reachable = max(reachable, i+nums[i])\n \n return True\n \n``` | 5,306 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 38,764 | 364 | When I first see this problem, two things pop up in my mind:\n* Maybe I can do some sort of DFS, BFS (with backtracking?) but there will be a lot of redundancies\n* Then this begs for Dynamic Programming!\n\nBut my gut feeling was saying that this problem has to have a simpler approach.\n\nSo, here is my thinking process:\n* Base case: last index can trivially reach to last index.\n* **Q1**: How can I reach to the last index (I will call it `last_position`) from a preceding index?\n\t* If I have a preceding index `idx` in `nums` which has jump count `jump` which satisfies `idx+jump >= last_position`, I know that this `idx` is good enough to be treated as the last index because all I need to do now is to get to that `idx`. I am going to treat this new `idx` as a new `last_position`.\n* I ask **Q1** again.\n\nSo now, here are two important things:\n* If we have indices which are like **sinkholes**, those with 0 as jump and every other preceding index can only jump to that sinkhole, our `last_position` will not be updated anymore because `idx+jump >= last_position` will not be satisfied at that sinkhole and every other preceding index cannot satisfy the `idx+jump >= last_position` condition since their jumps are not big enough.\nE.g. ```nums=[3,2,1,0,4] # Here 0 is a sinkhole becuase all preceding indices can only jump to the sinkhole```\n* If we have **barriers**, those indices with 0 as jump, but the preceding indices contain jumps which can go beyond those barriers, `idx+jump >= last_position` will be satisfied and `last_position` will be updated.\nE.g. ```nums=[3,2,2,0,4] # Here 0 is just a barrier since the index before that 0 can jump *over* that barrier```\n\nFinally ask this question when we have finished looping\n* Is the last position index of 0? (i.e, have we reached to the beginning while doing the process of jumping and updating the `last_position`?)\n* If we have sinkholes in `nums`, our `last_position` will not be 0. Thus, `False` will be retured.\n\nThat\'s all!\n\nThis is what I have in mind when I was thinking of this approach :D\n![image]()\n\n## Python\n``` python\n1. class Solution:\n2. def canJump(self, nums: List[int]) -> bool:\n3. last_position = len(nums)-1\n4. \n5. for i in range(len(nums)-2,-1,-1): # Iterate backwards from second to last item until the first item\n6. if (i + nums[i]) >= last_position: # If this index has jump count which can reach to or beyond the last position\n7. last_position = i # Since we just need to reach to this new index\n8. return last_position == 0\t\n```\n\nBut in the interview, this approach may not be apparent or maybe the interviewer is looking for something. \n\n | 5,315 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 3,252 | 30 | # Intuition\nChange the destination point backwards. \n# Approach\nInitially, first destination point is last index. Change destination point to index of first previous element that can jump to current goal. That way we can, tecnically, consider this new goal as destination point cause once we can reach to it we can automatically get to original goal as well. In the end, if last updated goal happens to be very first element or zero index then it means that we can get to the original last index destination point from zero index.\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n #original destination is last index\n goal = len(nums)-1\n\n #check backwards\n for i in range(len(nums)-2,-1,-1):\n #if we can jump then update\n if i+nums[i] >= goal:\n goal = i\n\n #check if we can reach from first index\n return True if goal == 0 else False #return goal == 0\n\n``` | 5,317 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 16,195 | 107 | # **Java Solution:**\n```\nclass Solution {\n public boolean canJump(int[] nums) {\n // Take curr variable to keep the current maximum jump...\n int curr = 0;\n // Traverse all the elements through loop...\n for (int i = 0; i < nums.length; i++) {\n // If the current index \'i\' is less than current maximum jump \'curr\'...\n // It means there is no way to jump to current index...\n // so we should return false...\n if (i > curr) {\n return false;\n }\n // Update the current maximum jump...\n curr = Math.max(curr, i + nums[i]); // It\u2019s possible to reach the end of the array...\n }\n return true;\n }\n}\n```\n\n# **C++ Solution:**\n```\nclass Solution {\npublic:\n bool canJump(vector<int>& nums) {\n int idx = 0;\n //check what is the maximum index we can reach from that index...\n for (int maximum = 0; idx < nums.size() && idx <= maximum; ++idx)\n maximum = max(idx + nums[idx], maximum); //if the maximum index reached is the last index of the array...\n return idx == nums.size();\n }\n};\n```\n\n# **Python Solution:**\n```\nclass Solution(object):\n def canJump(self, nums):\n # Take curr variable to keep the current maximum jump...\n curr = nums[0]\n # Traverse all the elements through loop...\n for i in range(1,len(nums)):\n # If the current index \'i\' is less than current maximum jump \'curr\'...\n # It means there is no way to jump to current index...\n # so we should return false...\n if curr == 0:\n return False\n curr -= 1\n # Update the current maximum jump...\n curr = max(curr, nums[i]) # It\u2019s possible to reach the end of the array...\n return True\n```\n\n# **JavaScript Solution:**\n```\nvar canJump = function(nums) {\n // Base condition...\n if(nums.length <= 1)\n return true;\n // To keep the maximum index that can be reached...\n let maximum = nums[0];\n // Traverse all the elements through loop...\n for(let i = 0; i < nums.length; i++){\n //if there is no way to jump to next...\n // so we should return false...\n if(maximum <= i && nums[i] == 0) \n return false;\n //update the maximum jump... \n if(i + nums[i] > maximum){\n maximum = i + nums[i];\n }\n //maximum is enough to reach the end...\n if(maximum >= nums.length-1) \n return true;\n }\n return false; \n};\n```\n\n# **C Language:**\n```\nbool canJump(int* nums, int numsSize){\n int jump = 0;\n for (int i = 0; i < numsSize; i++) {\n if (jump < i) {\n break;\n }\n if (jump < i + nums[i]) {\n jump = i + nums[i];\n }\n if (jump >= numsSize - 1) {\n return true;\n }\n }\n return false;\n}\n```\n\n# **Python3 Solution:**\n```\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n # Take curr variable to keep the current maximum jump...\n curr = nums[0]\n # Traverse all the elements through loop...\n for i in range(1,len(nums)):\n # If the current index \'i\' is less than current maximum jump \'curr\'...\n # It means there is no way to jump to current index...\n # so we should return false...\n if curr == 0:\n return False\n curr -= 1\n # Update the current maximum jump...\n curr = max(curr, nums[i]) # It\u2019s possible to reach the end of the array...\n return True\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...** | 5,324 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 848 | 7 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key mindset here is to use a counter to count on residual steps.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake k as your residual steps. Everytime you move, k-1. If nums[i] offers you more steps, take it! If you run out of your move and can\'t move to finishing line, you fail. Otherwise, return True.\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 canJump(self, nums: List[int]) -> bool:\n if len(nums)==1:\n return True\n k = nums[0]\n for i in range(len(nums)-1):\n if nums[i] > k:\n k = nums[i]\n k = k - 1\n if k < 0 :\n return False\n return True\n\n``` | 5,327 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 4,461 | 8 | # Approach\nCreate an array containing information whether you can get to the i-th position.\nWe can simply go through all elements of the array and then iterate over all possible jump lengths updating information in our boolean array.\n\n# Complexity\n- Time complexity: $$O(nk)$$, where k is a sum of all jumps (sum of nums array)\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n n=len(nums)\n dp=[False for _ in range(n)]\n dp[0]=True\n\n for i in range(n):\n if dp[i]: # if this position is reachable\n for j in range(1,nums[i]+1):\n if i+j<n:\n dp[i+j]=True\n if i+j==n-1:\n return True\n return dp[n-1]\n``` | 5,333 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 2,865 | 10 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI can start from the finish line and problems only appear when there is a zero\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses a greedy approach to iterate from the last index `j` towards the first index. It starts with `j` set to the last index of `nums`.\n\nIn each iteration, it checks if the element at index `j-1` is greater than 0. If it is, it means we can jump from index `j-1` to index `j`. In this case, it decrements `j` by 1 and continues to the next iteration.\n\nIf the element at index `j-1` is 0, it means we cannot jump from index `j-1` to index `j`. In this case, it enters a nested loop starting from index `i` set to `j-1` and iterates towards the first index (`i <= 0`).\n\nWithin the nested loop, it checks if the value at index `i` (`nums[i]`) is less than the distance between `j` and `i` (`j-i`). If it is, it means it is not possible to jump from index `i` to index `j` based on the value at index `i`. In this case, it decrements `i` by 1 and continues to check the previous indices.\n\nIf the nested loop reaches the first index (`i <= 0`) without finding a suitable index to jump from, it means it is not possible to reach the last index of `nums`. In this case, the code returns `False`.\n\nIf the outer loop completes and exits without encountering any issues, it means it is possible to reach the last index of `nums` based on the given jump values. The code then returns `True`.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n j=len(nums)-1\n\n while j>0:\n if nums[j-1]>0:\n j-=1\n else:\n i=j-1\n while nums[i]<j-i:\n if i<=0:\n return False\n i-=1\n j=i\n return True\n\n``` | 5,338 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 958 | 6 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n### Greedy TO(n) SO(1)\nMaintain a reachable variable and update it on every iteration, if we are ahead of reachable that means it\'s not possible. else reachle will be equal to n\n\n### DP TO(n^2) SO(n)\nUsing a 1d array to mark evry reachable destination by True and then check if we reached on then end or not.\n\n\n### Recurssive TO(n^n) SO(1)\nTry running DFS on every possible value and check if reached in the end or not.\n\n\n\n# Code\n```\n#Greedy\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n reacable = 0\n for i in range(len(nums)):\n if reacable < i :\n return False\n reacable = max(reacable, i+nums[i])\n return True\n```\n```\n#DP\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n n =len(nums)\n dp = [False for i in range(n)]\n dp[0] = True\n \n for i in range(n):\n if dp[i]:\n for j in range(i+1, i+nums[i]+1):\n if j < n:\n dp[j] = True\n if j == n - 1:\n return True\n return dp[n-1]\n```\n```\n#Recurssive\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n def dfs(i, n, nums):\n if i > n:\n return False\n if i == n:\n return True\n ans = False\n for e in range(1, nums[i]+1):\n ans = ans or dfs(e+i, n, nums)\n return ans\n return dfs(0, len(nums)-1, nums)\n```\n\n# Upvote if it\'s helpfulll. | 5,342 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 61,535 | 501 | **Solution 1**\n\nGoing forwards. `m` tells the maximum index we can reach so far.\n\n def canJump(self, nums):\n m = 0\n for i, n in enumerate(nums):\n if i > m:\n return False\n m = max(m, i+n)\n return True\n\n**Solution 2**\n\nOne-liner version:\n\n def canJump(self, nums):\n return reduce(lambda m, (i, n): max(m, i+n) * (i <= m), enumerate(nums, 1), 1) > 0\n\n**Solution 3**\n\nGoing backwards, most people seem to do that, here's my version.\n\n def canJump(self, nums):\n goal = len(nums) - 1\n for i in range(len(nums))[::-1]:\n if i + nums[i] >= goal:\n goal = i\n return not goal\n\n**Solution 4**\n\nC version.\n\n bool canJump(int* nums, int n) {\n int goal=n-1, i;\n for (i=n; i--;)\n if (i+nums[i] >= goal)\n goal=i;\n return !goal;\n } | 5,348 |
Jump Game | jump-game | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. | Array,Dynamic Programming,Greedy | Medium | null | 2,113 | 27 | # Intuition of this Problem:\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. Initialize a variable reach to 0, which represents the farthest index that can be reached so far.\n2. Loop through the array nums and for each index i, do the following:\n - a. If i is greater than reach or reach is greater than or equal to nums.length - 1, break the loop as it means reaching the last index is not possible.\n - b. Update the value of reach as the maximum of reach and i + nums[i].\n1. Return reach >= nums.length - 1, which means that the last index can be reached or not.\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 bool canJump(vector<int>& nums) {\n int n = nums.size();\n int reach = 0;\n for (int i = 0; i < n; i++) {\n // (i > reach) will cover [1,1,0,1,2] or [0,0,0....]\n if(i > reach || reach >= n-1)\n break;\n //this reach will store upto which index we can jump from that ith index\n reach = max(reach, i + nums[i]);\n }\n if (reach >= n-1)\n return true;\n //this "return false" means definitely (i > reach) at any point\n return false;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean canJump(int[] nums) {\n int reach = 0;\n for (int i = 0; i < nums.length; i++) {\n if (i > reach || reach >= nums.length - 1) break;\n reach = Math.max(reach, i + nums[i]);\n }\n return reach >= nums.length - 1;\n }\n}\n\n```\n```Python []\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n reach = 0\n for i in range(len(nums)):\n if i > reach or reach >= len(nums) - 1:\n break\n reach = max(reach, i + nums[i])\n return reach >= len(nums) - 1\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the length of the array nums. This is because we are looping through the entire nums array once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**, as we are using a single integer variable reach.\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 5,381 |
Merge Intervals | merge-intervals | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. | Array,Sorting | Medium | null | 36,773 | 482 | ```C++ []\nclass Solution {\npublic:\n vector<vector<int>> merge(vector<vector<int>>& intervals) {\n \n if(intervals.size()==1)\n return intervals;\n vector<pair<int,int>> p;\n for(int i=0;i<intervals.size();i++)\n {\n p.push_back({intervals[i][0],intervals[i][1]});\n } \n sort(p.begin(),p.end());\n\n vector<vector<int>> ans;\n int f=p[0].first,s=p[0].second;\n for(int i=0;i<p.size()-1;i++)\n {\n vector<int> a(2);\n if(s>=p[i+1].first)\n {\n s=max(s,p[i+1].second);\n }\n else\n {\n a[0]=f;\n a[1]=s;\n f=p[i+1].first;\n s=p[i+1].second;\n ans.push_back(a);\n }\n } \n int n=intervals.size();\n ans.push_back({f,s});\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals = sorted(intervals, key=lambda x: x [0])\n\n ans = []\n\n for interval in intervals:\n if not ans or ans[-1][1] < interval[0]:\n ans.append(interval)\n else:\n ans[-1][1] = max(ans[-1][1], interval[1])\n \n return ans\n```\n\n```Java []\nclass Solution {\n public int[][] merge(int[][] intervals) {\n\t\tint min = Integer.MAX_VALUE;\n\t\tint max = Integer.MIN_VALUE;\n\t\t\n\t\tfor (int i = 0; i < intervals.length; i++) {\n\t\t\tmin = Math.min(min, intervals[i][0]);\n\t\t\tmax = Math.max(max, intervals[i][0]);\n\t\t}\n\t\t\n\t\tint[] range = new int[max - min + 1];\n\t\tfor (int i = 0; i < intervals.length; i++) {\n\t\t\trange[intervals[i][0] - min] = Math.max(intervals[i][1] - min, range[intervals[i][0] - min]); \n\t\t}\n\t\t\n\t\tint start = 0, end = 0;\n\t\tLinkedList<int[]> result = new LinkedList<>();\n\t\tfor (int i = 0; i < range.length; i++) {\n\t\t\tif (range[i] == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i <= end) {\n\t\t\t\tend = Math.max(range[i], end);\n\t\t\t} else {\n\t\t\t\tresult.add(new int[] {start + min, end + min});\n\t\t\t\tstart = i;\n\t\t\t\tend = range[i];\n\t\t\t}\n\t\t}\n\t\tresult.add(new int[] {start + min, end + min});\n\t\treturn result.toArray(new int[result.size()][]);\n\t}\n}\n```\n | 5,400 |
Merge Intervals | merge-intervals | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. | Array,Sorting | Medium | null | 112,619 | 557 | Just go through the intervals sorted by start coordinate and either combine the current interval with the previous one if they overlap, or add it to the output by itself if they don't.\n\n def merge(self, intervals):\n out = []\n for i in sorted(intervals, key=lambda i: i.start):\n if out and i.start <= out[-1].end:\n out[-1].end = max(out[-1].end, i.end)\n else:\n out += i,\n return out | 5,438 |
Merge Intervals | merge-intervals | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. | Array,Sorting | Medium | null | 7,179 | 27 | # My youtube channel - KeetCode(Ex-Amazon)\nI create 158 videos for leetcode questions as of April 28, 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**My youtube channel - KeetCode(Ex-Amazon)**\nThere is my channel link under picture in LeetCode profile.\n\n\n\n---\n\n# Intuition\nSort intervals with start points. It takes advantage of the fact that the intervals are sorted by start point, which allows us to avoid comparing every interval to every other interval.\n\n# Approach\nThis is based on Python code. Other languages might be different.\n\n1. The merge method takes a list of lists as an argument. Each inner list represents an interval, and the first element of the inner list is the start point, and the second element is the end point.\n\n2. Check if the given list is empty, if yes, return an empty list.\n\n3. Initialize an empty list named merged to store the merged intervals.\n\n4. Sort the given list of intervals by the first element of each interval using the sort method and a lambda function.\n\n5. Set the variable prev to the first interval of the sorted intervals list.\n\n6. Iterate over the sorted intervals list, starting from the second interval.\n\n7. Check if the start point of the current interval is less than or equal to the end point of the previous interval.\n\n8. If yes, then update the end point of the previous interval with the maximum of the current interval\'s end point and the previous interval\'s end point.\n9. If no, then append the previous interval to the merged list and set prev to the current interval.\n\n10. After the loop, append the last interval (prev) to the merged list.\nReturn the merged list containing the merged intervals.\n\n# Complexity\nThis is based on Python code. Other languages might be different.\n\n- Time complexity: O(n log n)\nn is the length of the input list \'intervals\'. This is because the code sorts the intervals list in O(n log n) time using the built-in Python sorting algorithm, and then iterates over the sorted list once in O(n) time to merge overlapping intervals.\n\n- Space complexity: O(n)\nn is the length of the input list \'intervals\'. This is because the code creates a new list \'merged\' to store the merged intervals, which can contain up to n elements if there are no overlapping intervals. Additionally, the code uses a constant amount of space to store the \'prev\' variable and other temporary variables, which does not depend on the size of the input.\n\n---\n\n**My youtube channel - KeetCode(Ex-Amazon)**\nThere is my channel link under picture in LeetCode profile.\n\n\n---\n\n# Python\n```\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n if not intervals:\n return []\n \n merged = []\n intervals.sort(key=lambda x: x[0])\n\n prev = intervals[0]\n\n for interval in intervals[1:]:\n if interval[0] <= prev[1]:\n prev[1] = max(prev[1], interval[1])\n else:\n merged.append(prev)\n prev = interval\n \n merged.append(prev)\n\n return merged\n```\n# JavaScript\n```\n/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\nvar merge = function(intervals) {\n if (!intervals || intervals.length === 0) {\n return [];\n }\n\n let merged = [];\n intervals.sort((a, b) => a[0] - b[0]);\n\n let mergedInterval = intervals[0];\n\n for (let i = 1; i < intervals.length; i++) {\n let interval = intervals[i];\n\n if (interval[0] <= mergedInterval[1]) {\n mergedInterval[1] = Math.max(mergedInterval[1], interval[1]);\n } else {\n merged.push(mergedInterval);\n mergedInterval = interval;\n }\n }\n\n merged.push(mergedInterval);\n\n return merged; \n};\n```\n# Java\n```\nclass Solution {\n public int[][] merge(int[][] intervals) {\n if (intervals == null || intervals.length == 0) {\n return new int[0][];\n }\n\n Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));\n\n List<int[]> merged = new ArrayList<>();\n int[] mergedInterval = intervals[0];\n\n for (int i = 1; i < intervals.length; i++) {\n int[] interval = intervals[i];\n \n if (interval[0] <= mergedInterval[1]) {\n mergedInterval[1] = Math.max(mergedInterval[1], interval[1]);\n } else {\n merged.add(mergedInterval);\n mergedInterval = interval; \n }\n }\n\n merged.add(mergedInterval);\n\n return merged.toArray(new int[merged.size()][]); \n }\n}\n```\n# C++\n```\nclass Solution {\npublic:\n vector<vector<int>> merge(vector<vector<int>>& intervals) {\n if (intervals.empty()) {\n return {};\n }\n\n sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {\n return a[0] < b[0];\n });\n\n vector<vector<int>> merged;\n vector<int> mergedInterval = intervals[0];\n\n for (int i = 1; i < intervals.size(); i++) {\n const vector<int>& interval = intervals[i];\n \n if (interval[0] <= mergedInterval[1]) {\n mergedInterval[1] = max(mergedInterval[1], interval[1]);\n } else {\n merged.push_back(mergedInterval);\n mergedInterval = interval;\n }\n }\n\n merged.push_back(mergedInterval);\n\n return merged; \n }\n};\n``` | 5,469 |
Merge Intervals | merge-intervals | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. | Array,Sorting | Medium | null | 27,206 | 182 | ```\nintervals [[1, 3], [2, 6], [8, 10], [15, 18]]\nintervals.sort [[1, 3], [2, 6], [8, 10], [15, 18]]\n\ninterval = [1,3]\nmerged =[]\nnot merged:\n\tmerged =[ [1,3] ]\n\ninterval =[2,6]\nmerged = [ [1,3] ]\nmerged[-1][-1] = 3 > interval[0] = 2:\n\tmerged[-1][-1] = max(merged[-1][-1] = 3 ,interval[-1] = 6) =6\nmerged = [[1,6]]\n```\n```\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort(key =lambda x: x[0])\n merged =[]\n for i in intervals:\n\t\t\t# if the list of merged intervals is empty \n\t\t\t# or if the current interval does not overlap with the previous,\n\t\t\t# simply append it.\n if not merged or merged[-1][-1] < i[0]:\n merged.append(i)\n\t\t\t# otherwise, there is overlap,\n\t\t\t#so we merge the current and previous intervals.\n else:\n merged[-1][-1] = max(merged[-1][-1], i[-1])\n return merged\n```\n\n* Time complexity:\n\tIn python, use sort method to a list costs [O(nlogn)](), where n is the length of the list.\n\tThe for-loop used to merge intervals, costs O(n).\n\tO(nlogn)+O(n) = O(nlogn)\n\tSo the total time complexity is O(nlogn).\n* Space complexity\n\tThe algorithm used a merged list and a variable i.\n\tIn the worst case, the merged list is equal to the length of the input intervals list. So the space complexity is O(n), where n is the length of the input list.\n\n```\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort()\n merged = []\n for i in range(len(intervals)):\n if merged == []:\n merged.append(intervals[i])\n else:\n previous_end = merged[-1][1]\n current_start = intervals[i][0]\n current_end = intervals[i][1]\n if previous_end >= current_start: # overlap\n merged[-1][1] = max(previous_end,current_end)\n else:\n merged.append(intervals[i])\n return merged\n \n``` | 5,471 |
Merge Intervals | merge-intervals | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. | Array,Sorting | Medium | null | 4,055 | 16 | # Intuition:\nThe idea is to sort the intervals by their start time, and then merge them by checking if the end time of the previous interval is greater than or equal to the start time of the current interval. If so, we merge the intervals by updating the end time of the previous interval to be the maximum of its current end time and the end time of the current interval. Otherwise, we add the previous interval to the answer vector and update the previous interval to be the current interval.\n\n# Approach:\n1. Sort the intervals based on their start time.\n2. Initialize an empty vector of vectors to store the merged intervals.\n3. Initialize a temporary vector to store the first interval from the sorted input vector.\n4. Iterate over the input intervals from the second interval.\n5. If the start time of the current interval is less than or equal to the end time of the temporary interval, update the end time of the temporary interval to be the maximum of its current end time and the end time of the current interval.\n6. Otherwise, add the temporary interval to the answer vector and update the temporary interval to be the current interval.\n7. After the loop, add the last temporary interval to the answer vector.\n8. Return the answer vector.\n# Complexity:\n- Time Complexity:\nThe time complexity of this approach is O(n log n) due to the sorting operation, where n is the number of intervals. The for loop takes O(n) time to iterate over all intervals, and the inner operations take constant time.\n\n- Space Complexity:\nThe space complexity of this approach is O(n) to store the answer vector and the temporary vector.\n\n---\n# C++\n```cpp\nclass Solution {\npublic:\n vector<vector<int>> merge(vector<vector<int>>& intervals) {\n vector<vector<int>> ans;\n sort(intervals.begin(),intervals.end());\n if(intervals.size()==0){\n return ans;\n }\n vector <int> temp = intervals[0];\n for(int i=0;i<intervals.size();i++){\n if(intervals[i][0]<=temp[1]){\n temp[1]=max(temp[1],intervals[i][1]);\n }\n else{\n ans.push_back(temp);\n temp=intervals[i];\n }\n }\n ans.push_back(temp);\n return ans;\n }\n};\n```\n---\n# Java\n```java\nclass Solution {\n public int[][] merge(int[][] intervals) {\n List<int[]> ans = new ArrayList<>();\n Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n\n if (intervals.length == 0) {\n return ans.toArray(new int[0][]);\n }\n\n int[] temp = intervals[0];\n for (int i = 0; i < intervals.length; i++) {\n if (intervals[i][0] <= temp[1]) {\n temp[1] = Math.max(temp[1], intervals[i][1]);\n } else {\n ans.add(temp);\n temp = intervals[i];\n }\n }\n ans.add(temp);\n\n return ans.toArray(new int[0][]);\n }\n}\n```\n---\n# Python\n```py\nclass Solution(object):\n def merge(self, intervals):\n ans = []\n intervals.sort()\n\n if len(intervals) == 0:\n return ans\n\n temp = intervals[0]\n for interval in intervals:\n if interval[0] <= temp[1]:\n temp[1] = max(temp[1], interval[1])\n else:\n ans.append(temp)\n temp = interval\n ans.append(temp)\n\n return ans\n\n```\n---\n# JavaScript\n```js\nvar merge = function(intervals) {\n let ans = [];\n intervals.sort((a, b) => a[0] - b[0]);\n\n if (intervals.length === 0) {\n return ans;\n }\n\n let temp = intervals[0];\n for (let i = 0; i < intervals.length; i++) {\n if (intervals[i][0] <= temp[1]) {\n temp[1] = Math.max(temp[1], intervals[i][1]);\n } else {\n ans.push(temp);\n temp = intervals[i];\n }\n }\n ans.push(temp);\n\n return ans;\n};\n\n``` | 5,474 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 90,544 | 512 | **Solution 1:** (7 lines, 88 ms)\n\nCollect the intervals strictly left or right of the new interval, then merge the new one with the middle ones (if any) before inserting it between left and right ones.\n\n def insert(self, intervals, newInterval):\n s, e = newInterval.start, newInterval.end\n left = [i for i in intervals if i.end < s]\n right = [i for i in intervals if i.start > e]\n if left + right != intervals:\n s = min(s, intervals[len(left)].start)\n e = max(e, intervals[~len(right)].end)\n return left + [Interval(s, e)] + right\n\n---\n\n**Solution 2:** (8 lines, 84 ms)\n\nSame algorithm as solution 1, but different implementation with only one pass and explicitly collecting the to-be-merged intervals.\n\n def insert(self, intervals, newInterval):\n s, e = newInterval.start, newInterval.end\n parts = merge, left, right = [], [], []\n for i in intervals:\n parts[(i.end < s) - (i.start > e)].append(i)\n if merge:\n s = min(s, merge[0].start)\n e = max(e, merge[-1].end)\n return left + [Interval(s, e)] + right\n\n---\n\n**Solution 3:** (11 lines, 80 ms)\n\nSame again, but collect and merge while going over the intervals once.\n\n def insert(self, intervals, newInterval):\n s, e = newInterval.start, newInterval.end\n left, right = [], []\n for i in intervals:\n if i.end < s:\n left += i,\n elif i.start > e:\n right += i,\n else:\n s = min(s, i.start)\n e = max(e, i.end)\n return left + [Interval(s, e)] + right | 5,528 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 5,151 | 45 | \uD83D\uDD34 Check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord]() for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository]() and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast]() if you are interested.\n\n---\n\n<iframe src="" frameBorder="0" width="100%" height="500"></iframe> | 5,535 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 277 | 6 | # Intuition\n\nAs we iterate through the intervals we only need to merge intervals that overlap each other and insert our new interval if it ends before the next iterated interval\n\n# Approach\n\nWe begin by creating an empty list which will contain our final **output**.\n\nIterate through all of the provided `intervals`. For each iterated interval:\n- If it begins after our new interval ends,\n - Insert new interval to our **output**\n - **Add** all remaining intervals from the current interval to our **output** container.\n - **Exit** the loop by returning _the currently generated output._\n- If it ends before our new interval begins\n - **Add** it directly to our **output**, as new interval does not need to be processed yet and is still yet to come somewhere in the future time intervals.\n- If it overlaps with our new interval\n - **Redefine** new interval by taking the **minimum** of _compared beginnings_ as the **start** and the **maximum** of _compared beginnings_ as the **end**. _DO NOT INSERT IT YET!_\n\nNotice that after we **exit** out of our defined loop without hitting the **return** statement within our **first condition**, we have yet to **insert** our new interval to our **output**. So, before _returning_ the **output** at this point, have our _new interval_ inserted into the returned **output**.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python3 []\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n # Initialize an output container\n output = []\n\n # Iterate through all intervals\n for i in range(len(intervals)):\n # If the new interval ends before the current interval\n # - Append the new interval to the output\n # - Append the rest of the remaining intervals to the output\n # - Return the output\n if newInterval[1] < intervals[i][0]:\n output.append(newInterval)\n return output + intervals[i:]\n \n # If the new interval begins after the current interval\n # - Append the current interval to the output\n elif newInterval[0] > intervals[i][1]:\n output.append(intervals[i])\n\n # If the new interval overlaps with the current interval\n # merge intervals to create a new interval where\n # - Interval begins at the earliest of beginnings\n # - Interval ends at the latest of ends\n #\n # ! Do not add the new interval to the output just yet!\n # ! Further merging may be required\n else:\n newInterval = [\n min(newInterval[0], intervals[i][0]),\n max(newInterval[1], intervals[i][1])\n ]\n\n # Add the new interval to the output if not added already\n # ! No need for conditions as we would not reach this point otherwise\n output.append(newInterval)\n\n # Return the final output\n return output\n```\n```Go []\nfunc insert(intervals [][]int, newInterval []int) [][]int {\n // Initialize an output container\n output := [][]int{}\n\n // Iterate through all intervals\n for i := 0; i < len(intervals); i++ {\n if newInterval[1] < intervals[i][0] {\n // If the new interval ends before the current interval\n // - Append the new interval to the output\n // - Append the rest of the remaining intervals to the output\n // - Return the output\n output = append(output, newInterval)\n return append(output, intervals[i:]...)\n } else if newInterval[0] > intervals[i][1] {\n // If the new interval begins after the current interval\n // - Append the current interval to the output\n output = append(output, intervals[i])\n } else {\n // If the new interval overlaps with the current interval\n // merge intervals to create a new interval where\n // - Interval begins at the earliest of beginnings\n // - Interval ends at the latest of ends\n //\n // ! Do not add the new interval to the output just yet!\n // ! Further merging may be required\n newInterval = []int {\n min(newInterval[0], intervals[i][0]),\n max(newInterval[1], intervals[i][1]),\n }\n }\n }\n\n // Add the new interval to the output if not added already\n // ! No need for conditions as we would not reach this point otherwise\n output = append(output, newInterval)\n\n // Return the final output\n return output\n}\n```\n```typescript []\nfunction insert(intervals: number[][], newInterval: number[]): number[][] {\n // Initialize an output container\n const output: number[][] = [];\n\n // Iterate through all intervals\n for(let i = 0; i < intervals.length; i++) {\n // If the new interval ends before the current interval\n // - Append the new interval to the output\n // - Append the rest of the remaining intervals to the output\n // - Return the output\n if (newInterval[1] < intervals[i][0]) {\n output.push(newInterval);\n intervals.slice(i).forEach(interval => output.push(interval));\n return output;\n }\n\n // If the new interval begins after the current interval\n // - Append the current interval to the output\n else if (newInterval[0] > intervals[i][1])\n output.push(intervals[i])\n\n // If the new interval overlaps with the current interval\n // merge intervals to create a new interval where\n // - Interval begins at the earliest of beginnings\n // - Interval ends at the latest of ends\n //\n // ! Do not add the new interval to the output just yet!\n // ! Further merging may be required\n else\n newInterval = [\n Math.min(newInterval[0], intervals[i][0]),\n Math.max(newInterval[1], intervals[i][1])\n ];\n }\n\n // Add the new interval to the output if not added already\n // ! No need for conditions as we would not reach this point otherwise\n output.push(newInterval);\n\n // Return the final output\n return output;\n};\n```\n | 5,547 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 6,074 | 33 | **Approach:**\n* The approach used is to `first` iterate through the given intervals, and keeping track of the index of the interval where the new `interval` should be inserted such that the intervals remain `sorted`. Then it will `merge` any overlapping intervals with the new interval and update its `start` and `end` times. `Finally`, it will insert the new interval into the correct position in the intervals and `return` the modified intervals.\n* The `key` idea behind this approach is to maintain the `sorted` order of the intervals, and to `merge` any overlapping intervals with the new interval. \n* By iterating through the intervals and keeping track of the index where the new interval should be `inserted`, we can ensure that the intervals `remain` sorted, and by merging any `overlapping` intervals with the new interval, we can ensure that the final `output` has no `overlapping` intervals.\n\n**C++:**\n```\nclass Solution {\npublic:\n vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {\n vector<vector<int>> res;\n int i = 0, n = intervals.size();\n while (i < n && intervals[i][1] < newInterval[0]) res.push_back(intervals[i++]);\n while (i < n && intervals[i][0] <= newInterval[1]) newInterval = {min(intervals[i][0], newInterval[0]), max(intervals[i][1], newInterval[1])}, i++;\n res.push_back(newInterval);\n while (i < n) res.push_back(intervals[i++]);\n return res;\n }\n};\n```\n**Java:**\n```\nclass Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n List<int[]> res = new ArrayList<>();\n int i = 0, n = intervals.length;\n while (i < n && intervals[i][1] < newInterval[0]) res.add(intervals[i++]);\n while (i < n && intervals[i][0] <= newInterval[1]) newInterval = new int[] {Math.min(intervals[i][0], newInterval[0]), Math.max(intervals[i][1], newInterval[1])}, i++;\n res.add(newInterval);\n while (i < n) res.add(intervals[i++]);\n return res.toArray(new int[res.size()][2]);\n }\n}\n```\n**Python:**\n\n```\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n res = []\n i = 0\n n = len(intervals)\n while i < n and intervals[i][1] < newInterval[0]:\n res.append(intervals[i])\n i += 1\n while i < n and intervals[i][0] <= newInterval[1]:\n newInterval[0] = min(intervals[i][0], newInterval[0])\n newInterval[1] = max(intervals[i][1], newInterval[1])\n i += 1\n res.append(newInterval)\n while i < n:\n res.append(intervals[i])\n i += 1\n return res\n```\n\n----\nThe **Time complexity** is **O(n)** \nThe **Space complexity** is **O(n)** .\n\n----\n\n\n | 5,558 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 10,824 | 114 | the main idea is that when iterating over the intervals there are three cases:\n\n1. the new interval is in the range of the other interval\n2. the new interval\'s range is before the other\n3. the new interval is after the range of other interval\n\n```\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n result = []\n \n for interval in intervals:\n\t\t\t# the new interval is after the range of other interval, so we can leave the current interval baecause the new one does not overlap with it\n if interval[1] < newInterval[0]:\n result.append(interval)\n # the new interval\'s range is before the other, so we can add the new interval and update it to the current one\n elif interval[0] > newInterval[1]:\n result.append(newInterval)\n newInterval = interval\n # the new interval is in the range of the other interval, we have an overlap, so we must choose the min for start and max for end of interval \n elif interval[1] >= newInterval[0] or interval[0] <= newInterval[1]:\n newInterval[0] = min(interval[0], newInterval[0])\n newInterval[1] = max(newInterval[1], interval[1])\n\n \n result.append(newInterval); \n return result\n``` | 5,565 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 2,884 | 9 | \n# Approach\nThe solution follows the logic of iterating through the intervals to find the correct position to insert the new interval while maintaining the sorted order. After insertion, it iterates over the modified array to merge any overlapping intervals by updating the end time of the previous interval if necessary. Finally, it returns the modified array with the new interval inserted and any overlapping intervals merged.\n\n# Code\n```\nclass Solution:\n def insert(self, inv: List[List[int]], nw: List[int]) -> List[List[int]]:\n #insert nw\n test=True\n for i in range(len(inv)):\n if inv[i][0]>nw[0]:\n test=False\n inv.insert(i,nw)\n if test:\n inv.append(nw)\n\n i=1\n while i<len(inv):\n if inv[i-1][1]>=inv[i][0]:\n inv[i-1][1]=max (inv[i-1][1],inv[i][1])\n inv.pop(i)\n else:\n i+=1\n \n return inv\n``` | 5,588 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 958 | 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\n```\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n l = []\n for i in intervals:\n if i[1] < newInterval[0]:\n l.append(i)\n elif i[0] > newInterval[1]:\n l.append(newInterval)\n newInterval = i\n elif i[1] >= newInterval[0] or i[0] <= newInterval[1]:\n newInterval[0] = min(i[0],newInterval[0])\n newInterval[1] = max(newInterval[1],i[1])\n l.append(newInterval)\n return l\n\n\n\n\n\n``` | 5,590 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 32,245 | 176 | \n \n # O(nlgn) time, the same as Merge Intervals \n # \n def insert1(self, intervals, newInterval):\n intervals.append(newInterval)\n res = []\n for i in sorted(intervals, key=lambda x:x.start):\n if res and res[-1].end >= i.start:\n res[-1].end = max(res[-1].end, i.end)\n else:\n res.append(i)\n return res\n \n # O(n) time, not in-place, make use of the \n # property that the intervals were initially sorted \n # according to their start times\n def insert(self, intervals, newInterval):\n res, n = [], newInterval\n for index, i in enumerate(intervals):\n if i.end < n.start:\n res.append(i)\n elif n.end < i.start:\n res.append(n)\n return res+intervals[index:] # can return earlier\n else: # overlap case\n n.start = min(n.start, i.start)\n n.end = max(n.end, i.end)\n res.append(n)\n return res | 5,591 |
Insert Interval | insert-interval | You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. | Array | Medium | null | 2,862 | 16 | ```\ndef insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n result = []\n for i in range(len(intervals)):\n if newInterval[1] < intervals[i][0]:\n result.append(newInterval)\n return result + intervals[i:]\n elif newInterval[0] > intervals[i][1]:\n result.append(intervals[i])\n else:\n newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])]\n result.append(newInterval)\n return result\n``` | 5,598 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 981 | 8 | \n\nOne way of solving this would be to use the `split()` method to split the string on whitespaces, then return the length of the last word in the array:\n```\narray = s.split()\nreturn len(array[-1])\n```\nHowever, this is inefficient because you have to split on <i>every</i> whitespace in the string, when really, you only need the last word. An optimized solution would be to traverse the string from the back instead.\n\nThe first `while` loop moves the pointer `i` backwards through the string until the first non-whitespace character is found. Then we\'re ready to start counting the length of the word we just hit, so the second loop increments `length` and moves `i` backwards until a whitespace character is found.\n\nOnce that whitespace character is found, that means we\'ve finished traversing the word, so the only thing left to do is to return `length`.\n\n\n# Code\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n length = 0\n i = len(s) - 1\n while i >= 0 and s[i] == \' \':\n i -= 1\n while i >= 0 and s[i] != \' \':\n length += 1\n i -= 1\n return length\n``` | 5,603 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 4,847 | 15 | # Approach\nThis code defines a class `Solution` with a method `lengthOfLastWord` that calculates the length of the last word in a given input string `s`. Here\'s a brief explanation of each part of the code:\n\n1. `stripped = s.strip()`: This line removes leading and trailing whitespace from the input string `s` using the `strip` method. This is done to handle cases where there might be spaces at the beginning or end of the string.\n\n2. `strList = stripped.split(" ")`: This line splits the stripped string `stripped` into a list of words using a space as the delimiter. It uses the `split` method, which separates the string into a list of substrings wherever it encounters a space character.\n\n3. `lastWord = strList[-1]`: This line extracts the last element (which is the last word) from the `strList` by using the index `-1`. This assumes that words in the string are separated by spaces.\n\n4. `return len(lastWord)`: Finally, the code returns the length of the `lastWord` using the `len` function. This length represents the number of characters in the last word of the input string.\n\nIn summary, the code takes a string as input, removes leading and trailing spaces, splits the string into words, extracts the last word, and returns the length of that last word.\n\n# Code\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n stripped = s.strip()\n strList = stripped.split(" ")\n lastWord = strList[-1]\n return len(lastWord)\n```\n\n**Please upvote if you like the solution.\nHappy Coding! \uD83D\uDE0A** | 5,621 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 6,532 | 9 | # Approach\n- First we will convert given String of words into array of strings on basis of white spaces using python\'s `.split()` which converts the string into Array \n\n- for example:\n```\nstr = "Hello World"\narr = str.split()\n\n# arr will be\narr = ["Hello" , "World"]\n```\n- So we will just return the length of last string from the array \n\n# Code\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n arr = s.split()\n return len(arr[-1])\n```\n# proof \n\n![Screenshot 2023-04-24 at 12.17.38 AM.png]()\n | 5,624 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 3,540 | 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\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n return len(s.split()[-1])\n``` | 5,654 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 3,168 | 15 | The easist way may be iterate from the end of the string, can we do that with a different way?\n**Of course !**\n\n\u2B50**See more Code and Explanation : []()**\n\n##### C# Examples\n**1. Iteration**\n```\npublic class Solution {\n public int LengthOfLastWord(string s) {\n \n int cnt = 0;\n \n for(int i = s.Length-1;i>=0;i--)\n {\n if(Char.IsWhiteSpace(s[i]))\n {\n if(cnt>0)\n {\n return cnt; \n }\n continue;\n }\n \n cnt+=1;\n }\n return cnt;\n }\n}\n```\n\n**2. Split + Trim**\n```\npublic class Solution {\n public int LengthOfLastWord(string s) {\n s = s.TrimEnd(); //or you can use Trim()\n string[] tmp = s.Split(\' \');\n return tmp[tmp.Length-1].Length; \n }\n}\n```\nIs there an easier way in C#? Yes!\n\n---\n\n\n##### Java Solution\n**1. Iteration**\n```\nclass Solution {\n public int lengthOfLastWord(String s) {\n int cnt = 0;\n \n for(int i = s.length()-1;i>=0;i--)\n {\n if(s.charAt(i)==\' \')\n {\n if(cnt>0)\n {\n return cnt; \n }\n continue;\n }\n \n cnt+=1;\n }\n return cnt;\n }\n}\n```\n\n\n**2.**\n```\nclass Solution {\n public int lengthOfLastWord(String s) {\n s = s.trim();\n String[] arr = s.split("\\\\s+");\n \n return arr[arr.length-1].length();\n }\n}\n```\n\n---\n\n\n\n##### Python3 Solution\n**1. Iteration**\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n cnt = 0;\n for i in range(len(s)-1,-1,-1):\n if(s[i]== \' \'):\n if cnt>0 :\n return cnt\n continue\n cnt+=1;\n return cnt\n```\n\n**2.**\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n s = s.rstrip() #or strip\n return len(s.split()[-1])\n```\n\n---\n\n\n##### JavaScript Solution\n**1. Iteration**\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLastWord = function(s) {\n var cnt = 0;\n\n for(var i = s.length-1;i>=0;i--)\n {\n if(s[i]==\' \')\n {\n if(cnt>0)\n {\n return cnt; \n }\n continue;\n }\n\n cnt+=1;\n }\n return cnt;\n};\n```\n\n\n**2.**\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLastWord = function(s) {\n s = s.trim();\n var arr = s.split(\' \');\n return arr[arr.length-1].length;\n};\n```\n\n\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to leave your comment.\n\n\uD83E\uDDE1See more problems solutions - **[Zyrastory - LeetCode Solution]()**\n\nThanks! | 5,672 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 1,418 | 15 | ## ***Please Upvote my solution, if you find it helpful ;)***\n\n# Intuition\nThe intuition behind the solution is to iterate through the given string and keep track of the length of the last word encountered. By considering spaces as separators between words, we can determine the length of the last word by counting the characters until the next space or the end of the string.\n# Approach\n1. Initialize a count variable to 0. This variable will keep track of the length of the last word.\n1. Create a boolean variable called space and set it to false. This variable will help identify when a space character is encountered.\n1. Iterate through each character of the string using a for loop.\n1. Check if the current character is a space character by comparing it to \' \'. If it is, set the space variable to true.\n1. If the current character is not a space character and the space variable is true, it means we have encountered the first character of a new word. In this case, set the count to 1 and reset the space variable to false.\n1. If the current character is not a space character and the space variable is false, it means we are still in the middle of a word. In this case, increment the count by 1.\n1. After iterating through all the characters, the count will hold the length of the last word in the string.\n1. Return the count as the result.\n\n# Complexity\n- Time complexity:\nThe time complexity of this approach is $$O(n)$$, where n is the length of the input string. We iterate through the string once to determine the length of the last word.\n\n- Space complexity:\nThe space complexity of this approach is $$O(1)$$ since we are using a constant amount of additional space to store the count and the space flag, regardless of the size of the input string.\n\n# Code\n\n```java []\nclass Solution {\n public int lengthOfLastWord(String s) {\n\n int count = 0; // variable to store the length of the last word\n boolean space = false; // flag to track if a space has been encountered\n\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \' \') {\n space = true; // mark that a space has been encountered\n } else if (s.charAt(i) != \' \' && space == true) {\n count = 1; // start counting a new word, set count to 1\n space = false; // reset the space flag\n } else {\n count++; // increment the count for the current word\n }\n }\n return count; // return the length of the last word\n }\n}\n```\n```python []\nclass Solution(object):\n def lengthOfLastWord(self, s):\n count = 0 # Variable to store the length of the last word\n space = False # Boolean variable to track if a space is encountered\n \n # Iterate through each character in the string\n for i in xrange(len(s)):\n if s[i] == \' \': # If a space character is encountered\n space = True\n elif s[i] != \' \' and space: # If a non-space character is encountered after a space\n count = 1 # Start counting a new word\n space = False\n else:\n count += 1 # Increment the count for non-space characters\n \n return count\n\n```\n```C++ []\nclass Solution {\npublic:\n int lengthOfLastWord(string s) {\n int count = 0; // Variable to store the length of the last word\n bool space = false; // Boolean variable to track if a space is encountered\n \n // Iterate through each character in the string\n for (int i = 0; i < s.length(); i++) {\n if (s[i] == \' \') { // If a space character is encountered\n space = true;\n } else if (s[i] != \' \' && space) { // If a non-space character is encountered after a space\n count = 1; // Start counting a new word\n space = false;\n } else {\n count++; // Increment the count for non-space characters\n }\n }\n \n return count;\n }\n};\n\n```\n\n***Please Upvote my solution, if you find it helpful ;)***\n![6a87bc25-d70b-424f-9e60-7da6f345b82a_1673875931.8933976.jpeg]()\n | 5,688 |
Length of Last Word | length-of-last-word | Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. | String | Easy | null | 2,231 | 7 | ***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q58. Length of Last Word***\nGiven a string `s` consisting of words and spaces, return the length of the word **last** the string.\n\nA **word** is a maximal substring consisting of non-space characters only.\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n s=s.strip().split(" ")\n lst=[ i for i in s if i!=""]\n a=lst[-1]\n return len(a)\n```\n**Runtime:** 50 ms\t\n**Memory Usage:** 13.9 MB\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\nRuntime: 0 ms, faster than 100.00% of java online submissions for Length of Last Word.\n```\nclass Solution {\n public int lengthOfLastWord(String s) {\n int len=0;\n for(int i=s.length()-1;i>=0;i--)\n {\n if(s.charAt(i)!=\' \')\n len++;\n else if(len>0)\n return len;\n }\n return len;\n }\n}\n```\n**Runtime:** 0 ms\t\t\n**Memory Usage:** 43..8 MB\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n**Runtime**: 0 ms, faster than 100.00% of C++ online submissions for Length of Last Word.\n```\nclass Solution {\npublic:\n int lengthOfLastWord(string s) {\n int len=0;\n for(int i=s.size()-1;i>=0;i--)\n {\n if(s[i]!=\' \') len++;\n else if(len>0) return len;\n }\n return len;\n }\n};\n```\n**Runtime:** 0 ms\t\n**Memory Usage:** 5.3 MB\t\t\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 5,696 |
Spiral Matrix II | spiral-matrix-ii | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. | Array,Matrix,Simulation | Medium | null | 13,193 | 61 | **!! 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. I planned to give for next 10,000 Subscribers as well. If you\'re interested **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\n\n- Initialize an empty matrix of size n x n with all elements set to zero.\n- Define variables left, right, top, bottom, and num.\n- Use a while loop to iterate over the matrix in a spiral order.\n- In each iteration, fill in the top row, right column, bottom row, and left column of the remaining submatrix, in that order.\n- Increment/decrement the values of left, right, top, and bottom accordingly after each iteration, and update the value of num to be filled in the next iteration.\n- Return the generated matrix.\n# Intuition:\n\nThe code generates the matrix by filling in its elements in a spiral order, starting from the top-left corner and moving clockwise. It uses the variables left, right, top, and bottom to keep track of the current submatrix being filled in, and the variable num to keep track of the next number to be filled in the matrix. The algorithm fills in the matrix in four steps:\n\n- Fill in the top row from left to right.\n- Fill in the right column from top to bottom.\n- Fill in the bottom row from right to left.\n- Fill in the left column from bottom to top.\n\nAfter each step, the corresponding variable (left, right, top, or bottom) is incremented or decremented to exclude the already filled elements in the next iteration. The algorithm stops when the submatrix being filled in becomes empty, i.e., left > right or top > bottom. Finally, the generated matrix is returned.\n\n\n```Python []\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n if not n:\n return []\n matrix = [[0 for _ in range(n)] for _ in range(n)]\n left, right, top, bottom, num = 0, n-1, 0, n-1, 1\n while left <= right and top <= bottom:\n for i in range(left, right+1):\n matrix[top][i] = num \n num += 1\n top += 1\n for i in range(top, bottom+1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left-1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top-1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n\n```\n```Java []\nclass Solution {\n public int[][] generateMatrix(int n) {\n if (n == 0) {\n return new int[0][0];\n }\n int[][] matrix = new int[n][n];\n int left = 0, right = n-1, top = 0, bottom = n-1, num = 1;\n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num++;\n }\n left++;\n }\n }\n return matrix;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n if (n == 0) {\n return {};\n }\n vector<vector<int>> matrix(n, vector<int>(n, 0));\n int left = 0, right = n-1, top = 0, bottom = n-1, num = 1;\n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num++;\n }\n left++;\n }\n }\n return matrix;\n }\n};\n\n```\n# An Upvote will be encouraging \uD83D\uDC4D | 5,789 |
Spiral Matrix II | spiral-matrix-ii | Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. | Array,Matrix,Simulation | Medium | null | 4,934 | 46 | \n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n![image.png]()\n\n\n# BRUTE\nThe brute force solution to generate a matrix in spiral order is to simulate the process of filling the matrix in a spiral order. We can start by initializing the matrix with zeros and then fill the matrix in a spiral order by moving right, down, left, and up. We keep track of the current position in the matrix and the direction of movement. Whenever we reach the boundary of the matrix or encounter a non-zero element, we change the direction of movement. We continue this process until all the elements in the matrix are filled.\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int num = 1;\n int row = 0;\n int col = 0;\n int direction = 0;\n int[] dr = {0, 1, 0, -1};\n int[] dc = {1, 0, -1, 0};\n while (num <= n * n) {\n matrix[row][col] = num;\n num++;\n int nextRow = row + dr[direction];\n int nextCol = col + dc[direction];\n if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0) {\n direction = (direction + 1) % 4;\n }\n row += dr[direction];\n col += dc[direction];\n }\n return matrix;\n }\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int num = 1;\n int row = 0;\n int col = 0;\n int direction = 0;\n vector<int> dr = {0, 1, 0, -1};\n vector<int> dc = {1, 0, -1, 0};\n while (num <= n * n) {\n matrix[row][col] = num;\n num++;\n int nextRow = row + dr[direction];\n int nextCol = col + dc[direction];\n if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0) {\n direction = (direction + 1) % 4;\n }\n row += dr[direction];\n col += dc[direction];\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n num = 1\n row = 0\n col = 0\n direction = 0\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n while num <= n * n:\n matrix[row][col] = num\n num += 1\n nextRow = row + dr[direction]\n nextCol = col + dc[direction]\n if nextRow < 0 or nextRow >= n or nextCol < 0 or nextCol >= n or matrix[nextRow][nextCol] != 0:\n direction = (direction + 1) % 4\n row += dr[direction]\n col += dc[direction]\n return matrix\n```\n# Complexity\nThe time complexity of the brute force solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is also O(n^2)+2*O(1D) because we need to create a matrix of size n x n to store the elements and two direction 1D arrays.\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n# Better Solution:\n\nA better solution to generate a matrix in spiral order is to use a recursive approach. We can divide the matrix into four sub-matrices and fill each sub-matrix in a spiral order recursively. We start by filling the top row of the matrix, then fill the right column, then the bottom row, and finally the left column. We repeat this process for the remaining sub-matrix until all the elements in the matrix are filled.\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1);\n return matrix;\n }\n\n public void fillMatrix(int[][] matrix, int top, int bottom, int left, int right, int num) {\n if (top > bottom || left > right) {\n return;\n }\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n for (int i = top + 1; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n if (top < bottom && left < right) {\n for (int i = right - 1; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n for (int i = bottom - 1; i > top; i--) {\n matrix[i][left] = num;\n num++;\n }\n }\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num);\n }\n\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1);\n return matrix;\n}\n\nvoid fillMatrix(vector<vector<int>>& matrix, int top, int bottom, int left, int right, int num) {\n if (top > bottom || left > right) {\n return;\n }\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n for (int i = top + 1; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n if (top < bottom && left < right) {\n for (int i = right - 1; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n for (int i = bottom - 1; i > top; i--) {\n matrix[i][left] = num;\n num++;\n }\n }\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num);\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n fillMatrix(matrix, 0, n - 1, 0, n - 1, 1)\n return matrix\n\ndef fillMatrix(matrix: List[List[int]], top: int, bottom: int, left: int, right: int, num: int) -> None:\n if top > bottom or left > right:\n return\n for i in range(left, right + 1):\n matrix[top][i] = num\n num += 1\n for i in range(top + 1, bottom + 1):\n matrix[i][right] = num\n num += 1\n if top < bottom and left < right:\n for i in range(right - 1, left - 1, -1):\n matrix[bottom][i] = num\n num += 1\n for i in range(bottom - 1, top, -1):\n matrix[i][left] = num\n num += 1\n fillMatrix(matrix, top + 1, bottom - 1, left + 1, right - 1, num)\n```\n# Complexity\nThe time complexity of the better solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is also O(n^2) because we need to create a matrix of size n x n to store the elements. However, the space complexity of the recursive approach is O(n2)+o(log n) because we use the call stack to store the recursive calls, which has a maximum depth of log n.\n\n# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n# optimal\n\n```java []\npublic int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int top = 0;\n int bottom = n - 1;\n int left = 0;\n int right = n - 1;\n int num = 1;\n while (top <= bottom && left <= right) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num;\n num++;\n }\n left++;\n }\n }\n return matrix;\n }\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int top = 0;\n int bottom = n - 1;\n int left = 0;\n int right = n - 1;\n int num = 1;\n while (top <= bottom && <= right) {\n for (int i = left; i <= right; i++) {\n matrix[top][i] = num;\n num++;\n }\n top++;\n for (int i = top; i <= bottom; i++) {\n matrix[i][right] = num;\n num++;\n }\n right--;\n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n matrix[bottom][i] = num;\n num++;\n }\n bottom--;\n }\n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n matrix[i][left] = num;\n num++;\n }\n left++;\n }\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n top = 0\n bottom = n - 1\n left = 0\n right = n - 1\n num = 1\n while top <= bottom and left <= right:\n for i in range(left, right + 1):\n matrix[top][i] = num\n num += 1\n top += 1\n for i in range(top, bottom + 1):\n matrix[i][right] = num\n num += 1\n right -= 1\n if top <= bottom:\n for i in range(right, left - 1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1\n if left <= right:\n for i in range(bottom, top - 1, -1):\n matrix[i][left] = num\n num += 1\n left += 1\n return matrix\n```\n# Complexity\nThe time complexity of the optimal solution is O(n^2) because we need to fill all the elements in the matrix. The space complexity is o(n2)+ O(1) because we only need to create a constant number of variables to store the boundaries of the matrix and the current number to fill.\n\nIn terms of time complexity, the optimal solution is the best because it has the same time complexity as the other two solutions but uses a single loop instead of recursion or simulating the process of filling the matrix. In terms of space complexity, the optimal solution is the best because it only uses a constant amount of space, whereas the other two solutions use a matrix of size n x n or a call stack of size log n.\n\n# concise code\n# Algorithm\n##### \u2022\tUse four variables i, j, di, and dj to keep track of the current position and direction\n##### \u2022\tThen starts by initializing the matrix with all zeros\n##### \u2022\tIt then fills the matrix in a spiral order by moving in the current direction and changing direction when it encounters a non-zero element\n##### \u2022\tThe loop variable k starts from 1 and goes up to n * n\n##### \u2022\tIn each iteration, then sets the value of the current position (i, j) to k\n##### \u2022\tIt then checks if the next position in the current direction (i + di, j + dj) is already filled with a non-zero value\n##### \u2022\tIf it is, changes the direction by swapping di and dj and negating one of them\n##### \u2022\tFinally, updates the current position by adding di to i and dj to j\n##### \u2022\tOnce the loop is complete, the matrix is filled in a spiral order and returns the matrix\n\n```java []\npublic int[][] generateMatrix(int n) {\n int matrix[][] = new int[n][n],i = 0, j = 0, di = 0, dj = 1;\n for (int k = 1; k <= n * n; k++) {\n matrix[i][j] = k;\n if (matrix[(i + di + n) % n][(j + dj + n) % n] != 0) {\n int temp = di;\n di = dj;\n dj = -temp;\n }\n i += di;\n j += dj;\n } return matrix;\n}\n```\n```c++ []\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> matrix(n, vector<int>(n));\n int i = 0, j = 0, di = 0, dj = 1;\n for (int k = 1; k <= n * n; k++) {\n matrix[i][j] = k;\n if (matrix[(i + di + n) % n][(j + dj + n) % n] != 0) {\n int temp = di;\n di = dj;\n dj = -temp;\n }\n i += di;\n j += dj;\n }\n return matrix;\n}\n```\n```python []\ndef generateMatrix(self, n):\n A = [[0] * n for _ in range(n)]\n i, j, di, dj = 0, 0, 0, 1\n for k in xrange(n*n):\n A[i][j] = k + 1\n if A[(i+di)%n][(j+dj)%n]:\n di, dj = dj, -di\n i += di\n j += dj\n return A\n```\n\n# dry run for n=3\n##### \u2022\tInitially, we create a new n x n matrix filled with zeros\n##### \u2022\tWe also initialize i and j to 0, and di and dj to 0 and 1 respectively\n##### \u2022\tWe then enter a loop that runs from k=1 to k=n*n\n##### \u2022\tIn each iteration of the loop, we do the following:We set the value of the current cell to k\n##### \u2022\tWe check if the next cell in the direction of (di, dj) is already filled\n##### \u2022\tIf it is, we change the direction of motion by swapping di and dj and negating the new value of dj\n##### \u2022\tWe update the values of i and j by adding di and dj respectively\n##### \u2022\tAfter the loop completes, we return the filled matrix\n##### \u2022\tThe final matrix is:\n```\n1 2 3\n8 9 4\n7 6 5\n```\n# 3 LINES code\n# Algorithm\n##### \u2022\tFirst initializes an empty list A and a variable lo to n*n+1\n##### \u2022\tIt then enters a loop that continues until lo is less than or equal to 1\n##### \u2022\tIn each iteration, set hi to the current value of lo and updates lo to lo - len(A)\n##### \u2022\tIt then creates a new list of integers from lo to hi and appends it to the beginning of A\n##### \u2022\tThen reverses the order of the remaining elements in A and transposes the resulting list of lists using the zip() function\n##### \u2022\tThis effectively rotates the matrix by 90 degrees counterclockwise\n##### \u2022\tThe loop continues until lo is less than or equal to 1, at which point the matrix is filled in a spiral order and returns A\n\n```PYTHON []\ndef generateMatrix(self, n):\n A = [[n*n]]\n while A[0][0] > 1:\n A = [range(A[0][0] - len(A), A[0][0])] + zip(*A[::-1])\n return A * (n>0)\n```\n```PYTHON []\ndef generateMatrix(self, n):\n A, lo = [], n*n+1\n while lo > 1:\n lo, hi = lo - len(A), lo\n A = [range(lo, hi)] + zip(*A[::-1])\n return A\n```\n# dry run for n=3\n##### \u2022\tInitially, A is set to [[9]]\n##### \u2022\tIn the while loop, we check if the first element of A is greater than 1\n##### \u2022\tSince it is, we perform the following steps:We create a new list B containing a range of numbers from A[0][0] - len(A) to A[0][0] - 1\n##### \u2022\tIn this case, B is equal to range(7, 9)\n##### \u2022\tWe then take the transpose of A using zip(*A[::-1])\n##### \u2022\tThe [::-1] reverses the order of the elements in A, and the * unpacks the elements of A as arguments to zip\n##### \u2022\tThe zip function then groups the elements of each sub-list of A with the corresponding elements of B, effectively rotating the matrix by 90 degrees counterclockwise\n##### \u2022\tWe concatenate B with the result of step 2 to form a new matrix A\n##### \u2022\tWe repeat steps 1-3 until the first element of A is equal to 1\n##### \u2022\tFinally, we return A multiplied by (n>0), which is equivalent to returning A if n is positive and an empty list if n is zero\n\nAt each iteration, the code fills in one element of the matrix in a spiral order. The final matrix is filled in the following order:\n1 2 3\n8 9 4\n7 6 5\n\n![BREUSELEE.webp]()\n![image.png]()\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 | 5,798 |
Permutation Sequence | permutation-sequence | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: Given n and k, return the kth permutation sequence. | Math,Recursion | Hard | null | 2,542 | 23 | ```C++ []\nclass Solution {\npublic:\n string getPermutation(int n, int k) {\n vector<int> v={0};\n int tmp=1;\n for(int i=1;i<=n;i++){\n v.push_back(i);\n tmp*=i;\n }\n string s;\n cout<<tmp<<" ";\n for(int i=n;i>=2;i--){\n tmp/=i;\n int fl=(k+tmp-1)/tmp;\n s.push_back(v[fl]+\'0\');\n k-=(fl-1)*tmp;\n for(int j=fl;j<v.size()-1;j++){\n v[j]=v[j+1];\n }\n }\n s.push_back(v[1]+\'0\'); \n return s;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n nums = [i for i in range(1, n+1)] # list of numbers from 1 to n\n factorial = [1] * n\n for i in range(1, n):\n factorial[i] = factorial[i-1] * i\n \n k -= 1\n result = []\n for i in range(n-1, -1, -1):\n index = k // factorial[i]\n result.append(str(nums[index]))\n nums.pop(index)\n k = k % factorial[i]\n \n return \'\'.join(result)\n```\n\n```Java []\nclass Solution {\n private static int[] fact = {0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};\n \n private String getPermutation(int n, int k, boolean[] nums, char[] str, int index) {\n int i = 0, m = nums.length;\n if(n == 1) {\n while(i < m && nums[i]) ++i;\n str[index++]=(char)(\'0\'+i+1);\n return String.valueOf(str);\n }\n if(k == 0) {\n while(i < m) {\n if(!nums[i]) str[index++]=(char)(\'0\'+i+1);\n ++i;\n }\n return String.valueOf(str);\n }\n \n int div = k/fact[n-1], mod = k%fact[n-1], j = -1;\n while(i < m-1 && div != j) {\n if(!nums[i]) ++j;\n if(j == div) break;\n ++i;\n }\n str[index++]=(char)(\'0\'+i+1);\n if(i < m) nums[i]=true;\n return getPermutation(n-1, mod, nums, str, index); \n }\n\n public String getPermutation(int n, int k) {\n boolean[] nums = new boolean[n];\n char[] charArr = new char[n];\n return getPermutation(n, k-1, nums, charArr, 0);\n }\n}\n```\n | 5,827 |
Permutation Sequence | permutation-sequence | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: Given n and k, return the kth permutation sequence. | Math,Recursion | Hard | null | 25,359 | 159 | The idea is as follow:\n\nFor permutations of n, the first (n-1)! permutations start with 1, next (n-1)! ones start with 2, ... and so on. And in each group of (n-1)! permutations, the first (n-2)! permutations start with the smallest remaining number, ...\n\ntake n = 3 as an example, the first 2 (that is, (3-1)! ) permutations start with 1, next 2 start with 2 and last 2 start with 3. For the first 2 permutations (123 and 132), the 1st one (1!) starts with 2, which is the smallest remaining number (2 and 3). So we can use a loop to check the region that the sequence number falls in and get the starting digit. Then we adjust the sequence number and continue.\n\n import math\n class Solution:\n # @param {integer} n\n # @param {integer} k\n # @return {string}\n def getPermutation(self, n, k):\n numbers = range(1, n+1)\n permutation = ''\n k -= 1\n while n > 0:\n n -= 1\n # get the index of current digit\n index, k = divmod(k, math.factorial(n))\n permutation += str(numbers[index])\n # remove handled number\n numbers.remove(numbers[index])\n \n return permutation | 5,844 |
Permutation Sequence | permutation-sequence | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: Given n and k, return the kth permutation sequence. | Math,Recursion | Hard | null | 926 | 5 | # Complexity\n- Time complexity: O(n) -> Linear\n- Space complexity: O(n) -> To store the list[]\n\n# Code\n```\nimport math\nclass Solution(object):\n def getPermutation(self, n, k):\n stToRet = ""\n lst = [str(i) for i in range(1,n+1)]\n \n while len(lst):\n n = len(lst)\n n1Fac = math.factorial(n-1)\n idxToRem = k/n1Fac-1 if (k%n1Fac==0) else k/n1Fac\n stToRet+= lst.pop(idxToRem)\n k = k%n1Fac\n return stToRet\n```\nYou Can also Look At My SDE Prep Repo [*`\uD83E\uDDE2 GitHub`*]() | 5,873 |
Permutation Sequence | permutation-sequence | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: Given n and k, return the kth permutation sequence. | Math,Recursion | Hard | null | 1,921 | 15 | My solution is basically the same with the many others but here is another explanation:\n\nLet\'s go over an example:\n```\nn=4 k=9\n1234 ------ start here\n1243 ------ third digit changes here \n1324 ------ second digit changes here \n1342\n1423\n1432 \n2134 ------ first digit changes here \n2143\n2314 -> k=9\n2341\n2413\n2431\n3124 ------ first digit changes here \n.\n.\n.\n```\nAs you can see first digit changes after 6 occurances which is (n-1)! and the second digit changes after 2 occurances which is (n-2)!. Similarly third digit changes after 1 occurances which is (n-3)!. Is this a coincidance? Of course not. Since it is a permutation we compute it like this:\n```(n)(n-1)(n-2)...(1)``` each paranthesis represents a digit. for the first place, we have n options. After using one of the numbers, we cannot use it again. So we have n-1 number options for the second place. In the end we multiply them to get the total number of permutations. Let\'s say we picked \'1\' for the first place. now we have (n-1)! options for the rest of the number. This is why at each step a number is repeated that many time. \n\nLet\'s go back to our example:\n\nSince the first digit is repeated (n-1)! times, by dividing the k by n we can find our first digit. Division must be integer division because we are only interested in the integer part.\n``` \nk=9, n=4\n(n-1)! = 6\nk /(n-1)! = 1\nremainder = 3\n```\nNumbers that we can use as digits are = ```[1,2,...,n]```\n\nSo, our first digit is the digit at index 1 which is ```2```. We take the digit at 1 because our list is sorted so we are sure that the second smallest digit is at index 1.\n\nSince we used ```2```, we need to remove it from our list and k takes the value of the remainder. You can think of lit ike this: we decided on our first digit so we can discard that part and deal with the rest of the number. As you can see the problem is the same! but this time we have (n-2)! instead of (n-1)!, k=remainder and we have one less number in our list. \n\n\n\nHere is my code:\n```\nclass Solution:\n def getPermutation(self, n: int, k: int) -> str:\n factor = factorial(n-1)\n k -= 1 # index starts from 1 in the question but our list indexs starts from 0\n ans = []\n numbers_left = list(range(1,n+1))\n \n for m in range(n-1,0,-1):\n index = int(k // factor)\n ans += str(numbers_left[index])\n numbers_left.pop(index)\n k %= factor\n factor /= m\n \n ans += str(numbers_left[0])\n return \'\'.join(ans)\n```\n\n**Tips:**\n* Don\'t make ```ans``` a string because strings are not modified in place. It creates another copy of the string which makes your code slower. Instead of string, use a list which is pretty easy to append at the end, and then concatenate them in the end with join function. | 5,896 |
Rotate List | rotate-list | Given the head of a linked list, rotate the list to the right by k places. | Linked List,Two Pointers | Medium | null | 26,038 | 321 | Please upvote if you liked the solution \n\n\n```\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def rotateRight(self, head: ListNode, k: int) -> ListNode:\n \n if not head:\n return None\n \n lastElement = head\n length = 1\n # get the length of the list and the last node in the list\n while ( lastElement.next ):\n lastElement = lastElement.next\n length += 1\n\n # If k is equal to the length of the list then k == 0\n # ElIf k is greater than the length of the list then k = k % length\n k = k % length\n \n # Set the last node to point to head node\n # The list is now a circular linked list with last node pointing to first node\n lastElement.next = head\n \n # Traverse the list to get to the node just before the ( length - k )th node.\n # Example: In 1->2->3->4->5, and k = 2\n # we need to get to the Node(3)\n tempNode = head\n for _ in range( length - k - 1 ):\n tempNode = tempNode.next\n \n # Get the next node from the tempNode and then set the tempNode.next as None\n # Example: In 1->2->3->4->5, and k = 2\n # tempNode = Node(3)\n # answer = Node(3).next => Node(4)\n # Node(3).next = None ( cut the linked list from here )\n answer = tempNode.next\n tempNode.next = None\n \n return answer\n\n\n``` | 5,911 |
Rotate List | rotate-list | Given the head of a linked list, rotate the list to the right by k places. | Linked List,Two Pointers | Medium | null | 3,326 | 58 | \uD83D\uDD3A**Please UPVOTE: Can we hit 20?** \uD83D\uDD3A\n\n**Approach**\nHere we modify the linked list in place by visiting the last node and then moving a certain number of nodes to find the new head of the linked list. The example below shows a visual of the algorithm working on the given example [1,2,3,4,5] k=2.\n\n![image]()\n\n\n\n**Code**\nSee the code below related to the visual above.\n\n<iframe src="" frameBorder="0" width="800" height="600"></iframe>\n\n\t\nHope you enjoyed! Please leave a comment if anything is missed. Thanks!\n\uD83D\uDD3A**Please UPVOTE: Can we hit 20?** \uD83D\uDD3A | 5,947 |
Rotate List | rotate-list | Given the head of a linked list, rotate the list to the right by k places. | Linked List,Two Pointers | Medium | null | 2,193 | 27 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nFirst of all, we notice that `k` can be greater than the length of the list. In this case, rotations will be repeated. To avoid useless operations, we convert `k` as follows: `k = k % length` (if `k` is equal to the length, the k becomes 0 so we don\'t need to rotate anything). Thus, we need to know the length of the list and also the last element to attach it to the head. After we figure out the true `k`, we can find the node where we have to cut the list.\n\nTime: **O(n)** - traversing\nSpace: **O(1)**\n\nRuntime: 38 ms, faster than **86.22%** of Python3 online submissions for Rotate List.\nMemory Usage: 13.9 MB, less than **88.66%** of Python3 online submissions for Rotate List.\n\n```\nclass Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if not head: return head\n \n zero = ListNode(next=head) # dummy node\n \n count, tail = 0, zero\n while tail.next:\n count, tail = count + 1, tail.next\n \n k = k % count\n if not k: return head\n\n newTail = zero\n for _ in range(0, count - k):\n newTail = newTail.next\n\n zero.next, tail.next, newTail.next = newTail.next, head, None\n \n return zero.next\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 5,973 |
Unique Paths | unique-paths | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. | Math,Dynamic Programming,Combinatorics | Medium | null | 1,172 | 22 | # Intuition\nThe main idea to solve the unique paths question is to use dynamic programming to calculate the number of unique paths from the top-left corner of a grid to the bottom-right corner. \n\nThis approach efficiently solves the problem by breaking it down into smaller subproblems and avoiding redundant calculations. It\'s a classic example of dynamic programming used for finding solutions to grid-related problems.\n\n---\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 253 videos as of September 3rd, 2023.\n\n\n\n### In the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n### \u2B50\uFE0F Don\'t forget to subscribe to my channel!\n\n**\u25A0 Subscribe URL**\n\n\n---\n\n# Approach\nThis is based on Python. Other might be differnt a bit.\n\n1. **Initialization of the AboveRow list**\n - Main Point: Initialize the aboveRow list with `n` elements, all set to 1.\n - Detailed Explanation: This list represents the number of unique paths for each column in the top row of the grid. It\'s initialized with 1 because there\'s only one way to reach each cell in the top row, which is by moving horizontally.\n\n2. **Iteration through Rows**\n - Main Point: Loop `m - 1` times, where `m` is the number of rows in the grid.\n - Detailed Explanation: This loop iterates over each row below the top row. The `-1` is used because the top row was already initialized, and there\'s no need to recompute it.\n\n3. **Creating a New Row**\n - Main Point: Inside the loop, create a new list called currentRow with `n` elements, all set to 1.\n - Detailed Explanation: For each row below the top row, we create a new list to store the number of unique paths for each column in that row. All values are initialized to 1 because there are no previous paths to consider yet.\n\n4. **Nested Loop for Columns**\n - Main Point: Iterate over each column in the currentRow from index 1 to `n - 1`.\n - Detailed Explanation: This nested loop starts from index 1 because the cell at index 0 already has one unique path, and we want to calculate the number of unique paths for the remaining cells in the current row.\n\n5. **Updating Cell Values**\n - Main Point: In the nested loop, update the currentRow list at index `i` by adding the value at index `i-1` of the currentRow and the value at index `i` of the aboveRow.\n - Detailed Explanation: This step implements the dynamic programming logic. The number of unique paths to reach a cell in the current row is the sum of the number of paths to reach the cell immediately to the left (in the same row) and the number of paths to reach the cell above it (from the aboveRow).\n\n6. **Updating aboveRow**\n - Main Point: After the nested loop completes, update the aboveRow to be equal to the currentRow.\n - Detailed Explanation: We update the aboveRow to be the same as the currentRow because it becomes the reference for the next row calculation.\n\n7. **Returning the Result**\n - Main Point: Once the outer loop finishes, return the last element of the aboveRow list, which represents the number of unique paths to reach the bottom-right cell of the grid.\n - Detailed Explanation: The final result is stored in the last element of the aboveRow list because it represents the number of unique paths to reach the last column in the last row, which is the destination cell.\n\nThis algorithm efficiently calculates the number of unique paths to traverse an `m x n` grid from the top-left corner to the bottom-right corner using dynamic programming.\n\n# Complexity\n- Time complexity: O(m * n)\n\n- Space complexity: O(n)\nn is the number of columns in the grid\n\n```python []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n\n aboveRow = [1] * n\n\n for _ in range(m - 1):\n currentRow = [1] * n\n for i in range(1, n):\n currentRow[i] = currentRow[i-1] + aboveRow[i]\n aboveRow = currentRow\n \n return aboveRow[-1]\n```\n```javascript []\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nvar uniquePaths = function(m, n) {\n let aboveRow = Array(n).fill(1);\n\n for (let row = 1; row < m; row++) {\n let currentRow = Array(n).fill(1);\n for (let col = 1; col < n; col++) {\n currentRow[col] = currentRow[col - 1] + aboveRow[col];\n }\n aboveRow = currentRow;\n }\n\n return aboveRow[n - 1]; \n};\n```\n```java []\nclass Solution {\n public int uniquePaths(int m, int n) {\n int[] aboveRow = new int[n];\n Arrays.fill(aboveRow, 1);\n\n for (int row = 1; row < m; row++) {\n int[] currentRow = new int[n];\n Arrays.fill(currentRow, 1);\n for (int col = 1; col < n; col++) {\n currentRow[col] = currentRow[col - 1] + aboveRow[col];\n }\n aboveRow = currentRow;\n }\n\n return aboveRow[n - 1]; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int uniquePaths(int m, int n) {\n std::vector<int> aboveRow(n, 1);\n\n for (int row = 1; row < m; row++) {\n std::vector<int> currentRow(n, 1);\n for (int col = 1; col < n; col++) {\n currentRow[col] = currentRow[col - 1] + aboveRow[col];\n }\n aboveRow = currentRow;\n }\n\n return aboveRow[n - 1]; \n }\n};\n```\n | 6,005 |
Unique Paths | unique-paths | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. | Math,Dynamic Programming,Combinatorics | Medium | null | 15,671 | 113 | # Interview Guide - Unique Paths in a Grid\n\n## Problem Understanding\n\nThe problem describes a robot situated on a $$ m \\times n $$ grid, starting at the top-left corner (i.e., $$ \\text{grid}[0][0] $$). The robot can move either to the right or downwards at any given time, and the objective is to reach the bottom-right corner of the grid. The challenge is to find the number of unique paths the robot can take to reach this goal.\n\n### Key Points to Consider\n\n1. **Grid Dimensions**: \n The grid dimensions are $$ m $$ (rows) and $$ n $$ (columns), with $$ 1 \\leq m, n \\leq 100 $$.\n \n2. **Movement Constraints**: \n The robot can only move either down or to the right at any given point. It cannot move diagonally or backwards.\n\n3. **Dynamic Programming and Combinatorial Mathematics**: \n The problem can be solved using either a Dynamic Programming approach or using Combinatorial Mathematics.\n\n---\n\n## Live Coding & More - 3 Solutions\n\n\n## Solution #1: Dynamic Programming\n\n### Intuition and Logic Behind the Solution\n\nThe idea behind this approach is to use a 2D Dynamic Programming (DP) array to store the number of unique paths to each cell. A cell $$ (i, j) $$ can be reached either from $$ (i-1, j) $$ or $$ (i, j-1) $$, and thus the number of unique paths to $$ (i, j) $$ is the sum of the number of unique paths to these two cells.\n\n### Step-by-step Explanation\n\n1. **Initialization**: \n - Create a $$ m \\times n $$ DP array, initializing the first row and first column to 1 because there\'s only one way to reach those cells from the starting point.\n\n2. **Main Algorithm**: \n - Iterate over the DP array starting from cell $$ (1, 1) $$.\n - For each cell $$ (i, j) $$, set $$ \\text{dp}[i][j] = \\text{dp}[i-1][j] + \\text{dp}[i][j-1] $$.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$ O(m \\times n) $$ \u2014 We iterate through each cell once.\n- **Space Complexity**: $$ O(m \\times n) $$ \u2014 For the DP array.\n\n---\n\n## Solution #2: Memory-Optimized Dynamic Programming\n\n### Intuition and Logic Behind the Solution\n\nThe original DP solution used a $$ m \\times n $$ array to store the number of unique paths to each cell. However, since we only need information from the previous row and the current row to compute the number of unique paths for a given cell, we can optimize the solution to use only two rows at a time. This reduces the space complexity from $$ O(m \\times n) $$ to $$ O(n) $$.\n\n### Transitioning from $$ O(m \\times n) $$ to $$ O(n) $$\n\nIn the original $$ O(m \\times n) $$ approach, we used a 2D array `dp` where $$ \\text{dp}[i][j] $$ represented the number of unique paths to reach cell $$ (i, j) $$. To optimize this to $$ O(n) $$, we can maintain only two 1D arrays: `prev_row` and `curr_row`, each of length $$ n $$.\n\n- `prev_row[j]` will represent $$ \\text{dp}[i-1][j] $$, the number of unique paths to reach the cell in the previous row and $$ j $$-th column.\n- `curr_row[j]` will represent $$ \\text{dp}[i][j] $$, the number of unique paths to reach the cell in the current row and $$ j $$-th column.\n\n### Step-by-step Explanation\n\n1. **Initialization**: \n - Initialize two 1D arrays `curr_row` and `prev_row` with $$ n $$ elements, setting all elements to 1.\n\n2. **Main Algorithm**: \n - Iterate over the rows starting from 1 (the second row).\n - For each cell $$ (i, j) $$, set `curr_row[j] = curr_row[j-1] + prev_row[j]` .\n - Swap `curr_row` and `prev_row` for the next iteration.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$ O(m \\times n) $$ \u2014 We still iterate through each cell once.\n- **Space Complexity**: $$ O(n) $$ \u2014 For the two 1D arrays.\n\n---\n\n## Solution #3: Combinatorial Mathematics\n\n### Intuition\n\nThe number of unique paths can be seen as the number of ways to choose $$ m-1 $$ downs and $$ n-1 $$ rights, regardless of the order. In combinatorial terms, this is equivalent to $$ \\binom{m+n-2}{m-1} $$.\n\n### Algorithm\n\n1. **Use the Combinatorial Formula**: \n $$ \\binom{m+n-2}{m-1} $$ or $$ \\binom{m+n-2}{n-1} $$ to calculate the number of unique paths.\n\n2. **Python\'s Math Library**: \n Python provides a built-in function $$ \\text{math.comb(n, k)} $$ to calculate $$ \\binom{n}{k} $$ efficiently.\n\n### Complexity Analysis\n\n- **Time Complexity**: $$ O(m) $$ or $$ O(n) $$ \u2014 For calculating the combination.\n- **Space Complexity**: $$ O(1) $$ \u2014 Constant space.\n\n---\n\n# Performance\n### Dynamic Programming\n\n| Language | Time (ms) | Memory (MB) |\n|-----------|-----------|-------------|\n| Rust | 0 ms | 2.2 MB |\n| C++ | 0 ms | 6.5 MB |\n| Java | 0 ms | 39.9 MB |\n| Go | 1 ms | 2.1 MB |\n| PHP | 10 ms | 19.3 MB |\n| C# | 23 ms | 26.6 MB |\n| Python3 (1D) | 26 ms | 16.3 MB |\n| Python3 (2D) | 28 ms | 16.3 MB |\n| JavaScript| 52 ms | 41.6 MB |\n\n![dp.png]()\n\n\n## Combinatorial Mathematics\n\n| Language | Time (ms) | Memory (MB) |\n|-----------|-----------|-------------|\n| Rust | 0 ms | 2.2 MB |\n| C++ | 0 ms | 5.9 MB |\n| PHP | 0 ms | 18.9 MB |\n| Java | 0 ms | 39.8 MB |\n| Go | 1 ms | 1.9 MB |\n| C# | 22 ms | 26.5 MB |\n| Python3 | 27 ms | 16.4 MB |\n| JavaScript| 55 ms | 41.3 MB |\n\n![mt.png]()\n\n# Code Math\n``` Python []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n return math.comb(m+n-2, m-1)\n```\n``` Rust []\nimpl Solution {\n pub fn unique_paths(m: i32, n: i32) -> i32 {\n let mut ans: i64 = 1;\n for i in 1..=m as i64 - 1 {\n ans = ans * (n as i64 - 1 + i) / i;\n }\n ans as i32\n }\n}\n```\n``` Go []\nfunc uniquePaths(m int, n int) int {\n ans := 1\n for i := 1; i <= m - 1; i++ {\n ans = ans * (n - 1 + i) / i\n }\n return ans\n}\n```\n``` C++ []\n#include <cmath>\nclass Solution {\npublic:\n int uniquePaths(int m, int n) {\n long long ans = 1;\n for (int i = 1; i <= m - 1; ++i) {\n ans = ans * (n - 1 + i) / i;\n }\n return (int)ans;\n }\n};\n```\n``` Java []\npublic class Solution {\n public int uniquePaths(int m, int n) {\n long ans = 1;\n for (int i = 1; i <= m - 1; i++) {\n ans = ans * (n - 1 + i) / i;\n }\n return (int)ans;\n }\n}\n```\n``` C# []\npublic class Solution {\n public int UniquePaths(int m, int n) {\n long ans = 1;\n for (int i = 1; i <= m - 1; i++) {\n ans = ans * (n - 1 + i) / i;\n }\n return (int)ans;\n }\n}\n```\n``` PHP []\nclass Solution {\n function uniquePaths($m, $n) {\n $ans = 1;\n for ($i = 1; $i <= $m - 1; ++$i) {\n $ans = $ans * ($n - 1 + $i) / $i;\n }\n return (int)$ans;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nvar uniquePaths = function(m, n) {\n let ans = 1;\n for (let i = 1; i <= m - 1; i++) {\n ans = ans * (n - 1 + i) / i;\n }\n return ans;\n};\n```\n# Code DP - 2D\n``` Python []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n dp = [[1 if i == 0 or j == 0 else 0 for j in range(n)] for i in range(m)]\n \n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n \n return dp[-1][-1]\n```\n``` C++ []\nclass Solution {\npublic:\n int uniquePaths(int m, int n) {\n vector<vector<int>> dp(m, vector<int>(n, 0));\n \n for (int i = 0; i < m; ++i) {\n dp[i][0] = 1;\n }\n for (int j = 0; j < n; ++j) {\n dp[0][j] = 1;\n }\n \n for (int i = 1; i < m; ++i) {\n for (int j = 1; j < n; ++j) {\n dp[i][j] = dp[i-1][j] + dp[i][j-1];\n }\n }\n \n return dp[m-1][n-1];\n }\n};\n```\n``` Java []\npublic class Solution {\n public int uniquePaths(int m, int n) {\n int[][] dp = new int[m][n];\n \n for (int i = 0; i < m; i++) {\n dp[i][0] = 1;\n }\n for (int j = 0; j < n; j++) {\n dp[0][j] = 1;\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j] = dp[i-1][j] + dp[i][j-1];\n }\n }\n \n return dp[m-1][n-1];\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn unique_paths(m: i32, n: i32) -> i32 {\n let mut dp: Vec<Vec<i32>> = vec![vec![1; n as usize]; m as usize];\n \n for i in 1..m as usize {\n for j in 1..n as usize {\n dp[i][j] = dp[i-1][j] + dp[i][j-1];\n }\n }\n \n dp[(m-1) as usize][(n-1) as usize]\n }\n}\n```\n``` Go []\nfunc uniquePaths(m int, n int) int {\n dp := make([][]int, m)\n for i := range dp {\n dp[i] = make([]int, n)\n }\n \n for i := 0; i < m; i++ {\n dp[i][0] = 1\n }\n for j := 0; j < n; j++ {\n dp[0][j] = 1\n }\n \n for i := 1; i < m; i++ {\n for j := 1; j < n; j++ {\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n }\n }\n \n return dp[m-1][n-1]\n}\n```\n``` C# []\npublic class Solution {\n public int UniquePaths(int m, int n) {\n int[,] dp = new int[m, n];\n \n for (int i = 0; i < m; i++) {\n dp[i, 0] = 1;\n }\n for (int j = 0; j < n; j++) {\n dp[0, j] = 1;\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i, j] = dp[i-1, j] + dp[i, j-1];\n }\n }\n \n return dp[m-1, n-1];\n }\n}\n```\n``` PHP []\nclass Solution {\n function uniquePaths($m, $n) {\n $dp = array_fill(0, $m, array_fill(0, $n, 0));\n \n for ($i = 0; $i < $m; ++$i) {\n $dp[$i][0] = 1;\n }\n for ($j = 0; $j < $n; ++$j) {\n $dp[0][$j] = 1;\n }\n \n for ($i = 1; $i < $m; ++$i) {\n for ($j = 1; $j < $n; ++$j) {\n $dp[$i][$j] = $dp[$i-1][$j] + $dp[$i][$j-1];\n }\n }\n \n return $dp[$m-1][$n-1];\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nvar uniquePaths = function(m, n) {\n const dp = Array.from({ length: m }, () => Array(n).fill(0));\n \n for (let i = 0; i < m; ++i) {\n dp[i][0] = 1;\n }\n for (let j = 0; j < n; ++j) {\n dp[0][j] = 1;\n }\n \n for (let i = 1; i < m; ++i) {\n for (let j = 1; j < n; ++j) {\n dp[i][j] = dp[i-1][j] + dp[i][j-1];\n }\n }\n \n return dp[m-1][n-1];\n};\n```\n# Code DP - 1D\n``` Python []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n curr_row = [1] * n\n prev_row = [1] * n\n\n for i in range(1, m):\n for j in range(1, n):\n curr_row[j] = curr_row[j - 1] + prev_row[j] \n curr_row, prev_row = prev_row, curr_row\n \n return prev_row[-1]\n```\n\n## Final Thoughts\n\nBoth solutions are valid for the given problem constraints. The Dynamic Programming approach is more general and can be extended to more complex scenarios, such as when some cells are blocked. On the other hand, the Combinatorial Mathematics approach is more efficient for this specific problem.\n\nTackling this problem offers a deep dive into Dynamic Programming and Combinatorial Mathematics. Whether you use a dynamic table or mathematical combinations, each approach is a lesson in computational thinking. This isn\'t just a problem; it\'s a tool for honing your optimization and math skills. So dive in and advance your algorithm mastery. \uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB\uD83C\uDF1F | 6,006 |
Unique Paths | unique-paths | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. | Math,Dynamic Programming,Combinatorics | Medium | null | 4,558 | 103 | # Question Understanding-\n\n**Given are only two valid moves :**\n- **Move right**\n- **Move down**\nHence, it is clear number of paths from cell (i,j) = sum of paths from cell( i+1,j) and cell(i,j+1)\n\n**It becomes a DP problem.**\nBut implementing DP directly **will lead to TLE**.\n**So memoization is useful -> Storing a result** so that we donot need to calculate it again.\n\ndp[i][j] = d[i+1][j] + dp[i][j+1]\n\n# BASE CASES\n\n**If we are in last row**, i == m-1, we only have the choice to move RIGHT, Hence number of moves will be 1.\n**If we are in last column**, j == n-1, we only have the choice to move DOWN, Hence number of moves will be 1.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Step-by-Step Solution:\n\n---\n\n\n---\n# **Bottom-Up Dynamic Programming:**\n\n**Step 1: Initialize the DP Table**\n- Create a 2D DP (dynamic programming) table of **size m x n** to store the number of unique paths for each cell.\n- **Initialize the rightmost column and bottom row of the DP table to 1** because there\'s only one way to reach each cell in those rows/columns (by moving all the way right or all the way down).\n\n**Step 2: Fill in the DP Table**\n\n- **Start from the second-to-last** row and second-to-last column (i.e., i = m - 2 and j = n - 2).\n- **For each cell (i, j) in the grid:**\n - Calculate the **number of unique paths to reach (i, j)** as the sum of the unique paths from the cell below (i+1, j) and **the cell to the right (i, j+1)**. Use this formula: **dp[i][j] = dp[i+1][j] + dp[i][j+1].**\n - **Continue filling** in the DP table row by row and column by column until you reach the top-left corner (dp[0][0]).\n\n**Step 3: Return the Result**\n\n- Return the value stored in the top-left corner of the DP table (dp[0][0]), which represents the number of unique paths from the top-left corner to the bottom-right corner.\n<!-- Describe your approach to solving the problem. -->\n\n---\n\n\n---\n\n\n# **Top-Down Dynamic Programming:**\n\n**Step 1: Initialize the Memoization Table**\n\n- **Create a memoization table** (an auxiliary 2D array) of size m x n to store computed results. Initialize all entries to -1 to indicate that no results have been computed yet.\n\n**Step 2: Recursive Function**\n- **Implement a recursive function**, say **uniquePathsRecursive(x, y, m, n, memo)**, which calculates the number of unique paths to reach cell (x, y) from the top-left corner.\n- **In this function:**\n - **Check if (x, y) is the destination cell** (m - 1, n - 1). If yes, return 1 since there is one way to reach the destination.\n - **Check if the result for (x, y) is already computed** in the memoization table (memo[x][y] != -1). **If yes, return the stored result.** \n\n - **Otherwise, calculate the number of unique paths** by recursively moving right and down (if valid) and adding the results. **Use the following logic:**\n \u27A1**If (x, y) can move right** (i.e., x < m - 1), calculate rightPaths = uniquePathsRecursive(x + 1, y, m, n, memo).\n \u27A1 **If (x, y) can move down** (i.e., y < n - 1), calculate downPaths = uniquePathsRecursive(x, y + 1, m, n, memo).\n \u27A1 **The total unique paths to (x, y) are rightPaths + downPaths.**\n \u27A1** Store the result** in the memoization table (memo[x][y]) and return it. \n\n**Step 3: Invoke the Recursive Function**\n\n- Call the recursive function with the initial arguments (0, 0, m, n, memo) to find the number of unique paths.\n\n**Step 4: Return the Result**\n\n- The result obtained from the recursive function call represents the number of unique paths from the top-left corner to the bottom-right corner.\n # Complexity\n\n---\n\n\n**Bottom-Up Dynamic Programming:**\n**Time Complexity (TC):** The bottom-up approach fills in the DP table iteratively, visiting each cell once. There are m rows and n columns in the grid, so the TC is **O(m * n)**.\n**Space Complexity (SC):** The space complexity is determined by the DP table, which is of size m x n. Therefore, **the SC is O(m * n)** to store the DP table.\n\n---\n\n\n**Top-Down Dynamic Programming (with Memoization):**\n**Time Complexity (TC):** O(m * n).\n**Space Complexity (SC):** O(m + n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n---\n\n\n\n# \uD83D\uDE0A\uD83D\uDE0ASMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n---\n\n\n# Bottom up Approach Code\n```C++ []\nclass Solution {\npublic:\n int uniquePaths(int m, int n) {\n vector<vector<int>> dp(m, vector<int>(n, 0));\n \n // Initialize the rightmost column and bottom row to 1 because there is only one way to reach each cell in those rows/columns.\n for (int i = 0; i < m; i++) {\n dp[i][n-1] = 1;\n }\n for (int j = 0; j < n; j++) {\n dp[m-1][j] = 1;\n }\n \n // Fill in the dp table bottom-up\n for (int i = m - 2; i >= 0; i--) {\n for (int j = n - 2; j >= 0; j--) {\n dp[i][j] = dp[i+1][j] + dp[i][j+1];\n }\n }\n \n return dp[0][0];\n }\n};\n\n```\n```python3 []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n # Create a 2D DP table filled with zeros\n dp = [[0] * n for _ in range(m)]\n \n # Initialize the rightmost column and bottom row to 1\n for i in range(m):\n dp[i][n-1] = 1\n for j in range(n):\n dp[m-1][j] = 1\n \n # Fill in the DP table bottom-up\n for i in range(m - 2, -1, -1):\n for j in range(n - 2, -1, -1):\n dp[i][j] = dp[i+1][j] + dp[i][j+1]\n \n # Return the result stored in the top-left corner\n return dp[0][0]\n\n```\n```Java []\nclass Solution {\n public int uniquePaths(int m, int n) {\n // Create a 2D DP array filled with zeros\n int[][] dp = new int[m][n];\n \n // Initialize the rightmost column and bottom row to 1\n for (int i = 0; i < m; i++) {\n dp[i][n-1] = 1;\n }\n for (int j = 0; j < n; j++) {\n dp[m-1][j] = 1;\n }\n \n // Fill in the DP array bottom-up\n for (int i = m - 2; i >= 0; i--) {\n for (int j = n - 2; j >= 0; j--) {\n dp[i][j] = dp[i+1][j] + dp[i][j+1];\n }\n }\n \n // Return the result stored in the top-left corner\n return dp[0][0];\n }\n}\n\n```\n```Javascript []\nvar uniquePaths = function(m, n) {\n // Create a 2D DP array filled with zeros\n let dp = new Array(m).fill().map(() => new Array(n).fill(0));\n \n // Initialize the rightmost column and bottom row to 1\n for (let i = 0; i < m; i++) {\n dp[i][n-1] = 1;\n }\n for (let j = 0; j < n; j++) {\n dp[m-1][j] = 1;\n }\n \n // Fill in the DP array bottom-up\n for (let i = m - 2; i >= 0; i--) {\n for (let j = n - 2; j >= 0; j--) {\n dp[i][j] = dp[i+1][j] + dp[i][j+1];\n }\n }\n \n // Return the result stored in the top-left corner\n return dp[0][0];\n};\n\n```\n# Top-Down Approach Code\n\n```C++ []\nclass Solution {\npublic:\n int uniquePaths(int m, int n) {\n // Create a memoization table to store computed results\n vector<vector<int>> memo(m, vector<int>(n, -1));\n \n // Call the recursive function to compute unique paths\n return uniquePathsRecursive(0, 0, m, n, memo);\n }\n \n int uniquePathsRecursive(int x, int y, int m, int n, vector<vector<int>>& memo) {\n // If we reach the destination (bottom-right corner), return 1\n if (x == m - 1 && y == n - 1) {\n return 1;\n }\n \n // If we have already computed the result for this cell, return it from the memo table\n if (memo[x][y] != -1) {\n return memo[x][y];\n }\n \n // Calculate the number of unique paths by moving right and down\n int rightPaths = 0;\n int downPaths = 0;\n \n // Check if it\'s valid to move right\n if (x < m - 1) {\n rightPaths = uniquePathsRecursive(x + 1, y, m, n, memo);\n }\n \n // Check if it\'s valid to move down\n if (y < n - 1) {\n downPaths = uniquePathsRecursive(x, y + 1, m, n, memo);\n }\n \n // Store the result in the memo table and return it\n memo[x][y] = rightPaths + downPaths;\n return memo[x][y];\n }\n};\n\n```\n```python3 []\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n # Create a memoization table to store computed results\n memo = [[-1 for _ in range(n)] for _ in range(m)]\n \n # Call the recursive function to compute unique paths\n return self.uniquePathsRecursive(0, 0, m, n, memo)\n \n def uniquePathsRecursive(self, x: int, y: int, m: int, n: int, memo: List[List[int]]) -> int:\n # If we reach the destination (bottom-right corner), return 1\n if x == m - 1 and y == n - 1:\n return 1\n \n # If we have already computed the result for this cell, return it from the memo table\n if memo[x][y] != -1:\n return memo[x][y]\n \n # Calculate the number of unique paths by moving right and down\n rightPaths = 0\n downPaths = 0\n \n # Check if it\'s valid to move right\n if x < m - 1:\n rightPaths = self.uniquePathsRecursive(x + 1, y, m, n, memo)\n \n # Check if it\'s valid to move down\n if y < n - 1:\n downPaths = self.uniquePathsRecursive(x, y + 1, m, n, memo)\n \n # Store the result in the memo table and return it\n memo[x][y] = rightPaths + downPaths\n return memo[x][y]\n\n```\n```Java []\nclass Solution {\n public int uniquePaths(int m, int n) {\n // Create a memoization table to store computed results\n int[][] memo = new int[m][n];\n \n // Initialize the memoization table with -1 to indicate uncomputed results\n for (int i = 0; i < m; i++) {\n Arrays.fill(memo[i], -1);\n }\n \n // Call the recursive function to compute unique paths\n return uniquePathsRecursive(0, 0, m, n, memo);\n }\n \n public int uniquePathsRecursive(int x, int y, int m, int n, int[][] memo) {\n // If we reach the destination (bottom-right corner), return 1\n if (x == m - 1 && y == n - 1) {\n return 1;\n }\n \n // If we have already computed the result for this cell, return it from the memo table\n if (memo[x][y] != -1) {\n return memo[x][y];\n }\n \n // Calculate the number of unique paths by moving right and down\n int rightPaths = 0;\n int downPaths = 0;\n \n // Check if it\'s valid to move right\n if (x < m - 1) {\n rightPaths = uniquePathsRecursive(x + 1, y, m, n, memo);\n }\n \n // Check if it\'s valid to move down\n if (y < n - 1) {\n downPaths = uniquePathsRecursive(x, y + 1, m, n, memo);\n }\n \n // Store the result in the memo table and return it\n memo[x][y] = rightPaths + downPaths;\n return memo[x][y];\n }\n}\n\n```\n```Javascript []\nvar uniquePaths = function(m, n) {\n // Create a memoization table to store computed results\n let memo = new Array(m).fill(null).map(() => new Array(n).fill(-1));\n \n // Call the recursive function to compute unique paths\n return uniquePathsRecursive(0, 0, m, n, memo);\n};\n\nvar uniquePathsRecursive = function(x, y, m, n, memo) {\n // If we reach the destination (bottom-right corner), return 1\n if (x === m - 1 && y === n - 1) {\n return 1;\n }\n \n // If we have already computed the result for this cell, return it from the memo table\n if (memo[x][y] !== -1) {\n return memo[x][y];\n }\n \n // Calculate the number of unique paths by moving right and down\n let rightPaths = 0;\n let downPaths = 0;\n \n // Check if it\'s valid to move right\n if (x < m - 1) {\n rightPaths = uniquePathsRecursive(x + 1, y, m, n, memo);\n }\n \n // Check if it\'s valid to move down\n if (y < n - 1) {\n downPaths = uniquePathsRecursive(x, y + 1, m, n, memo);\n }\n \n // Store the result in the memo table and return it\n memo[x][y] = rightPaths + downPaths;\n return memo[x][y];\n};\n\n```\n# \uD83D\uDE0A\uD83D\uDE0ASMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A![UPVOTE.png]()\n | 6,007 |
Unique Paths | unique-paths | There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. The test cases are generated so that the answer will be less than or equal to 2 * 109. | Math,Dynamic Programming,Combinatorics | Medium | null | 300 | 5 | # 1. Recursive Approach-------->Top to Down\n```\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n def solve(ind1,ind2):\n if ind1==0 and ind2==0:\n return 1\n if ind1<0 or ind2<0:\n return 0\n return solve(ind1-1,ind2)+solve(ind1,ind2-1)\n return solve(m-1,n-1)\n ```\n # 2. Memorization Approach\n ```\n class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n dp=[[-1]*(n+1) for i in range(m)]\n def solve(ind1,ind2):\n if ind1==0 and ind2==0:\n return 1\n if ind1<0 or ind2<0:\n return 0\n if dp[ind1][ind2]!=-1:\n return dp[ind1][ind2]\n left=solve(ind1,ind2-1)\n up=solve(ind1-1,ind2)\n dp[ind1][ind2]=up+left\n return left+up\n return solve(m-1,n-1)\n```\n# 3. Tabulation------>Bottom to Up Approach\n```\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n dp=[[0]*(n+1) for i in range(m+1)]\n for ind1 in range(1,m+1):\n for ind2 in range(1,n+1):\n if ind1==ind2==1:\n dp[ind1][ind2]=1\n else:\n left=up=0\n if ind2-1>=0:\n left=dp[ind1][ind2-1]\n if ind1-1>=0:\n up=dp[ind1-1][ind2]\n dp[ind1][ind2]=up+left\n return dp[-1][-1]\n```\n# 4. Space Optimization\n```\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n prev=[0]*(n+1)\n for ind1 in range(1,m+1):\n cur=[0]*(n+1)\n for ind2 in range(1,n+1):\n if ind1==ind2==1:\n cur[ind2]=1\n else:\n left=up=0\n if ind2-1>=0:\n left=cur[ind2-1]\n if ind1-1>=0:\n up=prev[ind2]\n cur[ind2]=up+left\n prev=cur\n return cur[-1]\n```\n# please upvote me it would encourage me alot\n | 6,082 |
Unique Paths II | unique-paths-ii | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. | Array,Dynamic Programming,Matrix | Medium | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | 3,198 | 15 | # Intuition\nMain goal is to determine the count of unique paths from the top-left corner to the bottom-right corner of a grid while accounting for obstacles in the grid. It uses dynamic programming to iteratively calculate the paths, avoiding obstacles and utilizing previously computed values to efficiently arrive at the final count.\n\nThis python solution beats 96%.\n![Screen Shot 2023-08-12 at 21.13.22.png]()\n\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n# Subscribe to my channel from here. I have 244 videos as of August 12th\n\n\n\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. Define the class `Solution` which contains the method `uniquePathsWithObstacles` that takes `obstacleGrid` as input and returns the number of unique paths.\n\n2. Check if `obstacleGrid` is empty or if the starting cell (0, 0) is an obstacle (marked as 1). If either of these conditions is met, return 0, as there is no way to reach the destination.\n\n3. Get the number of rows and columns in the `obstacleGrid` and store them in `rows` and `cols` variables, respectively.\n\n4. Create an array `dp` of size `cols` to store the number of unique paths for each column. Initialize all values in `dp` to 0.\n\n5. Set `dp[0]` to 1, representing the number of ways to reach the starting cell (0, 0).\n\n6. Iterate through each row (`r`) in the `obstacleGrid`:\n\n a. For each row, iterate through each column (`c`) in the `obstacleGrid`:\n\n - If the current cell (`obstacleGrid[r][c]`) contains an obstacle (marked as 1), set `dp[c]` to 0, indicating that there are no paths to reach this obstacle cell.\n\n - Otherwise, if the current cell is not an obstacle:\n\n - Check if `c` is greater than 0 (i.e., not in the leftmost column). If true, update `dp[c]` by adding the value of `dp[c - 1]`. This accounts for the paths coming from the cell above (`dp[c]`) and the cell to the left (`dp[c - 1]`).\n\n7. After iterating through all the cells in the grid, return the value of `dp[cols - 1]`, which represents the number of unique paths to reach the bottom-right cell (rows - 1, cols - 1).\n\nIn summary, this algorithm uses dynamic programming to calculate the number of unique paths from the top-left corner to the bottom-right corner of the grid while avoiding obstacles. The `dp` array is updated iteratively, taking into account the paths from the cell above and the cell to the left.\n\n# How solution code works\n`[0, 0, 0]`\n`[0, 1, 0]`\n`[0, 0, 0]`\n\nBefore starting nested loop, `dp` is `[1, 0, 0]`.\n\n1. iterating the first row and using `[1, 0, 0]`(previous result). In the end dp should be `[1, 1, 1]`\n - check `uniquePathsWithObstacles[0][0]` \u2192 `dp = [1, 0, 0]`\n - check `uniquePathsWithObstacles[0][1]` \u2192 `dp = [1, 1, 0]`\n - check `uniquePathsWithObstacles[0][2]` \u2192 `dp = [1, 1, 1]`\n\n2. iterating the second row and using `[1, 1, 1]`(previous result). In the end dp should be `[1, 0, 1]`\n - check `uniquePathsWithObstacles[1][0]` \u2192 `dp = [1, 1, 1]`\n - check `uniquePathsWithObstacles[1][1]` \u2192 `dp = [1, 0, 1]`\n - check `uniquePathsWithObstacles[1][2]` \u2192 `dp = [1, 0, 1]`\n\n3. iterating the thrid row and using `[1, 0, 1]`(previous result). In the end dp should be `[1, 1, 2]`\n - check `uniquePathsWithObstacles[2][0]` \u2192 `dp = [1, 0, 1]`\n - check `uniquePathsWithObstacles[2][1]` \u2192 `dp = [1, 1, 1]`\n - check `uniquePathsWithObstacles[2][2]` \u2192 `dp = [1, 1, 2]` \n\nOutput should be `2`.\n\n# Complexity\n- Time complexity: O(rows * cols)\n\n- Space complexity: O(cols)\n\n```python []\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n if not obstacleGrid or obstacleGrid[0][0] == 1:\n return 0\n\n rows, cols = len(obstacleGrid), len(obstacleGrid[0])\n dp = [0] * cols\n dp[0] = 1\n\n for r in range(rows):\n for c in range(cols):\n if obstacleGrid[r][c] == 1:\n dp[c] = 0\n else:\n if c > 0:\n dp[c] += dp[c - 1]\n\n return dp[cols - 1] \n```\n```javascript []\n/**\n * @param {number[][]} obstacleGrid\n * @return {number}\n */\nvar uniquePathsWithObstacles = function(obstacleGrid) {\n if (!obstacleGrid || obstacleGrid[0][0] === 1) {\n return 0;\n }\n\n const rows = obstacleGrid.length;\n const cols = obstacleGrid[0].length;\n const dp = new Array(cols).fill(0);\n dp[0] = 1;\n\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n if (obstacleGrid[r][c] === 1) {\n dp[c] = 0;\n } else {\n if (c > 0) {\n dp[c] += dp[c - 1];\n }\n }\n }\n }\n\n return dp[cols - 1]; \n};\n```\n```java []\nclass Solution {\n public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n if (obstacleGrid == null || obstacleGrid[0][0] == 1) {\n return 0;\n }\n\n int rows = obstacleGrid.length;\n int cols = obstacleGrid[0].length;\n int[] dp = new int[cols];\n dp[0] = 1;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (obstacleGrid[r][c] == 1) {\n dp[c] = 0;\n } else {\n if (c > 0) {\n dp[c] += dp[c - 1];\n }\n }\n }\n }\n\n return dp[cols - 1]; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n if (obstacleGrid.empty() || obstacleGrid[0][0] == 1) {\n return 0;\n }\n\n int rows = obstacleGrid.size();\n int cols = obstacleGrid[0].size();\n vector<int> dp(cols, 0);\n dp[0] = 1;\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (obstacleGrid[r][c] == 1) {\n dp[c] = 0;\n } else {\n if (c > 0) {\n dp[c] += dp[c - 1];\n }\n }\n }\n }\n\n return dp[cols - 1]; \n }\n};\n```\n\n# Related video\nI have an video for Unique Path I. Please check if you like.\n\n\n\nThank you for reading. Please upvote this article and don\'t forget to subscribe to my youtube channel!\n | 6,147 |
Unique Paths II | unique-paths-ii | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. | Array,Dynamic Programming,Matrix | Medium | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | 9,450 | 50 | # Problem Understanding\n\nIn the "Unique Paths II" problem, we are presented with a grid filled with obstacles and open paths. Starting from the top-left corner, the goal is to find the number of unique paths that lead to the bottom-right corner. We can only move right or down at any point in time. If a cell has an obstacle, we cannot pass through it.\n\nFor example, consider the following grid:\n\n$$\n\\begin{array}{ccc}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 0 \\\\\n\\end{array}\n$$\n\n![63_tsa.png]()\n\n\n- The grid cells with obstacles are colored in red.\n- The two unique paths from the top-left to the bottom-right corner are represented by the blue and green dashed lines.\n\nFrom the plot, you can see the two possible routes:\n\n- The blue path goes Right -> Right -> Down -> Down.\n- The green path goes Down -> Down -> Right -> Right.\n\n---\n\n# Live Coding\n\n\n- [in Python \uD83D\uDC0D]()\n- [in Rust \uD83E\uDD80]()\n\n# Approach\n\n## The Basic Idea\n\nThe underlying concept is rooted in dynamic programming. Essentially, for any cell `(i, j)`, the number of ways you can reach it is the sum of the ways you can reach the cell directly above it `(i-1, j)` and the cell directly to its left `(i, j-1)`. However, this is only true if the cell `(i, j)` does not have an obstacle. If it does, then the number of ways to reach this cell is 0 because it\'s inaccessible.\n\n### 2D Transition:\nIn a 2D dynamic programming approach, you would have a `dp` array of size `m x n`, where ` dp[i][j] ` represents the number of ways to reach cell ` (i, j) `.\n\nThe transition formula would be:\n$$ dp[i][j] = \n\\begin{cases} \n0 & \\text{if } obstacleGrid[i][j] = 1 \\\\\ndp[i-1][j] + dp[i][j-1] & \\text{otherwise}\n\\end{cases}\n$$\n\nSo, for each cell ` (i, j) `, if there\'s no obstacle, its value would be the sum of the cell above it and the cell to its left.\n\n### Translation to 1D:\n\nNow, given the 2D transition, notice how for any cell \\( (i, j) \\), we only need values from the current row and the previous row. This observation allows us to reduce our 2D `dp` array to two 1D arrays, `previous` and `current`.\n\nThe transition formula in 1D would be analogous to the 2D version but slightly adjusted:\n\nFor the first column (`j = 0`):\n$$ current[0] = \n\\begin{cases} \n0 & \\text{if } obstacleGrid[i][0] = 1 \\\\\nprevious[0] & \\text{otherwise}\n\\end{cases}\n$$\n\nFor other columns:\n$$ current[j] = \n\\begin{cases} \n0 & \\text{if } obstacleGrid[i][j] = 1 \\\\\nprevious[j] + current[j-1] & \\text{otherwise}\n\\end{cases}\n$$\n\nHere, `previous` is analogous to `dp[i-1]` and `current` is analogous to `dp[i]` from our 2D approach. After processing each row, we\'ll swap `previous` and `current` to roll over to the next iteration.\n\nThe transition remains conceptually the same between the 2D and 1D versions. The 1D optimization simply leverages the observation that for each cell, we only need data from the current and previous rows. This reduces space complexity from $$ O(m \\times n) $$ to $$ O(n) $$.\n\nThis rolling array technique is a common optimization strategy in dynamic programming problems involving grids.\n\n### Step-by-step Breakdown:\n\n1. **Initialization**:\n - We initialize the `previous` array with zeros. This array represents the number of ways to reach each cell in the previous row.\n - We set `previous[0]` to 1 because there\'s only one way to get to the starting cell (by starting there!).\n \n2. **Iterate through the Grid**:\n - For each row, we consider each cell:\n - If the cell has an obstacle, it\'s unreachable, so the number of ways to get there (`current[j]`) is 0.\n - Otherwise, the number of ways to reach the cell is the sum of the ways to reach the cell above and the cell to the left. This translates to `current[j-1] + previous[j]`.\n - Once we\'ve processed a row, we set `previous` to `current`, preparing for the next iteration.\n\n3. **Result**:\n - Once we\'ve processed all rows, `previous[n-1]` gives us the number of unique paths to the bottom-right corner of the grid.\n\n## Example\n\nUsing the earlier example:\n\n$$\n\\begin{array}{ccc}\n0 & 0 & 0 \\\\\n0 & 1 & 0 \\\\\n0 & 0 & 0 \\\\\n\\end{array}\n$$\n\nHere\'s how the `previous` and `current` arrays evolve:\n\nThe function\'s output matches the example description:\n\n**Initial State**:\n- `previous`: $$[1, 0, 0]$$\n- `current`: $$[0, 0, 0]$$\n\n**After processing row 0**:\n- `previous`: $$[1, 0, 0]$$\n- `current`: $$[1, 1, 1]$$\n\n**After processing row 1**:\n- `previous`: $$[1, 1, 1]$$\n- `current`: $$[1, 0, 1]$$\n\n**After processing row 2**:\n- `previous`: $$[1, 0, 1]$$\n- `current`: $$[1, 1, 2]$$\n\nFrom the final state of the `previous` array, we can infer that there are 2 unique paths from the top-left to the bottom-right corner, avoiding obstacles. This matches the expected result.\n\n# Complexity\n\n**Time Complexity:** $$O(m \\times n)$$\n**Space Complexity:** $$O(n)$$\n\nThis solution is optimal in terms of both time and space complexity. It efficiently computes the number of unique paths by building upon previous calculations.\n\n# Performance\n\n| Language | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%) |\n|-------------|--------------|------------------|-------------|-----------------|\n| Go | 0 | 100% | 2.4 | 71.38% |\n| C++ | 0 | 100% | 7.6 | 81.25% |\n| Java | 0 | 100% | 40.5 | 72.53% |\n| Rust | 1 | 85% | 2 | 87.50% |\n| Python3 | 38 | 99.30% | 16.3 | 82.98% |\n| JavaScript | 47 | 97.40% | 41.6 | 97.86% |\n| C# | 81 | 80.72% | 38.7 | 63.25% |\n\n![perf_518.png]()\n\n\n---\n\n# Code\n\n``` Python []\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n if not obstacleGrid or not obstacleGrid[0] or obstacleGrid[0][0] == 1:\n return 0\n \n m, n = len(obstacleGrid), len(obstacleGrid[0])\n \n previous = [0] * n\n current = [0] * n\n previous[0] = 1\n \n for i in range(m):\n current[0] = 0 if obstacleGrid[i][0] == 1 else previous[0]\n for j in range(1, n):\n current[j] = 0 if obstacleGrid[i][j] == 1 else current[j-1] + previous[j]\n previous[:] = current\n \n return previous[n-1]\n```\n``` C++ []\nclass Solution {\npublic:\n int uniquePathsWithObstacles(std::vector<std::vector<int>>& obstacleGrid) {\n if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0] == 1) {\n return 0;\n }\n \n int m = obstacleGrid.size();\n int n = obstacleGrid[0].size();\n \n std::vector<int> previous(n, 0);\n std::vector<int> current(n, 0);\n previous[0] = 1;\n \n for (int i = 0; i < m; i++) {\n current[0] = obstacleGrid[i][0] == 1 ? 0 : previous[0];\n for (int j = 1; j < n; j++) {\n current[j] = obstacleGrid[i][j] == 1 ? 0 : current[j-1] + previous[j];\n }\n previous = current;\n }\n \n return previous[n-1];\n }\n};\n```\n``` Go []\nfunc uniquePathsWithObstacles(obstacleGrid [][]int) int {\n if len(obstacleGrid) == 0 || len(obstacleGrid[0]) == 0 || obstacleGrid[0][0] == 1 {\n return 0\n }\n\n m := len(obstacleGrid)\n n := len(obstacleGrid[0])\n\n previous := make([]int, n)\n current := make([]int, n)\n previous[0] = 1\n\n for i := 0; i < m; i++ {\n if obstacleGrid[i][0] == 1 {\n current[0] = 0\n } else {\n current[0] = previous[0]\n }\n \n for j := 1; j < n; j++ {\n if obstacleGrid[i][j] == 1 {\n current[j] = 0\n } else {\n current[j] = current[j-1] + previous[j]\n }\n }\n previous, current = current, previous\n }\n return previous[n-1]\n}\n```\n``` Rust []\nimpl Solution {\n pub fn unique_paths_with_obstacles(obstacleGrid: Vec<Vec<i32>>) -> i32 {\n if obstacleGrid.is_empty() || obstacleGrid[0].is_empty() || obstacleGrid[0][0] == 1 {\n return 0;\n }\n \n let m = obstacleGrid.len();\n let n = obstacleGrid[0].len();\n \n let mut previous = vec![0; n];\n let mut current = vec![0; n];\n previous[0] = 1;\n \n for row in &obstacleGrid {\n current[0] = if row[0] == 1 { 0 } else { previous[0] };\n for j in 1..n {\n if row[j] == 1 {\n current[j] = 0;\n } else {\n current[j] = current[j-1] + previous[j];\n }\n }\n std::mem::swap(&mut previous, &mut current);\n }\n \n previous[n-1]\n }\n}\n```\n``` Java []\npublic class Solution {\n public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0 || obstacleGrid[0][0] == 1) {\n return 0;\n }\n\n int m = obstacleGrid.length;\n int n = obstacleGrid[0].length;\n\n int[] previous = new int[n];\n int[] current = new int[n];\n previous[0] = 1;\n\n for (int i = 0; i < m; i++) {\n current[0] = obstacleGrid[i][0] == 1 ? 0 : previous[0];\n for (int j = 1; j < n; j++) {\n current[j] = obstacleGrid[i][j] == 1 ? 0 : current[j-1] + previous[j];\n }\n System.arraycopy(current, 0, previous, 0, n);\n }\n\n return previous[n-1];\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[][]} obstacleGrid\n * @return {number}\n */\nvar uniquePathsWithObstacles = function(obstacleGrid) {\n if (!obstacleGrid.length || !obstacleGrid[0].length || obstacleGrid[0][0] === 1) {\n return 0;\n }\n\n let m = obstacleGrid.length;\n let n = obstacleGrid[0].length;\n\n let previous = new Array(n).fill(0);\n let current = new Array(n).fill(0);\n previous[0] = 1;\n\n for (let i = 0; i < m; i++) {\n current[0] = obstacleGrid[i][0] === 1 ? 0 : previous[0];\n for (let j = 1; j < n; j++) {\n current[j] = obstacleGrid[i][j] === 1 ? 0 : current[j-1] + previous[j];\n }\n previous = [...current];\n }\n\n return previous[n-1];\n};\n```\n``` C# []\npublic class Solution {\n public int UniquePathsWithObstacles(int[][] obstacleGrid) {\n if (obstacleGrid == null || obstacleGrid.Length == 0 || obstacleGrid[0].Length == 0 || obstacleGrid[0][0] == 1) {\n return 0;\n }\n\n int m = obstacleGrid.Length;\n int n = obstacleGrid[0].Length;\n\n int[] previous = new int[n];\n int[] current = new int[n];\n previous[0] = 1;\n\n for (int i = 0; i < m; i++) {\n current[0] = obstacleGrid[i][0] == 1 ? 0 : previous[0];\n for (int j = 1; j < n; j++) {\n current[j] = obstacleGrid[i][j] == 1 ? 0 : current[j-1] + previous[j];\n }\n Array.Copy(current, previous, n);\n }\n\n return previous[n-1];\n }\n}\n```\n\n# Conclusion\n\nThe "Unique Paths II" problem showcases how dynamic programming can help find solutions to combinatorial problems in a structured and efficient manner. By understanding the relationship between subproblems, we can incrementally build the solution and avoid redundant computations. \n\nAs with any algorithmic challenge, practice and understanding the underlying principles are key. Don\'t hesitate to tweak, optimize, and experiment with the solution to deepen your understanding!\n\n# Live Coding in Rust\n | 6,148 |
Unique Paths II | unique-paths-ii | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. | Array,Dynamic Programming,Matrix | Medium | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | 3,128 | 11 | <iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int uniquePathsWithObstacles(int[][] A) {\n int n = A.length;\n int m = A[0].length;\n int [][] ans = new int[n][m];\n for(int i = 0;i<n;i++){\n if(A[i][0] == 0) ans[i][0] = 1;\n else break;\n }\n for(int j = 0;j<m;j++){\n if(A[0][j] == 0) ans[0][j] = 1;\n else break;\n }\n\n for(int i = 1;i<n;i++){\n for(int j = 1;j<m;j++){\n if(A[i][j]==0) ans[i][j] = ans[i-1][j]+ans[i][j-1];\n }\n }\n return ans[n-1][m-1];\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int uniquePathsWithObstacles(vector<vector<int>>& A) {\n int n = A.size();\n int m = A[0].size();\n vector<vector<int>> ans(n, vector<int>(m, 0));\n \n for (int i = 0; i < n; i++) {\n if (A[i][0] == 0)\n ans[i][0] = 1;\n else\n break;\n }\n \n for (int j = 0; j < m; j++) {\n if (A[0][j] == 0)\n ans[0][j] = 1;\n else\n break;\n }\n \n for (int i = 1; i < n; i++) {\n for (int j = 1; j < m; j++) {\n if (A[i][j] == 0)\n ans[i][j] = ans[i-1][j] + ans[i][j-1];\n }\n }\n \n return ans[n-1][m-1];\n }\n};\n\n```\n\n```\nclass Solution:\n def uniquePathsWithObstacles(self, A: List[List[int]]) -> int:\n n = len(A)\n m = len(A[0])\n ans = [[0] * m for _ in range(n)]\n \n for i in range(n):\n if A[i][0] == 0:\n ans[i][0] = 1\n else:\n break\n \n for j in range(m):\n if A[0][j] == 0:\n ans[0][j] = 1\n else:\n break\n \n for i in range(1, n):\n for j in range(1, m):\n if A[i][j] == 0:\n ans[i][j] = ans[i-1][j] + ans[i][j-1]\n \n return ans[n-1][m-1]\n\n``` | 6,173 |
Unique Paths II | unique-paths-ii | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. | Array,Dynamic Programming,Matrix | Medium | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | 2,064 | 15 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find the number of unique paths from the top-left corner of a matrix to the bottom-right corner. The matrix contains obstacles which are represented by 1 and free spaces represented by 0. If there is an obstacle at a cell, we cannot go through that cell. Our intuition should be to use Dynamic Programming (DP) to solve this problem.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use a DP matrix `dp` of the same size as the input `obstacleGrid`. The value of `dp[i][j]` represents the number of unique paths to reach the cell at `(i, j)` in `obstacleGrid`.\n\nWe can initialize the `dp` matrix with `0`s. For the top-left corner of `obstacleGrid`, if there is an obstacle, then there are no unique paths to reach that cell. Hence, we set `dp[0][0]` to `0`. Otherwise, there is only one unique path to reach that cell, so we set `dp[0][0]` to `1`.\n\nNext, we can consider the first row and first column of `obstacleGrid`. If there is an obstacle in any cell in the first row or first column, we cannot move right or down, respectively. Hence, we set the corresponding `dp` value to `0`. Otherwise, we can only move either right or down in these cells, and hence there is only one unique path to reach these cells. We set the corresponding `dp` value to `1`.\n\nWe then iterate over the remaining cells in `obstacleGrid`, and for each cell, we check if there is an obstacle in that cell. If there is an obstacle, we set the corresponding dp value to 0, as we cannot go through that cell. Otherwise, the number of unique paths to reach that cell is the sum of the number of unique paths to reach the cell above it and the cell to the left of it. Hence, we set `dp[i][j] = dp[i-1][j] + dp[i][j-1]`.\n\nFinally, the number of unique paths to reach the bottom-right corner of `obstacleGrid` is `dp[m-1][n-1]`, where `m` and `n` are the number of rows and columns in `obstacleGrid`, respectively.\n# Complexity\n- Time complexity: The algorithm iterates over each cell in `obstacleGrid` exactly once, and for each cell, it performs a constant number of operations. Hence, the time complexity of this algorithm is $$O(mn)$$.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The algorithm uses a DP matrix `dp` of size `m` x `n`, which requires $$O(mn)$$ space.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n m, n = len(obstacleGrid), len(obstacleGrid[0])\n dp = [[0] * n for _ in range(m)]\n dp[0][0] = 1 if obstacleGrid[0][0] == 0 else 0\n for i in range(1, m):\n if obstacleGrid[i][0] == 0:\n dp[i][0] = dp[i-1][0]\n for j in range(1, n):\n if obstacleGrid[0][j] == 0:\n dp[0][j] = dp[0][j-1]\n for i in range(1, m):\n for j in range(1, n):\n if obstacleGrid[i][j] == 0:\n dp[i][j] = dp[i-1][j] + dp[i][j-1]\n return dp[m-1][n-1]\n``` | 6,188 |
Unique Paths II | unique-paths-ii | You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m-1][n-1]). The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. Return the number of possible unique paths that the robot can take to reach the bottom-right corner. The testcases are generated so that the answer will be less than or equal to 2 * 109. | Array,Dynamic Programming,Matrix | Medium | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | 344 | 7 | # Intuition\nYou can solve this problem using dynamic programming.\n\n# Approach\nYou can solve this problem using dynamic programming. The idea is to create a 2D DP array where each cell `(i, j)` represents the number of unique paths to reach that cell. If the cell contains an obstacle, then the number of paths to that cell is 0. Otherwise, you can calculate the number of paths by adding the number of paths from the cell above `(i-1, j)` and the cell to the left `(i, j-1)`.\n\n\n\n# Complexity\n- Time complexity:\nO(mn)\n\n- Space complexity:\nO(mn)\n\n# Code\n```\nclass Solution(object):\n def uniquePathsWithObstacles(self, obstacleGrid):\n """\n :type obstacleGrid: List[List[int]]\n :rtype: int\n """\n m, n = len(obstacleGrid), len(obstacleGrid[0])\n \n # Create a DP array initialized with 0\n dp = [[0] * n for _ in range(m)]\n \n # Initialize the starting point\n dp[0][0] = 1 if obstacleGrid[0][0] == 0 else 0\n \n # Fill in the DP array\n for i in range(m):\n for j in range(n):\n if obstacleGrid[i][j] == 1:\n dp[i][j] = 0\n else:\n if i > 0:\n dp[i][j] += dp[i - 1][j]\n if j > 0:\n dp[i][j] += dp[i][j - 1]\n \n return dp[m - 1][n - 1]\n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 6,193 |
Minimum Path Sum | minimum-path-sum | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. | Array,Dynamic Programming,Matrix | Medium | null | 27,117 | 288 | # 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\n# Video Solution\n**Search \uD83D\uDC49 `Minimum Path Sum by Tech Wired` on YouTube**\n\n![Yellow & Black Earn Money YouTube Thumbnail (1).png]()\n\n\nHappy Learning, Cheers Guys \uD83D\uDE0A\n\n# Approach:\n\n- The code implements a dynamic programming approach to find the minimum path sum in a grid.\n\n- The algorithm uses a 2D array to store the minimum path sum to reach each position (i, j) in the grid, where i represents the row and j represents the column.\n\n- The minimum path sum to reach each position (i, j) is computed by taking the minimum of the path sum to reach the position above (i-1, j) and the position to the left (i, j-1), and adding the cost of the current position (i, j).\n\n- The minimum path sum to reach the bottom-right corner of the grid is stored in the last element of the array (grid[m-1][n-1]), where m is the number of rows and n is the number of columns in the grid.\n\n# Intuition:\n\n- The intuition behind the dynamic programming approach is that the minimum path sum to reach a position (i, j) in the grid can be computed by considering the minimum path sum to reach the positions (i-1, j) and (i, j-1).\n\n- This is because the only two possible ways to reach the position (i, j) are either by moving down from (i-1, j) or moving right from (i, j-1).\n\n- By computing the minimum path sum to reach each position in the grid, the algorithm can find the minimum path sum to reach the bottom-right corner of the grid by simply looking at the last element of the array (grid[m-1][n-1]).\n\n\n```Python []\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n \n \n m, n = len(grid), len(grid[0])\n \n for i in range(1, m):\n grid[i][0] += grid[i-1][0]\n \n for i in range(1, n):\n grid[0][i] += grid[0][i-1]\n \n for i in range(1, m):\n for j in range(1, n):\n grid[i][j] += min(grid[i-1][j], grid[i][j-1])\n \n return grid[-1][-1]\n \n # An Upvote will be encouraging\n\n```\n```Java []\nclass Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n \n for (int i = 1; i < m; i++) {\n grid[i][0] += grid[i-1][0];\n }\n \n for (int j = 1; j < n; j++) {\n grid[0][j] += grid[0][j-1];\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);\n }\n }\n \n return grid[m-1][n-1];\n }\n}\n\n\n```\n```C++ []\nclass Solution {\npublic:\n int minPathSum(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n \n for (int i = 1; i < m; i++) {\n grid[i][0] += grid[i-1][0];\n }\n \n for (int j = 1; j < n; j++) {\n grid[0][j] += grid[0][j-1];\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n grid[i][j] += min(grid[i-1][j], grid[i][j-1]);\n }\n }\n \n return grid[m-1][n-1];\n }\n};\n\n\n```\n\n![image.png]()\n\n# Please UPVOTE \uD83D\uDC4D | 6,205 |
Minimum Path Sum | minimum-path-sum | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. | Array,Dynamic Programming,Matrix | Medium | null | 4,550 | 28 | # Intuition\nTo find the minimum sum path from the top left corner to the bottom right corner of the grid, we can use dynamic programming. We create a dp table to store the minimum sum path to each cell. The value in the (i, j) cell of the dp table represents the minimum sum path from the top left corner to that cell. We can then fill the dp table using the values from the grid.\n\n\n\n# Approach\n- Initialize the dp table with the value of the top left corner of the grid.\n- Fill the first row of the dp table by adding the values in the previous cell and the current cell in the grid.\n- Fill the first column of the dp table by adding the values in the previous cell and the current cell in the grid.\n- Fill the rest of the dp table by taking the minimum of the value above and the value to the left of the current cell in the dp table, and adding the value in the current cell of the grid.\n- Return the value in the bottom right corner of the dp table, which represents the minimum sum path from the top left corner to the bottom right corner of the grid.\n\n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the graph. We visit each node at most once, and perform constant-time operations on each node.\n\n- Space complexity: O(n), where n is the number of nodes in the graph. We use an array of size n to keep track of the time at which we visit each node.\n\n<!-- Add your space complexity here, e.g. $$O(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 public int minPathSum(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n \n // Create a dp table to store the minimum sum path to each cell\n int[][] dp = new int[m][n];\n dp[0][0] = grid[0][0];\n \n // Fill the first row\n for (int i = 1; i < n; i++) {\n dp[0][i] = dp[0][i-1] + grid[0][i];\n }\n \n // Fill the first column\n for (int i = 1; i < m; i++) {\n dp[i][0] = dp[i-1][0] + grid[i][0];\n }\n \n // Fill the rest of the dp table\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];\n }\n }\n \n return dp[m-1][n-1];\n }\n}\n\n\n```\n``` C++ []\nclass Solution {\npublic:\n int minPathSum(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n \n // Create a dp table to store the minimum sum path to each cell\n vector<vector<int>> dp(m, vector<int>(n));\n \n // Fill the first row\n dp[0][0] = grid[0][0];\n for (int i = 1; i < n; i++) {\n dp[0][i] = dp[0][i-1] + grid[0][i];\n }\n \n // Fill the first column\n for (int i = 1; i < m; i++) {\n dp[i][0] = dp[i-1][0] + grid[i][0];\n }\n \n // Fill the rest of the dp table\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];\n }\n }\n \n return dp[m-1][n-1];\n }\n};\n\n\n```\n``` Python []\nclass Solution(object):\n def minPathSum(self, grid):\n m = len(grid)\n n = len(grid[0])\n \n # Create a dp table to store the minimum sum path to each cell\n dp = [[0 for j in range(n)] for i in range(m)]\n \n # Fill the first row\n dp[0][0] = grid[0][0]\n for i in range(1, n):\n dp[0][i] = dp[0][i-1] + grid[0][i]\n \n # Fill the first column\n for i in range(1, m):\n dp[i][0] = dp[i-1][0] + grid[i][0]\n \n # Fill the rest of the dp table\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]\n \n return dp[m-1][n-1]\n\n\n\n```\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n``` | 6,245 |
Minimum Path Sum | minimum-path-sum | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. | Array,Dynamic Programming,Matrix | Medium | null | 2,070 | 9 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe problem asks to find the minimum sum of a path from the top-left corner to the bottom-right corner of a grid. Since we are only allowed to move right and down, the possible paths we can take are limited. Hence, we can use dynamic programming to solve this problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can create a 2D array `dp` that stores the minimum sum of a path from the top-left corner to the current cell (i, j). We can initialize `dp[0][0]` as the first element of the grid. We can then populate the first row and column of the `dp` array by adding the current element of the grid to the previous element in the row/column.\n\nAfter initializing the first row and column, we can iterate through the rest of the `dp` array and calculate the minimum sum of the path to the current cell (i, j). We can calculate this by taking the minimum of the previous minimum path sum of the cell above (i-1, j) and the cell to the left (i, j-1). We then add the current element of the grid to the minimum sum.\n\nThe minimum sum of the path from the top-left corner to the bottom-right corner of the grid will be stored in `dp[m-1][n-1]`, where `m` and `n` are the dimensions of the grid.\n# Complexity\n- Time complexity: $$O(mn)$$, where m and n are the dimensions of the grid. We iterate through each cell in the `dp` array exactly once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(mn)$$, where m and n are the dimensions of the grid. We create a 2D array of size m x n to store the minimum path sum to each cell.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dp = [[0] * n for _ in range(m)]\n dp[0][0] = grid[0][0]\n for i in range(1, m):\n dp[i][0] = dp[i-1][0] + grid[i][0]\n for j in range(1, n):\n dp[0][j] = dp[0][j-1] + grid[0][j]\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]\n return dp[m-1][n-1]\n``` | 6,259 |
Minimum Path Sum | minimum-path-sum | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. | Array,Dynamic Programming,Matrix | Medium | null | 6,890 | 51 | This code is an implementation of the minimum path sum problem on a 2D grid. The problem requires finding the minimum sum of numbers along a path from the top-left corner to the bottom-right corner of the grid.\n\nThe function takes a 2D list of integers grid as input, which represents the values in the grid. The function uses dynamic programming approach to solve the problem.\n\nFirst, the function determines the dimensions of the grid using the len() function. Then, it iterates over the grid using two nested for loops to check each cell of the grid.\n\nFor each cell, the function checks if it is on the top row or the leftmost column of the grid. If the cell is on the top row, the function adds the value of the cell to the value of the cell immediately to its left. Similarly, if the cell is on the leftmost column, the function adds the value of the cell to the value of the cell immediately above it.\n\nFor all other cells, the function adds the value of the cell to the minimum value of the cells directly above and directly to the left of the current cell.\n\nFinally, the function returns the value in the bottom-right corner of the grid, which represents the minimum path sum.\n![image.png]()\n# Please Upvote \uD83D\uDE07\n\n## Python3\n```\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n n=len(grid)\n m=len(grid[0])\n for i in range(n):\n for j in range(m):\n if i==0:\n if j!=0:\n grid[i][j]+=grid[i][j-1]\n elif j==0:\n if i!=0:\n grid[i][j]+=grid[i-1][j]\n else:\n grid[i][j]+=min(grid[i-1][j],grid[i][j-1])\n return grid[n-1][m-1]\n```\n# C++\n```\nclass Solution {\npublic:\n int minPathSum(vector<vector<int>>& grid) {\n int n=grid.size(),m=grid[0].size();\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(i==0 and j!=0) grid[i][j]+=grid[i][j-1];\n if(j==0 and i!=0) grid[i][j]+=grid[i-1][j];\n if(i!=0 and j!=0) grid[i][j]+=min(grid[i-1][j],grid[i][j-1]);\n }\n }\n return grid[n-1][m-1];\n }\n};\n```\n![image.png]()\n | 6,273 |
Minimum Path Sum | minimum-path-sum | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. | Array,Dynamic Programming,Matrix | Medium | null | 6,663 | 40 | # Video Solution (`Aryan Mittal`)\n`Minimum Path Sum` by `Aryan Mittal`\n![meta5.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![image.png]()\n![image.png]()\n![image.png]()\n\n\n\n# Method1 Code: By Modifying the Grid O(1) Space\n```C++ []\nclass Solution {\npublic:\n int minPathSum(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n \n for (int i = 1; i < m; i++) grid[i][0] += grid[i-1][0];\n \n for (int j = 1; j < n; j++) grid[0][j] += grid[0][j-1];\n \n for (int i = 1; i < m; i++)\n for (int j = 1; j < n; j++)\n grid[i][j] += min(grid[i-1][j], grid[i][j-1]);\n \n return grid[m-1][n-1];\n }\n};\n```\n```Java []\nclass Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n \n for (int i = 1; i < m; i++) grid[i][0] += grid[i-1][0];\n \n for (int j = 1; j < n; j++) grid[0][j] += grid[0][j-1];\n \n for (int i = 1; i < m; i++)\n for (int j = 1; j < n; j++)\n grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);\n \n return grid[m-1][n-1];\n }\n}\n```\n```Python []\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n for i in range(1, m):\n grid[i][0] += grid[i-1][0]\n \n for i in range(1, n):\n grid[0][i] += grid[0][i-1]\n \n for i in range(1, m):\n for j in range(1, n):\n grid[i][j] += min(grid[i-1][j], grid[i][j-1])\n \n return grid[-1][-1]\n```\n\n# Method4 Code: Without Modifying the Grid O(m) Space\n```C++ []\nclass Solution {\npublic:\n int minPathSum(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector<int> cur(m, grid[0][0]);\n \n for (int i = 1; i < m; i++)\n cur[i] = cur[i - 1] + grid[i][0]; \n \n for (int j = 1; j < n; j++) {\n cur[0] += grid[0][j]; \n for (int i = 1; i < m; i++)\n cur[i] = min(cur[i - 1], cur[i]) + grid[i][j];\n }\n return cur[m - 1];\n }\n};\n```\n```Java []\nclass Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n int[] cur = new int[m];\n cur[0] = grid[0][0];\n \n for (int i = 1; i < m; i++)\n cur[i] = cur[i - 1] + grid[i][0];\n \n for (int j = 1; j < n; j++) {\n cur[0] += grid[0][j];\n for (int i = 1; i < m; i++)\n cur[i] = Math.min(cur[i - 1], cur[i]) + grid[i][j];\n }\n return cur[m - 1];\n }\n}\n```\n```Python []\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n cur = [grid[0][0]] * m\n \n for i in range(1, m):\n cur[i] = cur[i - 1] + grid[i][0]\n \n for j in range(1, n):\n cur[0] += grid[0][j]\n for i in range(1, m):\n cur[i] = min(cur[i - 1], cur[i]) + grid[i][j]\n \n return cur[m - 1]\n```\n | 6,282 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 2,135 | 13 | ```C++ []\nclass Solution {\npublic:\n bool isNumber(string s) {\n return is_valid_number(s);\n }\n\nbool is_valid_number(const std::string& s) {\n if (s.empty()) return false;\n\n size_t i = 0;\n if (s[i] == \'+\' || s[i] == \'-\') i++;\n\n bool has_integer_part = false;\n while (i < s.size() && isdigit(s[i])) {\n has_integer_part = true;\n i++;\n }\n\n bool has_decimal_part = false;\n if (i < s.size() && s[i] == \'.\') {\n i++;\n while (i < s.size() && isdigit(s[i])) {\n has_decimal_part = true;\n i++;\n }\n }\n\n if (i < s.size() && (s[i] == \'e\' || s[i] == \'E\')) {\n i++;\n\n if (i < s.size() && (s[i] == \'+\' || s[i] == \'-\')) i++;\n\n if (i == s.size() || !isdigit(s[i])) {\n return false;\n }\n while (i < s.size() && isdigit(s[i])) {\n i++;\n }\n }\n return i == s.size() && (has_integer_part || has_decimal_part);\n}\n};\n```\n\n```Python3 []\nclass Solution:\n r\n def is_uinteger(self, st):\n if st=="": return False\n return set(st).issubset("0123456789")\n def is_integer(self,st):\n if st=="": return False\n if st[0] in "+-":\n return self.is_uinteger(st[1:])\n return self.is_uinteger(st)\n def is_decimal(self,st):\n if st=="": return False\n for c,ss in enumerate(st):\n if ss==".": break \n else: \n return self.is_integer(st) \n left = st[:c]\n right = st[c+1:]\n return (((left in "+-") and self.is_uinteger(right)) or\n ((self.is_integer(left) and (self.is_uinteger(right) or right==""))))\n def isNumber(self, s: str) -> bool:\n for c,ss in enumerate(s):\n if ss in "eE":\n break \n else:\n return self.is_decimal(s) or self.is_integer(s)\n return self.is_decimal(s[:c]) & self.is_integer(s[c+1:])\n```\n\n```Java []\nclass Solution {\n public boolean isNumber(String S) {\n boolean num = false, exp = false, sign = false, dec = false;\n for (int i = 0; i < S.length(); i++) {\n char c = S.charAt(i);\n if (c >= \'0\' && c <= \'9\') num = true ; \n else if (c == \'e\' || c == \'E\')\n if (exp || !num) return false;\n else {\n exp = true;\n sign = false;\n num = false;\n dec = false;\n }\n else if (c == \'+\' || c == \'-\')\n if (sign || num || dec) return false;\n else sign = true;\n else if (c == \'.\')\n if (dec || exp) return false;\n else dec = true;\n else return false;\n }\n return num;\n }\n}\n```\n | 6,306 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 582 | 5 | # Intuition\nUsed try and except method.\n\n# Approach\nSimply used except block when getting error in try block while typecasting string to integer\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def isNumber(self, s: str) -> bool:\n try:\n if s == "inf" or s == "-inf" or s == "+inf" or s =="Infinity" or s == "infinity" or s=="+Infinity" or s == "-Infinity" or s == "+infinity" or s == "-infinity" or s == "nan":\n return 0\n num = float(s)\n return 1\n except:\n return 0\n``` | 6,308 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 4,875 | 67 | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n### ***Idea:***\n\nTo solve this problem, we should should just make a list of the possible error conditions and then check for each one.\n\nThe error conditions are:\n - More than one exponent character (**\'e\'/\'E\'**), or seeing an **\'e\'/\'E\'** when a number has not yet been seen.\n - More than one sign, or a sign appearing after a decimal or number have been seen. This gets reset when passing an **\'e\'/\'E\'**.\n - More than one decimal, or a decimal appearing after an **\'e\'/\'E\'** has been seen.\n - Any other non-number character appearing.\n - Reaching the end of **S** without an active number.\n\nTo help with this process, we can set up some boolean flags for the different things of which we\'re keeping track (**num, exp, sign, dec**). We\'ll also need to remember to reset all flags except **exp** when we find an **\'e\'/\'E\'**, as we\'re starting a new integer expression.\n\n - _**Time Complexity: O(N)** where **N** is the number of characters in **S**_\n - _**Space Complexity: O(1)**_\n\n---\n\n### ***Javascript Code:***\n```javascript\nvar isNumber = function(S) {\n let exp = false, sign = false, num = false, dec = false\n for (let c of S)\n if (c >= \'0\' && c <= \'9\') num = true \n else if (c === \'e\' || c === \'E\')\n if (exp || !num) return false\n else exp = true, sign = false, num = false, dec = false\n else if (c === \'+\' || c === \'-\')\n if (sign || num || dec) return false\n else sign = true\n else if (c === \'.\')\n if (dec || exp) return false\n else dec = true\n else return false\n return num\n};\n```\n\n---\n\n### ***Python Code:***\n```python\nclass Solution:\n def isNumber(self, S: str) -> bool: \n num, exp, sign, dec = False, False, False, False\n for c in S:\n if c >= \'0\' and c <= \'9\': num = True \n elif c == \'e\' or c == \'E\':\n if exp or not num: return False\n else: exp, num, sign, dec = True, False, False, False\n elif c == \'+\' or c == \'-\':\n if sign or num or dec: return False\n else: sign = True\n elif c == \'.\':\n if dec or exp: return False\n else: dec = True\n else: return False\n return num\n```\n\n---\n\n#### ***Java Code:***\n```java\nclass Solution {\n public boolean isNumber(String S) {\n boolean num = false, exp = false, sign = false, dec = false;\n for (int i = 0; i < S.length(); i++) {\n char c = S.charAt(i);\n if (c >= \'0\' && c <= \'9\') num = true ; \n else if (c == \'e\' || c == \'E\')\n if (exp || !num) return false;\n else {\n exp = true;\n sign = false;\n num = false;\n dec = false;\n }\n else if (c == \'+\' || c == \'-\')\n if (sign || num || dec) return false;\n else sign = true;\n else if (c == \'.\')\n if (dec || exp) return false;\n else dec = true;\n else return false;\n }\n return num;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n```c++\nclass Solution {\npublic:\n bool isNumber(string S) {\n bool num = false, exp = false, sign = false, dec = false;\n for (auto c : S)\n if (c >= \'0\' && c <= \'9\') num = true ; \n else if (c == \'e\' || c == \'E\')\n if (exp || !num) return false;\n else exp = true, sign = false, num = false, dec = false;\n else if (c == \'+\' || c == \'-\')\n if (sign || num || dec) return false;\n else sign = true;\n else if (c == \'.\')\n if (dec || exp) return false;\n else dec = true;\n else return false;\n return num;\n }\n};\n``` | 6,313 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 4,874 | 67 | If you want to practice regex, regex101.com is a good site\n```\nclass Solution:\n def isNumber(self, s: str) -> bool:\n\t\t#Example: +- 1 or 1. or 1.2 or .2 e or E +- 1 \n engine = re.compile(r"^[+-]?((\\d+\\.?\\d*)|(\\d*\\.?\\d+))([eE][+-]?\\d+)?$")\n return engine.match(s.strip(" ")) # i prefer this over putting more things (\\S*) in regex\n```\nPlease leave a like if you find this helpful.\n\nAs @nwiger pointed out, the new testcase consists of "E" as well, so it should be `"^[+-]?((\\d+\\.?\\d*)|(\\d*\\.?\\d+))([eE][+-]?\\d+)?$"` (extra `E`)\n\nThanks,\nJummyEgg | 6,320 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 1,189 | 5 | ```\nclass Solution:\n r"""\n Idea: split the input by the e or E and follow the validation rule"""\n def is_uinteger(self, st):\n if st=="": return False\n return set(st).issubset("0123456789")\n def is_integer(self,st):\n if st=="": return False\n if st[0] in "+-":\n return self.is_uinteger(st[1:])\n return self.is_uinteger(st)\n def is_decimal(self,st):\n if st=="": return False\n for c,ss in enumerate(st):\n if ss==".": break \n else: \n return self.is_integer(st) \n left = st[:c]\n right = st[c+1:]\n # first operand : rule 1 and 2.3 \n # second operand: rule 2.1 and 2.2\n return (((left in "+-") and self.is_uinteger(right)) or\n ((self.is_integer(left) and (self.is_uinteger(right) or right==""))))\n \n def isNumber(self, s: str) -> bool:\n for c,ss in enumerate(s):\n if ss in "eE":\n break \n else:\n return self.is_decimal(s) or self.is_integer(s)\n return self.is_decimal(s[:c]) & self.is_integer(s[c+1:])\n```\nPlease upvote :) | 6,327 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 11,254 | 56 | def isNumber(self, s):\n\n try: float(s)\n except ValueError: return False\n else: return True\n\nEasy Peasy :) | 6,347 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 834 | 11 | This solution is based on [this thread]() which is by far the most inspirational solution that I\'ve found on LC. Please upvote that thread if you like this implementation. \n\n```\nclass Solution:\n def isNumber(self, s: str) -> bool:\n dfa = [{\'space\': 0, \'sign\': 1, \'digit\': 2, \'.\': 3}, #state 0 - leading space\n {\'digit\': 2, \'.\': 3}, #state 1 - sign\n {\'digit\': 2, \'.\': 4, \'e\': 5, \'space\': 8}, #state 2 - digit (terminal)\n {\'digit\': 4}, #state 3 - dot\n {\'digit\': 4, \'e\': 5, \'space\': 8}, #state 4 - digit post dot (terminal)\n {\'sign\': 6, \'digit\': 7}, #state 5 - exponential \n {\'digit\': 7}, #state 6 - sign post exponential \n {\'digit\': 7, \'space\': 8}, #state 7 - digit post exponential (terminal)\n {\'space\': 8} #state 8 - trailing space (terminal)\n ]\n \n state = 0\n for c in s.lower(): \n if c in "0123456789": c = "digit"\n elif c == " ": c = "space"\n elif c in "+-": c = "sign"\n if c not in dfa[state]: return False \n state = dfa[state][c]\n return state in [2, 4, 7, 8]\n``` | 6,377 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 602 | 8 | Simply use regex to check.\n* first character is -, +, or nothing: ```^[\\-\\+]?```\n* then: ```([0-9]+([\\.][0-9]*)?|[\\.][0-9]+)```\n * one or more digits, then maybe a decimal point and zero or more digits ```[0-9]+([\\.][0-9]*)?``` OR\n * no leading digit before the decimal point, but must have at least one digit after ```[\\.][0-9]+```\n* lastly, we may have an exponent: ```([e][\\-\\+]?[0-9]+)?$```\n * starts with e: ```[e]```\n * then may have a sign: ```[\\-\\+]?```\n * then one or more digits: ```[0-9]+```\n```\nimport re\nclass Solution:\n def isNumber(self, s: str) -> bool:\n return re.match(r\'^[\\-\\+]?([0-9]+([\\.][0-9]*)?|[\\.][0-9]+)([e][\\-\\+]?[0-9]+)?$\', s.strip()) is not None\n``` | 6,385 |
Valid Number | valid-number | A valid number can be split up into these components (in order): A decimal number can be split up into these components (in order): An integer can be split up into these components (in order): For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"], while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]. Given a string s, return true if s is a valid number. | String | Hard | null | 1,102 | 8 | Using try and except block in the question makes it extremely simple to handle.\nBasically, **just return True if float of the string exists, else the compiler will throw an error which will be caught by the except block, where we can return False.**\n```\nclass Solution:\n def isNumber(self, s: str) -> bool:\n try:\n if \'inf\' in s.lower() or s.isalpha():\n return False\n if float(s) or float(s) >= 0:\n return True\n except:\n return False\n```\nTime Complexity: O(n) where n -> Length of the string\nSpace Complexity: O(1) | 6,389 |
Plus One | plus-one | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. | Array,Math | Easy | null | 6,520 | 38 | # Your upvote is my motivation!\n\n# Code\n# Approach 1 (Array) -> 98.30 % beats\n```\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n\n for i in range(len(digits)-1, -1, -1):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[i] = digits[i] + 1\n return digits\n return [1] + digits \n\n \n```\n\n# Approach 2 (Convert list -> Number :: -> Addition +1 :: -> Number -> List\n```\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n # List -> Number\n n = 0\n for ele in digits:\n n = (n*10) + ele\n \n n = n+1\n \n # Number -> List\n digits = []\n while n > 0:\n digits.insert(0, n % 10) \n n //= 10 \n return digits\n``` | 6,411 |
Plus One | plus-one | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. | Array,Math | Easy | null | 4,776 | 27 | # Code\n```\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n\n for i in range(len(digits)-1,-1,-1):\n if digits[i]==9:\n digits[i]=0\n else:\n digits[i]+=1\n return digits\n return [1]+digits\n``` | 6,444 |
Plus One | plus-one | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. | Array,Math | Easy | null | 18,521 | 40 | # Intuition\nOften the obvious approach is among the best. If you just convert to an integer and add one, it beats 98% of solutions.\n\n# Approach\nInstead of looping across the list and accounting for random 9s, just convert to an integer and add one. Then convert back to a list.\n\n# Complexity\nThe time complexity is O(n) because we have to traverse the list exactly once then convert back to a list.\n\n# Code\n```\nclass Solution:\n def plusOne(self, digits):\n strings = ""\n for number in digits:\n strings += str(number)\n\n temp = str(int(strings) +1)\n\n return [int(temp[i]) for i in range(len(temp))]\n\n\n``` | 6,460 |
Plus One | plus-one | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. | Array,Math | Easy | null | 555 | 6 | # Intuition\nUsing Iteration form n-1 to 0\n\nWe have to add 1 in given digit ( given array ) , so we simple iterate form last index (n-1) to first index (0) and will check if we add (+1) or not , ( (if(digits[i] == 9)) if current element is 9 then we can\'t add directly )\n\nif not (means digits[i] == 9 ) then we make current element 0 (digits[i] = 0) and move to its previous element and we perform this step until we reach to element which is less then 9 , if we reach to (0) index and it is still (digits[0] == 9 , means all element of array is 9 [9,9,9,9,9,9] ) then at the end we insert new element (1) at zero index [1,0,0,0,0,0,0]\n digits.insert(0 , 1)\n return digits\n\nif (digits[i] != 9) then add 1 ,and after adding we break the loop \n digits[i] = digits[i] + 1\n return digits\n\nTime Complexity is O(N) and Space Complexity is O(1)\n\n\n\n\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n\n* If this was helpful, please upvote so that others can see this solution too.\n\n# Code\n```\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n n = len(digits)\n\n for i in range(n-1 , -1 , -1):\n if(digits[i] == 9):\n digits[i] = 0 \n else:\n digits[i] = digits[i] + 1\n return digits\n \n digits.insert(0 , 1)\n return digits\n``` | 6,470 |
Plus One | plus-one | You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. | Array,Math | Easy | null | 1,319 | 5 | \n\n# Code\n```\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n s= \'\'.join(map(str,digits))\n i=int(s)+1\n li=list(map(int,str(i))) \n return li\n``` | 6,487 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 91,286 | 487 | # Intuition :\n- We have to add two binary numbers (made up of 0\'s and 1\'s) and returns the result in binary.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\n- We start at the right end of each binary number, adding the digits and any carry-over value, and storing the result in a new string. \n- Now we move to the next digit on the left and repeats the process until it has gone through all the digits in both binary numbers.\n- If there is any carry-over value after adding all the digits, append it to the end of the new string. \n- Finally, the new string is reversed and returned as the sum of the two binary numbers.\n<!-- Describe your approach to solving the problem. -->\n# Explanation to Approach :\n- Suppose we want to add two binary numbers - "1010" and "1101". \n- To add these two numbers, we can use the given function as follows:\n- First, we initialize a StringBuilder object to store the sum and two integer variables \'carry\' and \'i\' to keep track of the carry-over value and the current position in the first binary number (a), respectively. \n- We also initialize another integer variable \'j\' to keep track of the current position in the second binary number (b). Here is how the code initializes these variables:\n```\nStringBuilder sb = new StringBuilder();\nint carry = 0;\nint i = a.length() - 1;\nint j = b.length() - 1;\n\n```\n- Next, we enter a while loop that iterates until we have processed all digits in both binary numbers and there is no more carry-over value left. In each iteration, we add the digits from both numbers at the current position and the carry-over value (if any), and append the result to the StringBuilder object. \n- We also update the carry-over value based on the sum of the digits. Here is the code for this step:\n```\nwhile (i >= 0 || j >= 0 || carry == 1) {\n if (i >= 0) {\n carry += a.charAt(i--) - \'0\';\n }\n if (j >= 0) {\n carry += b.charAt(j--) - \'0\';\n }\n sb.append(carry % 2);\n carry /= 2;\n}\n\n```\n- In each iteration, the current position in each binary number is moved one digit to the left (if there are any digits left to process) by decrementing the value of i and j. \n- If there is a carry-over value from the previous iteration or the addition of the two digits produces a carry-over value, we set the value of \'carry\' to 1; otherwise, we set it to 0. \n- We also append the sum of the digits to the StringBuilder object by computing the remainder of \'carry\' divided by 2 (which is either 0 or 1). \n- Finally, we update the value of \'carry\' by dividing it by 2 (which gives either 0 or 1) so that we can carry over any remaining value to the next iteration.\n- After the while loop completes, we reverse the StringBuilder object and convert it to a string using the toString() method. \n- This gives us the sum of the two binary numbers in binary format. Here is the final code:\n```\nreturn sb.reverse().toString();\n\n```\n# Example : the sum of "1010" and "1101\n```\n 1010\n +1101\n ______\n 10111\n```\n\n# Complexity\n- Time complexity : O(max|a|,|b|)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(max|a|,|b|)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A\n```\n# Codes [C++ |Java |Python3] \n```C++ []\nclass Solution {\n public:\n string addBinary(string a, string b) {\n string ans;\n int carry = 0;\n int i = a.length() - 1;\n int j = b.length() - 1;\n\n while (i >= 0 || j >= 0 || carry) {\n if (i >= 0)\n carry += a[i--] - \'0\';\n if (j >= 0)\n carry += b[j--] - \'0\';\n ans += carry % 2 + \'0\';\n carry /= 2;\n }\n\n reverse(begin(ans), end(ans));\n return ans;\n }\n};\n```\n```Java []\nclass Solution \n{\n public String addBinary(String a, String b) \n {\n StringBuilder sb = new StringBuilder();\n int carry = 0;\n int i = a.length() - 1;\n int j = b.length() - 1;\n\n while (i >= 0 || j >= 0 || carry == 1) \n {\n if(i >= 0)\n carry += a.charAt(i--) - \'0\';\n if(j >= 0)\n carry += b.charAt(j--) - \'0\';\n sb.append(carry % 2);\n carry /= 2;\n }\n return sb.reverse().toString();\n }\n}\n```\n```Python3 []\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n s = []\n carry = 0\n i = len(a) - 1\n j = len(b) - 1\n\n while i >= 0 or j >= 0 or carry:\n if i >= 0:\n carry += int(a[i])\n i -= 1\n if j >= 0:\n carry += int(b[j])\n j -= 1\n s.append(str(carry % 2))\n carry //= 2\n\n return \'\'.join(reversed(s))\n```\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n![ezgif-3-22a360561c.gif]()\n\n | 6,501 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 91,496 | 841 | ```\n\t\t\t\t\t\t\t\t\t\t\t\t\t# IMPORTANT INFO FOR YOU\n```\n* If, you are preperaing for `FACEBOOK interview` or will prepare. Then according to `LeetCode premium` it is no.4 most asked Question by **Facebook** as per now.\n\n**So Ladies n Gentlemen without any further due let\'s start,**\n`What question saying is, Given two binary strings a and b, return their sum as a binary string.`\n\n**Approach Explained :**\n\n**Summary of Below Explanation :**\n\n*The overall idea is to make up the short two strings with 00 to make the two strings have the same length, and then traverse and calculate from the end to get the final result.*\n\nLet\'s understand with an **example** : Addition of **1 and 1** will lead to **carry 1** and **print 0** , Addition of **1 and 0** give us **1 as carry** will lead **print 0** , Addition of last remaning **carry 1** with no body will lead to **print 1** , So, we get something like **"1 0 0"** as answer\nOne **key point** total addition will be 3 then print 1 and carry will remain 1\n\n**Detailed Explaination :**\n\nSo, first do we understand how do we perform **binary addition**. **Take an example**, given two numbers **"11" + "1"** where **"11"** is representing **"3"** & **"1"** is **"1"**, in decimal form. \nNow let\'s perform **binary addition** it\'s very **similar to the decimal addition** that we do. In decimal what we do we add 2 numbers & if it goes beyond 9 we **take a carry**. And here also we have a **number in range 0 - 1**, **2 values over here** & in **Decimal range is 0 - 9**, **10 values** are there. So, in binary what it means is if result more **than 1**, there **is a carry** otherwise **no carry**.\nLet me show you in diagram:\n![image]()\n\n\n* So, what\'s going in diagram is **intially carry is "0"** we **add 1 + 1** we **get 2** which is more **then 1**, so there is a **carry of 1** and **result is 0**. Now we have **carry of 1**, **again 1 + 1 is 0**, and still left with **carry of 1**. And the **last carry** one will be **return as it is**. \n* So, if you see this binary number it is **[2^2 * 1 + 2^1 * 0 + 2^0 * 0]** and this is the decimal coversion of **[1 0 0]** which **is 4**. \n\n![image]()\n\n**Hope you got the point **\n\n*Now, let\'s code it up:*\n**code, each lne explained :** `Similar for C++, Java, Python` **{Only synatx difference}** approach is same\n\n* Step 1:\n```\n{\n// First, create result name string and intially it is empty & in the end we gonna return it as our aswer\n StringBuilder res = new StringBuilder(); \n int i = a.length() - 1; // we crete i pointer for string a and we have to start adding from right to left \n int j = b.length() - 1; // similar pointer j for string b\n int carry = 0; // we create a carry, as we have to consider it as well\n```\n* Step 2:\n```\n// iterate over the loop until the both condition become false\n while(i >= 0 || j >= 0){ \n int sum = carry; // intialise our sum with carry;\n \n // Now, we subtract by \'0\' to convert the numbers from a char type into an int, so we can perform operations on the numbers\n if(i >= 0) sum += a.charAt(i--) - \'0\';\n if(j >= 0) sum += b.charAt(j--) - \'0\';\n // taking carry;\n carry = sum > 1 ? 1 : 0; // getting carry depend on the quotient we get by dividing sum / 2 that will be our carry. Carry could be either 1 or 0 \n\t\t\t// if sum is 0 res is 1 & then carry would be 0;\n // if sum is 1 res is 1 & carry would be 0\n // if sum is 2 res is 0 & carry would be 1\n // if sum is 3 res is 1 & carry would be 1\n res.append(sum % 2); // just moduling the sum so, we can get remainder and add it into our result\n }\n```\n* Final Step:\n```\nif(carry != 0) res.append(carry); // we gonna add it into res until carry becomes 0;\n return res.reverse().toString(); // revese the answer we get & convt to string and return by the help of result;\n```\n* Let\'s combine each line of code\n\n\n**Java**\n```\nclass Solution {\n public String addBinary(String a, String b) {\n StringBuilder res = new StringBuilder();\n int i = a.length() - 1;\n int j = b.length() - 1;\n int carry = 0;\n while(i >= 0 || j >= 0){\n int sum = carry;\n if(i >= 0) sum += a.charAt(i--) - \'0\';\n if(j >= 0) sum += b.charAt(j--) - \'0\';\n carry = sum > 1 ? 1 : 0;\n res.append(sum % 2);\n }\n if(carry != 0) res.append(carry);\n return res.reverse().toString();\n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n string addBinary(string a, string b) {\n string res;\n int i = a.length() - 1;\n int j = b.length() - 1;\n int carry = 0;\n while(i >= 0 || j >= 0){\n int sum = carry;\n if(i >= 0) sum += a[i--] - \'0\';\n if(j >= 0) sum += b[j--] - \'0\';\n carry = sum > 1 ? 1 : 0;\n res += to_string(sum % 2);\n }\n if(carry) res += to_string(carry);\n reverse(res.begin(), res.end());\n return res;\n }\n};\n```\n**Python**\n```\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n res = ""\n i, j, carry = len(a) - 1, len(b) - 1, 0\n while i >= 0 or j >= 0:\n sum = carry;\n if i >= 0 : sum += ord(a[i]) - ord(\'0\') # ord is use to get value of ASCII character\n if j >= 0 : sum += ord(b[j]) - ord(\'0\')\n i, j = i - 1, j - 1\n carry = 1 if sum > 1 else 0;\n res += str(sum % 2)\n\n if carry != 0 : res += str(carry);\n return res[::-1]\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(max(M, N)), M & N is the length of string a, b;\n\n* **Space Complexity :-** BigO(max(M, N)), which is the size of "res" object\n\n**Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F**\n`If you have some \uD83E\uDD14 doubts feel free to bug me` | 6,502 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 22,980 | 85 | # Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n# Intuition\nLet\'s understand with an example : Addition of 1 and 1 will lead to carry 1 and print 0 , Addition of 1 and 0 give us 1 as carry will lead print 0 , Addition of last remaning carry 1 with no body will lead to print 1 , So, we get something like "1 0 0" as answer\nOne key point total addition will be 3 then print 1 and carry will remain 1.\n\n**Adding 2 binary bits :**\n 0 + 0 = 0\n 1 + 0 = 1\n 0 + 1 = 1\n 1 + 1 = 10\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n**Example :**\n- So, what\'s going in diagram is intially **carry is "0"** we **add 1 + 1** we **get 2** which is **more then 1**, so there is a **carry of 1 and result is 0**. Now we have **carry of 1, again 1 + 1 is 0**, and **still left with carry of 1**. And the last carry one will be **return as it is**.\n- So, if you see this binary number it is **[2^2 * 1 + 2^1 * 0 + 2^0 * 0]** and this is the decimal coversion of **[1 0 0] which is 4.**\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(max(n, m))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(max(n, m))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Consider\uD83D\uDC4D\n Thanks for visiting\uD83D\uDE0A\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to add two binary numbers represented as strings\n string addBinary(string a, string b) {\n // Initialize two pointers to traverse the binary strings from right to left\n int i = a.length()-1;\n int j = b.length()-1;\n string ans;\n int carry = 0;\n \n // Loop until both pointers have reached the beginning of their respective strings and there is no carry-over value left\n while(i >= 0 || j >= 0 || carry) {\n // Add the current binary digit in string a, if the pointer is still within bounds\n if(i >= 0) {\n carry += a[i] - \'0\';\n i--;\n }\n \n // Add the current binary digit in string b, if the pointer is still within bounds\n if(j >= 0) {\n carry += b[j] - \'0\';\n j--;\n }\n \n // Calculate the next binary digit in the result by taking the remainder of the sum divided by 2\n ans += (carry % 2 + \'0\');\n \n // Calculate the next carry-over value by dividing the sum by 2\n carry = carry / 2;\n }\n \n // Reverse the result and return it as a string\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n\n```\n```python []\nclass Solution:\n \n # Function to add two binary numbers represented as strings\n def addBinary(self, a, b):\n # List to store the result\n result = []\n # Variable to store the carry-over value\n carry = 0\n \n # Initialize two pointers to traverse the binary strings from right to left\n i, j = len(a)-1, len(b)-1\n \n # Loop until both pointers have reached the beginning of their respective strings and there is no carry-over value left\n while i >= 0 or j >= 0 or carry:\n total = carry\n \n # Add the current binary digit in string a, if the pointer is still within bounds\n if i >= 0:\n total += int(a[i])\n i -= 1\n \n # Add the current binary digit in string b, if the pointer is still within bounds\n if j >= 0:\n total += int(b[j])\n j -= 1\n \n # Calculate the next binary digit in the result by taking the remainder of the sum divided by 2\n result.append(str(total % 2))\n \n # Calculate the next carry-over value by dividing the sum by 2\n carry = total // 2\n \n # Reverse the result and join the elements to form a single string\n return \'\'.join(reversed(result))\n\n```\n```Java []\nclass Solution {\n // Function to add two binary numbers represented as strings\n public String addBinary(String a, String b) {\n // Initialize two pointers to traverse the binary strings from right to left\n int i = a.length() - 1;\n int j = b.length() - 1;\n StringBuilder ans = new StringBuilder();\n int carry = 0;\n \n // Loop until both pointers have reached the beginning of their respective strings and there is no carry-over value left\n while (i >= 0 || j >= 0 || carry != 0) {\n // Add the current binary digit in string a, if the pointer is still within bounds\n if (i >= 0) {\n carry += a.charAt(i) - \'0\';\n i--;\n }\n \n // Add the current binary digit in string b, if the pointer is still within bounds\n if (j >= 0) {\n carry += b.charAt(j) - \'0\';\n j--;\n }\n \n // Calculate the next binary digit in the result by taking the remainder of the sum divided by 2\n ans.append(carry % 2);\n \n // Calculate the next carry-over value by dividing the sum by 2\n carry = carry / 2;\n }\n \n // Reverse the result and return it as a string\n return ans.reverse().toString();\n }\n}\n\n```\n\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin]() | 6,523 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 42,258 | 344 | ```\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n carry = 0\n result = \'\'\n\n a = list(a)\n b = list(b)\n\n while a or b or carry:\n if a:\n carry += int(a.pop())\n if b:\n carry += int(b.pop())\n\n result += str(carry %2)\n carry //= 2\n\n return result[::-1]\n``` | 6,534 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 4,018 | 13 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis code is a simple implementation of converting binary numbers to integers, adding them, and then converting the sum back to binary. The conversion of binary to integer is done using the int() method with a base of 2, which means that it will treat the string as a binary number and return the equivalent integer. After adding the integers,\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n return bin(int(a , 2) + int(b,2))[2:]\n``` | 6,547 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 1,261 | 6 | \n\n# Code\n```\nclass Solution:\n def addBinary(self, a: str, b: str) -> str:\n res = str(bin(int(a, 2) + int(b, 2)))\n return res[2:]\n \n\n\n``` | 6,579 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 5,301 | 16 | # Intuition:\nThe problem is to add two binary numbers represented as strings, i.e., "101" + "110" should give "1011". We can start by aligning the two binary numbers by adding leading zeros to the shorter string so that both strings have equal lengths. Then we can add the digits from right to left and keep track of any carry generated. Finally, we add the carry to the leftmost position if any.\n\n# Approach:\n1. Calculate the lengths of the two input strings.\n2. If the length of string a is greater than that of string b, add leading zeros to string b to make its length equal to that of string a. Otherwise, add leading zeros to string a to make its length equal to that of string b.\n3. Initialize carry to 0 and an empty string ans.\n4. Traverse the two input strings from right to left, one character at a time.\n5. For each character, add its value with the corresponding character from the other string and the carry.\n6. Determine the value of the current bit and the carry generated.\n7. Add the current bit to the left end of the ans string.\n8. Finally, if there is any carry left, add it to the leftmost position of the ans string.\n9. Return the ans string.\n\n# Complexity:\n- Time Complexity: The algorithm has a time complexity of O(N), where N is the length of the longer input string. This is because we traverse the input strings once from right to left, which takes O(N) time. \n- Space Complexity: The algorithm has a space complexity of O(N), where N is the length of the longer input string. This is because we store the result in an ans string which can have a maximum length of N+1.\n\n---\n# C++\n```\nclass Solution {\npublic:\n string addBinary(string a, string b) {\n int l1=a.length();\n int l2=b.length();\n if(a.length()>b.length()){\n int diff=(a.length()-b.length());\n for(int i=0;i<diff;i++){\n b="0"+b;\n }\n }\n if(a.length()<b.length()){\n int diff=(b.length()-a.length());\n for(int i=0;i<diff;i++){\n a="0"+a;\n }\n }\n int carry=0;\n string ans="";\n for(int i=a.length()-1;i>=0;i--){\n cout<<a[i]<<"+"<<b[i]<<"+"<<carry<<endl;\n if(a[i]==\'0\' && b[i]==\'0\' && carry==0){\n ans="0"+ans;\n }\n else if(a[i]==\'0\' && b[i]==\'0\' && carry==1){\n ans="1"+ans;\n carry=0;\n }\n else if(a[i]==\'0\' && b[i]==\'1\' && carry==1){\n ans="0"+ans;\n carry=1;\n }\n else if(a[i]==\'1\' && b[i]==\'0\' && carry==1){\n ans="0"+ans;\n carry=1;\n }\n else if(a[i]==\'1\' && b[i]==\'0\' && carry==0){\n ans="1"+ans;\n carry=0;\n }\n else if(a[i]==\'1\' && b[i]==\'1\' && carry==1){\n ans="1"+ans;\n carry=1;\n }\n else if(a[i]==\'1\' && b[i]==\'1\' && carry==0){\n ans="0"+ans;\n carry=1;\n }\n else if(a[i]==\'0\' && b[i]==\'1\' && carry==0){\n ans="1"+ans;\n carry=0;\n }\n }\n if(carry==1){\n ans="1"+ans;\n }\n return ans;\n }\n};\n```\n\n---\n\n# JAVA\n```\nclass Solution {\n public String addBinary(String a, String b) {\n int l1 = a.length();\n int l2 = b.length();\n if (a.length() > b.length()) {\n int diff = a.length() - b.length();\n for (int i = 0; i < diff; i++) {\n b = "0" + b;\n }\n }\n if (a.length() < b.length()) {\n int diff = b.length() - a.length();\n for (int i = 0; i < diff; i++) {\n a = "0" + a;\n }\n }\n int carry = 0;\n String ans = "";\n for (int i = a.length() - 1; i >= 0; i--) {\n if (a.charAt(i) == \'0\' && b.charAt(i) == \'0\' && carry == 0) {\n ans = "0" + ans;\n } else if (a.charAt(i) == \'0\' && b.charAt(i) == \'0\' && carry == 1) {\n ans = "1" + ans;\n carry = 0;\n } else if (a.charAt(i) == \'0\' && b.charAt(i) == \'1\' && carry == 1) {\n ans = "0" + ans;\n carry = 1;\n } else if (a.charAt(i) == \'1\' && b.charAt(i) == \'0\' && carry == 1) {\n ans = "0" + ans;\n carry = 1;\n } else if (a.charAt(i) == \'1\' && b.charAt(i) == \'0\' && carry == 0) {\n ans = "1" + ans;\n carry = 0;\n } else if (a.charAt(i) == \'1\' && b.charAt(i) == \'1\' && carry == 1) {\n ans = "1" + ans;\n carry = 1;\n } else if (a.charAt(i) == \'1\' && b.charAt(i) == \'1\' && carry == 0) {\n ans = "0" + ans;\n carry = 1;\n } else if (a.charAt(i) == \'0\' && b.charAt(i) == \'1\' && carry == 0) {\n ans = "1" + ans;\n carry = 0;\n }\n }\n if (carry == 1) {\n ans = "1" + ans;\n }\n return ans;\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def addBinary(self, a, b):\n l1 = len(a)\n l2 = len(b)\n if len(a) > len(b):\n diff = len(a) - len(b)\n for i in range(diff):\n b = "0" + b\n if len(a) < len(b):\n diff = len(b) - len(a)\n for i in range(diff):\n a = "0" + a\n carry = 0\n ans = ""\n for i in range(len(a) - 1, -1, -1):\n if a[i] == \'0\' and b[i] == \'0\' and carry == 0:\n ans = "0" + ans\n elif a[i] == \'0\' and b[i] == \'0\' and carry == 1:\n ans = "1" + ans\n carry = 0\n elif a[i] == \'0\' and b[i] == \'1\' and carry == 1:\n ans = "0" + ans\n carry = 1\n elif a[i] == \'1\' and b[i] == \'0\' and carry == 1:\n ans = "0" + ans\n carry = 1\n elif a[i] == \'1\' and b[i] == \'0\' and carry == 0:\n ans = "1" + ans\n carry = 0\n elif a[i] == \'1\' and b[i] == \'1\' and carry == 1:\n ans = "1" + ans\n carry = 1\n elif a[i] == \'1\' and b[i] == \'1\' and carry == 0:\n ans = "0" + ans\n carry = 1\n elif a[i] == \'0\' and b[i] == \'1\' and carry == 0:\n ans = "1" + ans\n carry = 0\n if carry == 1:\n ans = "1" + ans\n return ans\n\n```\n\n---\n\n# JavaScript\n```\nvar addBinary = function(a, b) {\n let l1 = a.length;\n let l2 = b.length;\n if (a.length > b.length) {\n let diff = a.length - b.length;\n for (let i = 0; i < diff; i++) {\n b = "0" + b;\n }\n }\n if (a.length < b.length) {\n let diff = b.length - a.length;\n for (let i = 0; i < diff; i++) {\n a = "0" + a;\n }\n }\n let carry = 0;\n let ans = "";\n for (let i = a.length - 1; i >= 0; i--) {\n if (a[i] === \'0\' && b[i] === \'0\' && carry === 0) {\n ans = "0" + ans;\n } else if (a[i] === \'0\' && b[i] === \'0\' && carry === 1) {\n ans = "1" + ans;\n carry = 0;\n } else if (a[i] === \'0\' && b[i] === \'1\' && carry === 1) {\n ans = "0" + ans;\n carry = 1;\n } else if (a[i] === \'1\' && b[i] === \'0\' && carry === 1) {\n ans = "0" + ans;\n carry = 1;\n } else if (a[i] === \'1\' && b[i] === \'0\' && carry === 0) {\n ans = "1" + ans;\n carry = 0;\n } else if (a[i] === \'1\' && b[i] === \'1\' && carry === 1) {\n ans = "1" + ans;\n carry = 1;\n } else if (a[i] === \'1\' && b[i] === \'1\' && carry === 0) {\n ans = "0" + ans;\n carry = 1;\n } else if (a[i] === \'0\' && b[i] === \'1\' && carry === 0) {\n ans = "1" + ans;\n carry = 0;\n }\n }\n if (carry === 1) {\n ans = "1" + ans;\n }\n return ans; \n};\n``` | 6,580 |
Add Binary | add-binary | Given two binary strings a and b, return their sum as a binary string. | Math,String,Bit Manipulation,Simulation | Easy | null | 2,228 | 6 | Firstly we convert string into int using python function.\nThen add both the numbers.\nAt last Converting back int to string and returning them.\n\n```\n def addBinary(self, a, b):\n x,y = int(a,2) , int (b,2)\n return str(bin(x+y).replace("0b",""))\n``` | 6,597 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 11,254 | 65 | # Interview Problem Understanding\n\nIn interviews, understanding the problem at hand is half the battle. Let\'s break down the "Text Justification" challenge:\n\n**The Scenario**: Imagine you\'re building a word processor, and you need to implement the "Justify" alignment feature. This means that when a user selects a group of words and chooses the "Justify" option, the text is adjusted so that each line spans the entire width of the available space. Words are spaced out, and additional spaces are added between them to achieve this uniform width.\n\n**The Challenge**: Given an array of strings (or words) and a defined maximum width for each line:\n- Your task is to format the text such that each line is exactly the specified maximum width.\n- Each line should be both left and right justified. This means the words on each line are separated by one or more spaces to ensure the line extends from the very left to the very right.\n- There\'s a catch, though. For lines that aren\'t the last, if the spaces don\'t divide evenly, the leftmost gaps get more spaces. For the very last line or a line with a single word, it should be left-justified, and the extra spaces are added to the end.\n\n**Example**:\nSuppose you\'re given the words `["This", "is", "an", "example", "of", "text", "justification."]` and a `maxWidth` of 16. This means each line of the output can only be 16 characters wide. Your output should resemble:\n\n```\n[\n "This is an",\n "example of text",\n "justification. "\n]\n```\n\n**Input/Output**:\n- **Input**: You\'re provided with an array of words and a maximum width for each line.\n- **Output**: Your goal is to return a list of strings, where each string is a line of text that adheres to the justification rules.\n\n---\n\n# Live Coding + Explenation Modulo-based\n\n\n---\n\n## Approach 1: Modulo-based Space Distribution\n\nTo solve the "Text Justification" problem using this approach, we pack words into each line using a greedy strategy. We then distribute spaces among the words on each line, using modulo arithmetic to decide where to place the extra spaces.\n\n### Key Data Structures:\n- **List**: To store the current words for a line and the result.\n\n### Enhanced Breakdown:\n\n1. **Initialization**:\n - We start by initializing empty lists for the result and the current line words.\n - A counter is also initialized to keep track of the total length of words in the current line.\n \n2. **Processing Each Word**:\n - For each word, we check if adding the next word to the current line would make it exceed the maximum width.\n - If it does, we proceed to justify the current line. This involves distributing spaces among the words. The modulo arithmetic is handy here, ensuring that extra spaces are evenly spread among the words.\n - Once the line is justified, we reset the lists and counter for the next line.\n - A special case is the last line, where we simply left-justify the words.\n\n3. **Wrap-up**:\n - Once all the words are processed and lines are justified, we return the result list.\n\n## Example:\n\nGiven the `words = ["This", "is", "an", "example"]` and `maxWidth = 16`:\n\n- The word "This" is added to the current line.\n- The word "is" is added to the current line.\n- The word "an" is added to the current line, completing it with the string "This is an".\n- The word "example" starts a new line.\n\n---\n\n## Approach 2: Gap-based Space Distribution\n\nIn this method, the way we pack words into each line remains similar to the first approach. However, when it comes to distributing spaces, the logic is a tad different. Instead of using modulo arithmetic directly, we compute the number of gaps between words and then decide how many spaces to put in each gap. This makes the logic more intuitive.\n\n### Key Data Structures:\n- **List**: To store the current words for a line and the result.\n\n### Enhanced Breakdown:\n\n1. **Initialization**:\n - As before, we initialize empty lists for the result and the current line words.\n - A counter keeps track of the total length of words in the current line.\n \n2. **Processing Each Word**:\n - For every word, we check if adding it to the current line would cross the maximum width.\n - If yes, we justify the current line. This time, we compute the total number of spaces required for the current line. This is based on the maximum width and the length of words on the line.\n - We then determine how many gaps exist between the words and compute the number of spaces that can be evenly distributed across these gaps.\n - Any extra spaces that can\'t be evenly distributed are then added to the gaps from left to right.\n - The last line is handled specially, where we left-justify the words.\n\n3. **Wrap-up**:\n - After processing all the words and justifying the lines, we return the result list.\n\n---\n\n# Complexity:\n\n**Time Complexity:** Both approaches process each word once and have a time complexity of $$O(n)$$, where $$n$$ is the number of words.\n\n**Space Complexity:** The space complexity for both methods is $$O(n \\times m)$$, where $$n$$ is the number of words and $$m$$ is the average length of the words.\n\n---\n\n# Performance:\n\n| Language | Runtime (ms) | Memory (MB) |\n|-------------|--------------|-------------|\n| Rust | 1 ms | 2.1 MB |\n| Go | 1 ms | 2.1 MB |\n| Java | 1 ms | 40.7 MB |\n| C++ | 4 ms | 7.6 MB |\n| Python3 (v2)| 34 ms | 16.3 MB |\n| Python3 (v1)| 34 ms | 16.1 MB |\n| JavaScript | 55 ms | 42.2 MB |\n| C# | 139 ms | 43.7 MB |\n\n![p2a.png]()\n\n# Code Modulo-based\n``` Python []\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n res, line, width = [], [], 0\n\n for w in words:\n if width + len(w) + len(line) > maxWidth:\n for i in range(maxWidth - width): line[i % (len(line) - 1 or 1)] += \' \'\n res, line, width = res + [\'\'.join(line)], [], 0\n line += [w]\n width += len(w)\n\n return res + [\' \'.join(line).ljust(maxWidth)]\n```\n``` C++ []\nclass Solution {\npublic:\n std::vector<std::string> fullJustify(std::vector<std::string>& words, int maxWidth) {\n std::vector<std::string> res;\n std::vector<std::string> cur;\n int num_of_letters = 0;\n\n for (std::string word : words) {\n if (word.size() + cur.size() + num_of_letters > maxWidth) {\n for (int i = 0; i < maxWidth - num_of_letters; i++) {\n cur[i % (cur.size() - 1 ? cur.size() - 1 : 1)] += \' \';\n }\n res.push_back("");\n for (std::string s : cur) res.back() += s;\n cur.clear();\n num_of_letters = 0;\n }\n cur.push_back(word);\n num_of_letters += word.size();\n }\n\n std::string last_line = "";\n for (std::string s : cur) last_line += s + \' \';\n last_line = last_line.substr(0, last_line.size()-1); // remove trailing space\n while (last_line.size() < maxWidth) last_line += \' \';\n res.push_back(last_line);\n\n return res;\n }\n};\n```\n``` Java []\npublic class Solution {\n public List<String> fullJustify(String[] words, int maxWidth) {\n List<String> res = new ArrayList<>();\n List<String> cur = new ArrayList<>();\n int num_of_letters = 0;\n\n for (String word : words) {\n if (word.length() + cur.size() + num_of_letters > maxWidth) {\n for (int i = 0; i < maxWidth - num_of_letters; i++) {\n cur.set(i % (cur.size() - 1 > 0 ? cur.size() - 1 : 1), cur.get(i % (cur.size() - 1 > 0 ? cur.size() - 1 : 1)) + " ");\n }\n StringBuilder sb = new StringBuilder();\n for (String s : cur) sb.append(s);\n res.add(sb.toString());\n cur.clear();\n num_of_letters = 0;\n }\n cur.add(word);\n num_of_letters += word.length();\n }\n\n StringBuilder lastLine = new StringBuilder();\n for (int i = 0; i < cur.size(); i++) {\n lastLine.append(cur.get(i));\n if (i != cur.size() - 1) lastLine.append(" ");\n }\n while (lastLine.length() < maxWidth) lastLine.append(" ");\n res.add(lastLine.toString());\n\n return res;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string[]} words\n * @param {number} maxWidth\n * @return {string[]}\n */\nvar fullJustify = function(words, maxWidth) {\n let res = [];\n let cur = [];\n let num_of_letters = 0;\n\n for (let word of words) {\n if (word.length + cur.length + num_of_letters > maxWidth) {\n for (let i = 0; i < maxWidth - num_of_letters; i++) {\n cur[i % (cur.length - 1 || 1)] += \' \';\n }\n res.push(cur.join(\'\'));\n cur = [];\n num_of_letters = 0;\n }\n cur.push(word);\n num_of_letters += word.length;\n }\n\n let lastLine = cur.join(\' \');\n while (lastLine.length < maxWidth) lastLine += \' \';\n res.push(lastLine);\n\n return res;\n }\n```\n``` C# []\npublic class Solution {\n public IList<string> FullJustify(string[] words, int maxWidth) {\n var res = new List<string>();\n var cur = new List<string>();\n int num_of_letters = 0;\n\n foreach (var word in words) {\n if (word.Length + cur.Count + num_of_letters > maxWidth) {\n for (int i = 0; i < maxWidth - num_of_letters; i++) {\n cur[i % (cur.Count - 1 > 0 ? cur.Count - 1 : 1)] += " ";\n }\n res.Add(string.Join("", cur));\n cur.Clear();\n num_of_letters = 0;\n }\n cur.Add(word);\n num_of_letters += word.Length;\n }\n\n string lastLine = string.Join(" ", cur);\n while (lastLine.Length < maxWidth) lastLine += " ";\n res.Add(lastLine);\n\n return res;\n }\n}\n```\n``` Go []\nfunc fullJustify(words []string, maxWidth int) []string {\n var res []string\n var cur []string\n num_of_letters := 0\n\n for _, word := range words {\n if len(word) + len(cur) + num_of_letters > maxWidth {\n for i := 0; i < maxWidth - num_of_letters; i++ {\n cur[i % max(1, len(cur) - 1)] += " "\n }\n res = append(res, strings.Join(cur, ""))\n cur = cur[:0]\n num_of_letters = 0\n }\n cur = append(cur, word)\n num_of_letters += len(word)\n }\n\n lastLine := strings.Join(cur, " ")\n for len(lastLine) < maxWidth {\n lastLine += " "\n }\n res = append(res, lastLine)\n\n return res\n}\n\n// Helper function to get the maximum of two integers\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```\n``` Rust []\nimpl Solution {\n pub fn full_justify(words: Vec<String>, max_width: i32) -> Vec<String> {\n let mut res = Vec::new();\n let mut cur = Vec::new();\n let mut num_of_letters: i32 = 0;\n\n for word in &words {\n if word.len() as i32 + cur.len() as i32 + num_of_letters > max_width {\n for i in 0..(max_width - num_of_letters) {\n let idx = i as usize % (if cur.len() > 1 { cur.len() - 1 } else { cur.len() });\n cur[idx] = format!("{} ", cur[idx]);\n }\n res.push(cur.join(""));\n cur.clear();\n num_of_letters = 0;\n }\n cur.push(word.clone());\n num_of_letters += word.len() as i32;\n }\n\n let last_line = cur.join(" ");\n res.push(format!("{:<width$}", last_line, width=max_width as usize));\n\n res\n }\n}\n```\n\n# Code Gap-based\n``` Python []\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n res, cur_words, cur_len = [], [], 0\n\n for word in words:\n if cur_len + len(word) + len(cur_words) > maxWidth:\n total_spaces = maxWidth - cur_len\n gaps = len(cur_words) - 1\n if gaps == 0:\n res.append(cur_words[0] + \' \' * total_spaces)\n else:\n space_per_gap = total_spaces // gaps\n extra_spaces = total_spaces % gaps\n line = \'\'\n for i, w in enumerate(cur_words):\n line += w\n if i < gaps:\n line += \' \' * space_per_gap\n if i < extra_spaces:\n line += \' \'\n res.append(line)\n cur_words, cur_len = [], 0\n cur_words.append(word)\n cur_len += len(word)\n\n last_line = \' \'.join(cur_words)\n remaining_spaces = maxWidth - len(last_line)\n res.append(last_line + \' \' * remaining_spaces)\n\n return res\n\n```\n``` C++ []\nclass Solution {\npublic:\n std::vector<std::string> fullJustify(std::vector<std::string>& words, int maxWidth) {\n std::vector<std::string> res, cur_words;\n int cur_len = 0;\n\n for (const std::string& word : words) {\n if (cur_len + word.length() + cur_words.size() > maxWidth) {\n int total_spaces = maxWidth - cur_len;\n int gaps = cur_words.size() - 1;\n if (gaps == 0) {\n res.push_back(cur_words[0] + std::string(total_spaces, \' \'));\n } else {\n int space_per_gap = total_spaces / gaps;\n int extra_spaces = total_spaces % gaps;\n std::string line = "";\n for (int i = 0; i < cur_words.size(); ++i) {\n line += cur_words[i];\n if (i < gaps) {\n line += std::string(space_per_gap, \' \');\n if (i < extra_spaces) {\n line += \' \';\n }\n }\n }\n res.push_back(line);\n }\n cur_words.clear();\n cur_len = 0;\n }\n cur_words.push_back(word);\n cur_len += word.length();\n }\n\n std::string last_line = "";\n for (const std::string& word : cur_words) {\n if (!last_line.empty()) {\n last_line += \' \';\n }\n last_line += word;\n }\n last_line += std::string(maxWidth - last_line.length(), \' \');\n res.push_back(last_line);\n\n return res;\n }\n};\n```\n``` Java []\npublic class Solution {\n public List<String> fullJustify(String[] words, int maxWidth) {\n List<String> res = new ArrayList<>();\n List<String> curWords = new ArrayList<>();\n int curLen = 0;\n\n for (String word : words) {\n if (curLen + word.length() + curWords.size() > maxWidth) {\n int totalSpaces = maxWidth - curLen;\n int gaps = curWords.size() - 1;\n if (gaps == 0) {\n res.add(curWords.get(0) + " ".repeat(totalSpaces));\n } else {\n int spacePerGap = totalSpaces / gaps;\n int extraSpaces = totalSpaces % gaps;\n StringBuilder line = new StringBuilder();\n for (int i = 0; i < curWords.size(); i++) {\n line.append(curWords.get(i));\n if (i < gaps) {\n line.append(" ".repeat(spacePerGap));\n if (i < extraSpaces) {\n line.append(\' \');\n }\n }\n }\n res.add(line.toString());\n }\n curWords.clear();\n curLen = 0;\n }\n curWords.add(word);\n curLen += word.length();\n }\n\n StringBuilder lastLine = new StringBuilder(String.join(" ", curWords));\n while (lastLine.length() < maxWidth) {\n lastLine.append(\' \');\n }\n res.add(lastLine.toString());\n\n return res;\n }\n}\n```\n``` C# []\npublic class Solution {\n public IList<string> FullJustify(string[] words, int maxWidth) {\n List<string> res = new List<string>();\n List<string> curWords = new List<string>();\n int curLen = 0;\n\n foreach (string word in words) {\n if (curLen + word.Length + curWords.Count > maxWidth) {\n int totalSpaces = maxWidth - curLen;\n int gaps = curWords.Count - 1;\n if (gaps == 0) {\n res.Add(curWords[0] + new string(\' \', totalSpaces));\n } else {\n int spacePerGap = totalSpaces / gaps;\n int extraSpaces = totalSpaces % gaps;\n StringBuilder line = new StringBuilder();\n for (int i = 0; i < curWords.Count; i++) {\n line.Append(curWords[i]);\n if (i < gaps) {\n line.Append(new string(\' \', spacePerGap));\n if (i < extraSpaces) {\n line.Append(\' \');\n }\n }\n }\n res.Add(line.ToString());\n }\n curWords.Clear();\n curLen = 0;\n }\n curWords.Add(word);\n curLen += word.Length;\n }\n\n string lastLine = string.Join(" ", curWords);\n while (lastLine.Length < maxWidth) {\n lastLine += \' \';\n }\n res.Add(lastLine);\n\n return res;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string[]} words\n * @param {number} maxWidth\n * @return {string[]}\n */\nvar fullJustify = function(words, maxWidth) {\n let res = [];\n let curWords = [];\n let curLen = 0;\n\n for (let word of words) {\n if (curLen + word.length + curWords.length > maxWidth) {\n let totalSpaces = maxWidth - curLen;\n let gaps = curWords.length - 1;\n if (gaps === 0) {\n res.push(curWords[0] + \' \'.repeat(totalSpaces));\n } else {\n let spacePerGap = Math.floor(totalSpaces / gaps);\n let extraSpaces = totalSpaces % gaps;\n let line = \'\';\n for (let i = 0; i < curWords.length; i++) {\n line += curWords[i];\n if (i < gaps) {\n line += \' \'.repeat(spacePerGap);\n if (i < extraSpaces) {\n line += \' \';\n }\n }\n }\n res.push(line);\n }\n curWords = [];\n curLen = 0;\n }\n curWords.push(word);\n curLen += word.length;\n }\n\n let lastLine = curWords.join(\' \');\n while (lastLine.length < maxWidth) {\n lastLine += \' \';\n }\n res.push(lastLine);\n\n return res;\n }\n```\n\nThe choice between the two methods will depend on the specific use-case and the preference for clarity vs. conciseness. Both approaches offer an efficient way to tackle the problem of text justification. \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB | 6,643 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 2,006 | 12 | # Intuition\nThe algorithm justifies a given list of words into lines with a specified maximum width. It iterates through the words, adding them to a line if they fit within the width limit, or starts a new line if not. After splitting the text into lines, it evenly distributes extra spaces among words to justify the lines, ensuring the last line is left-justified. The final justified lines are returned as a result.\n\n---\n\n\n# Solution Video\nUsually, I put a video to visualize solution but today I have to go on business trip and come back at late night. Please subscribe to my channel from URL below and don\'t miss my latest solution videos in the future.\n\nI have 247 videos as of August 24th, 2023. Currently there are 2,071 subscribers.\n\n\u25A0 Subscribe URL\n\n\n---\n\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. **Initialization of Variables:**\n - Initialize an empty list `result` to store the final justified lines.\n - Initialize an empty list `line` to temporarily store words for the current line being processed.\n - Initialize an integer variable `line_length` to track the length of words in the current line.\n\n2. **Loop through Words:**\n - Loop through each word in the `words` list.\n - Check if adding the current `word` to the current line would exceed the `maxWidth` for the line.\n - If the addition doesn\'t exceed, append the `word` to the `line` and update the `line_length` accordingly.\n - If the addition exceeds, append the current `line` to the `result`, start a new line with the current `word`, and update `line_length`.\n\n3. **Append Last Line:**\n - Append the last `line` to the `result`.\n\n4. **Initialization for Justified Lines:**\n - Initialize an empty list `justified_lines` to store the lines after justification.\n\n5. **Loop through Lines for Justification:**\n - Loop through each line in `result` except the last one (from 0 to `len(result) - 2`).\n - Get the current `line` from the `result`.\n - Calculate the total number of words in the `line` as `num_words`.\n - Calculate the total number of spaces available for justification as `num_spaces` by subtracting the sum of lengths of words in the line from `maxWidth`.\n\n6. **Handle Zero Space Gaps:**\n - Calculate the number of space gaps (`space_gaps`) by taking the maximum of `num_words - 1` and 1 (to ensure there\'s at least one gap).\n\n7. **Calculate Spaces per Gap:**\n - Calculate the number of spaces per gap (`spaces_per_gap`) by performing integer division `num_spaces // space_gaps`.\n\n8. **Calculate Extra Spaces:**\n - Calculate the remaining extra spaces (`extra_spaces`) after distributing spaces evenly among gaps using modulo `num_spaces % space_gaps`.\n\n9. **Building Justified Line:**\n - Initialize an empty string `justified_line` to build the justified line.\n - Iterate through each `word` in the `line`.\n - Concatenate the `word` to the `justified_line`.\n - Check if there are more spaces to distribute (`space_gaps > 0`).\n - If yes, calculate the number of spaces to add (`spaces_to_add`) by adding `spaces_per_gap` and an extra space if `extra_spaces` is greater than 0.\n - Concatenate the calculated number of spaces to the `justified_line`.\n - Decrement `extra_spaces` and `space_gaps`.\n\n10. **Append Justified Line:**\n - Append the `justified_line` to the `justified_lines` list.\n\n11. **Construct the Last Line:**\n - Join the words in the last `result` line with a single space to form the `last_line`.\n - Add the required number of spaces at the end to make the total length `maxWidth`.\n\n12. **Append Last Line to Justified Lines:**\n - Append the `last_line` to the `justified_lines` list.\n\n13. **Return Justified Lines:**\n - Return the list of `justified_lines`.\n\n```python []\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n result = [] # To store the final justified lines\n line = [] # To temporarily store words for current line\n line_length = 0 # To track the length of the words in the current line\n \n # Loop through each word in the input words list\n for word in words:\n # Check if adding the current word exceeds the maxWidth for the line\n if line_length + len(line) + len(word) <= maxWidth:\n line.append(word) # Add the word to the line\n line_length += len(word) # Update the line length\n else:\n result.append(line) # Add the words in the line to the result\n line = [word] # Start a new line with the current word\n line_length = len(word) # Set the line length to the word\'s length\n \n result.append(line) # Append the last line to the result\n \n justified_lines = []\n \n # Loop through each line except the last one\n for i in range(len(result) - 1):\n line = result[i]\n num_words = len(line)\n num_spaces = maxWidth - sum(len(word) for word in line)\n \n # Handle the case when space_gaps is zero\n space_gaps = max(num_words - 1, 1)\n \n spaces_per_gap = num_spaces // space_gaps\n extra_spaces = num_spaces % space_gaps\n\n justified_line = ""\n \n # Iterate through each word in the line\n for word in line:\n justified_line += word\n \n # Check if there are more spaces to distribute\n if space_gaps > 0:\n spaces_to_add = spaces_per_gap + (1 if extra_spaces > 0 else 0)\n justified_line += " " * spaces_to_add\n extra_spaces -= 1\n space_gaps -= 1\n\n justified_lines.append(justified_line)\n\n last_line = " ".join(result[-1])\n last_line += " " * (maxWidth - len(last_line))\n justified_lines.append(last_line)\n\n return justified_lines\n```\n```javascript []\n/**\n * @param {string[]} words\n * @param {number} maxWidth\n * @return {string[]}\n */\nvar fullJustify = function(words, maxWidth) {\n const result = [];\n let line = [];\n let lineLength = 0;\n\n for (const word of words) {\n if (lineLength + line.length + word.length <= maxWidth) {\n line.push(word);\n lineLength += word.length;\n } else {\n result.push(line);\n line = [word];\n lineLength = word.length;\n }\n }\n\n result.push(line);\n\n const justifiedLines = [];\n for (let i = 0; i < result.length - 1; i++) {\n line = result[i];\n const numWords = line.length;\n const numSpaces = maxWidth - line.reduce((acc, word) => acc + word.length, 0);\n\n let spaceGaps = Math.max(numWords - 1, 1);\n const spacesPerGap = Math.floor(numSpaces / spaceGaps);\n let extraSpaces = numSpaces % spaceGaps;\n\n let justifiedLine = "";\n for (const word of line) {\n justifiedLine += word;\n\n if (spaceGaps > 0) {\n const spacesToAdd = spacesPerGap + (extraSpaces > 0 ? 1 : 0);\n justifiedLine += " ".repeat(spacesToAdd);\n extraSpaces -= 1;\n spaceGaps -= 1;\n }\n }\n\n justifiedLines.push(justifiedLine);\n }\n\n const lastLine = result[result.length - 1].join(" ");\n justifiedLines.push(lastLine + " ".repeat(maxWidth - lastLine.length));\n\n return justifiedLines; \n};\n```\n```java []\nclass Solution {\n public List<String> fullJustify(String[] words, int maxWidth) {\n List<List<String>> result = new ArrayList<>();\n List<String> line = new ArrayList<>();\n int lineLength = 0;\n\n for (String word : words) {\n if (lineLength + line.size() + word.length() <= maxWidth) {\n line.add(word);\n lineLength += word.length();\n } else {\n result.add(line);\n line = new ArrayList<>();\n line.add(word);\n lineLength = word.length();\n }\n }\n\n result.add(line);\n\n List<String> justifiedLines = new ArrayList<>();\n for (int i = 0; i < result.size() - 1; i++) {\n line = result.get(i);\n int numWords = line.size();\n int numSpaces = maxWidth - line.stream().mapToInt(String::length).sum();\n\n int spaceGaps = Math.max(numWords - 1, 1);\n int spacesPerGap = numSpaces / spaceGaps;\n int extraSpaces = numSpaces % spaceGaps;\n\n StringBuilder justifiedLine = new StringBuilder();\n for (String word : line) {\n justifiedLine.append(word);\n\n if (spaceGaps > 0) {\n int spacesToAdd = spacesPerGap + (extraSpaces > 0 ? 1 : 0);\n justifiedLine.append(" ".repeat(spacesToAdd));\n extraSpaces -= 1;\n spaceGaps -= 1;\n }\n }\n\n justifiedLines.add(justifiedLine.toString());\n }\n\n StringBuilder lastLine = new StringBuilder(String.join(" ", result.get(result.size() - 1)));\n lastLine.append(" ".repeat(maxWidth - lastLine.length()));\n justifiedLines.add(lastLine.toString());\n\n return justifiedLines; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<string> fullJustify(vector<string>& words, int maxWidth) {\n std::vector<std::vector<std::string>> result;\n std::vector<std::string> line;\n int lineLength = 0;\n\n for (const std::string& word : words) {\n if (lineLength + line.size() + word.length() <= maxWidth) {\n line.push_back(word);\n lineLength += word.length();\n } else {\n result.push_back(line);\n line.clear();\n line.push_back(word);\n lineLength = word.length();\n }\n }\n\n result.push_back(line);\n\n std::vector<std::string> justifiedLines;\n for (int i = 0; i < result.size() - 1; i++) {\n line = result[i];\n int numWords = line.size();\n int numSpaces = maxWidth;\n for (const std::string& word : line) {\n numSpaces -= word.length();\n }\n\n int spaceGaps = std::max(numWords - 1, 1);\n int spacesPerGap = numSpaces / spaceGaps;\n int extraSpaces = numSpaces % spaceGaps;\n\n std::string justifiedLine = "";\n for (const std::string& word : line) {\n justifiedLine += word;\n\n if (spaceGaps > 0) {\n int spacesToAdd = spacesPerGap + (extraSpaces > 0 ? 1 : 0);\n justifiedLine += std::string(spacesToAdd, \' \');\n extraSpaces -= 1;\n spaceGaps -= 1;\n }\n }\n\n justifiedLines.push_back(justifiedLine);\n }\n\n std::string lastLine = "";\n for (const std::string& word : result[result.size() - 1]) {\n lastLine += word + " ";\n }\n lastLine.pop_back();\n lastLine += std::string(maxWidth - lastLine.length(), \' \');\n justifiedLines.push_back(lastLine);\n\n return justifiedLines; \n }\n};\n```\n | 6,652 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 74,883 | 565 | --------------------------------------------\n\n def fullJustify(self, words, maxWidth):\n res, cur, num_of_letters = [], [], 0\n for w in words:\n if num_of_letters + len(w) + len(cur) > maxWidth:\n for i in range(maxWidth - num_of_letters):\n cur[i%(len(cur)-1 or 1)] += \' \'\n res.append(\'\'.join(cur))\n cur, num_of_letters = [], 0\n cur += [w]\n num_of_letters += len(w)\n return res + [\' \'.join(cur).ljust(maxWidth)]\n\nHow does it work? Well in the question statement, the sentence "Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right" was just a really long and awkward way to say *round robin*. The following line implements the round robin logic: \n\n for i in range(maxWidth - num_of_letters):\n cur[i%(len(cur)-1 or 1)] += \' \'\n\nWhat does this line do? Once you determine that there are only k words that can fit on a given line, you know what the total length of those words is num_of_letters. Then the rest are spaces, and there are (maxWidth - num_of_letters) of spaces. The "or 1" part is for dealing with the edge case len(cur) == 1.\n\n###### Note: I found that this problem & solution is directly being used in the "Elements of Programming Interviews in Python" book. Cool I guess, but the book should include an acknowledgement or link to this source.\n--------------------------------------------\n\nThe following is my older solution for reference, longer and less clear. The idea is the same, but I did not figure out the nice way to distribute the space at the time.\n\n def fullJustify(self, words, maxWidth):\n res, cur, num_of_letters = [], [], 0\n for w in words:\n if num_of_letters + len(w) + len(cur) > maxWidth:\n if len(cur) == 1:\n res.append( cur[0] + \' \'*(maxWidth - num_of_letters) )\n else:\n num_spaces = maxWidth - num_of_letters\n space_between_words, num_extra_spaces = divmod( num_spaces, len(cur)-1)\n for i in range(num_extra_spaces):\n cur[i] += \' \'\n res.append( (\' \'*space_between_words).join(cur) )\n cur, num_of_letters = [], 0\n cur += [w]\n num_of_letters += len(w)\n res.append( \' \'.join(cur) + \' \'*(maxWidth - num_of_letters - len(cur) + 1) )\n return res | 6,654 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 1,035 | 10 | # ANNOUNCEMENT:\n**Join the discord and don\'t forget to Subscribe the youtube channel to access the premium content materials related to computer science and data science in the discord. (For Only first 10,000 Subscribers)**\n\n**Happy Learning, Cheers Guys \uD83D\uDE0A**\n\n# Click the Link in my Profile to Subscribe\n\n# An UPVOTE will be encouraging \uD83D\uDC4D\n\n#Intuition\n\n- Initialize an empty result list to store the justified lines, an empty current line (cur), and a variable to keep track of the total number of letters in the current line (numOfLetters).\n\n- Iterate through the list of words one by one.\n\nFor each word:\n\n- Check if adding the word to the current line would exceed the maximum width. If it would, it\'s time to justify the current line.\n- Calculate the number of spaces that need to be added to distribute them evenly. This is done by finding the difference between the maximum width and the total number of letters in the current line.\n- Distribute these spaces evenly among the words in the current line. The modulo operator is used to ensure that spaces are distributed evenly, even if there are more words than spaces.\n- Add the justified line to the result list.\n- Clear the current line and reset the numOfLetters counter.\n- Continue adding words to the current line until you reach a point where adding the next word would exceed the maximum width.\n\n- For the last line of text, left-justify it by adding spaces between words. Ensure that the total width of the line matches the maximum width.\n\n- Return the list of justified lines as the final result.\n\n```Python []\nclass Solution:\n def fullJustify(self, words, maxWidth):\n result, cur, num_of_letters = [], [], 0\n\n for word in words:\n if num_of_letters + len(word) + len(cur) > maxWidth:\n for i in range(maxWidth - num_of_letters):\n cur[i % (len(cur) - 1 or 1)] += \' \'\n result.append(\'\'.join(cur))\n cur, num_of_letters = [], 0\n\n cur += [word]\n num_of_letters += len(word)\n\n return result + [\' \'.join(cur).ljust(maxWidth)]\n```\n```Java []\n\npublic class TextJustification {\n public List<String> fullJustify(String[] words, int maxWidth) {\n List<String> result = new ArrayList<>();\n List<String> cur = new ArrayList<>();\n int numOfLetters = 0;\n\n for (String word : words) {\n if (numOfLetters + word.length() + cur.size() > maxWidth) {\n int spacesToAdd = maxWidth - numOfLetters;\n for (int i = 0; i < spacesToAdd; i++) {\n cur.set(i % (cur.size() - 1), cur.get(i % (cur.size() - 1)) + " ");\n }\n result.add(String.join("", cur));\n cur.clear();\n numOfLetters = 0;\n }\n\n cur.add(word);\n numOfLetters += word.length();\n }\n\n result.add(String.join(" ", cur) + " ".repeat(maxWidth - numOfLetters - cur.size() + 1));\n\n return result;\n }\n}\n\n```\n```C++ []\n\nclass TextJustification {\npublic:\n vector<string> fullJustify(vector<string>& words, int maxWidth) {\n vector<string> result;\n vector<string> cur;\n int numOfLetters = 0;\n\n for (const string& word : words) {\n if (numOfLetters + word.length() + cur.size() > maxWidth) {\n int spacesToAdd = maxWidth - numOfLetters;\n for (int i = 0; i < spacesToAdd; i++) {\n cur[i % (cur.size() - 1)] += \' \';\n }\n result.push_back(accumulate(cur.begin(), cur.end(), string("")));\n cur.clear();\n numOfLetters = 0;\n }\n\n cur.push_back(word);\n numOfLetters += word.length();\n }\n\n string lastLine = accumulate(cur.begin(), cur.end(), string(" "));\n lastLine += string(maxWidth - numOfLetters - cur.size() + 1, \' \');\n result.push_back(lastLine);\n\n return result;\n }\n};\n\n```\n | 6,657 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 649 | 9 | ---\n![header_.png]()\n\n---\n```C []\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nchar ** fullJustify(char ** words, int wordsSize, int maxWidth, int* returnSize) {\n char **result = (char **)malloc(sizeof(char *) * wordsSize);\n *returnSize = 0;\n \n int start = 0; // Index of the first word in the current line.\n \n while (start < wordsSize) {\n int end = start; // Index of the last word in the current line.\n int lineLength = 0; // Length of the words and spaces in the current line.\n \n // Calculate the number of words and total length that can fit in the current line.\n while (end < wordsSize && lineLength + strlen(words[end]) + end - start <= maxWidth) {\n lineLength += strlen(words[end]);\n end++;\n }\n \n // Calculate the total number of spaces needed in the line.\n int totalSpaces = maxWidth - lineLength;\n \n // If it\'s the last line or only one word in the line, left-justify.\n if (end == wordsSize || end - start == 1) {\n result[*returnSize] = (char *)malloc(sizeof(char) * (maxWidth + 1));\n int idx = 0;\n for (int i = start; i < end; i++) {\n strcpy(result[*returnSize] + idx, words[i]);\n idx += strlen(words[i]);\n if (i != end - 1) {\n result[*returnSize][idx++] = \' \';\n }\n }\n while (idx < maxWidth) {\n result[*returnSize][idx++] = \' \';\n }\n result[*returnSize][maxWidth] = \'\\0\';\n } else {\n int spaceBetweenWords = totalSpaces / (end - start - 1);\n int extraSpaces = totalSpaces % (end - start - 1);\n \n result[*returnSize] = (char *)malloc(sizeof(char) * (maxWidth + 1));\n int idx = 0;\n for (int i = start; i < end; i++) {\n strcpy(result[*returnSize] + idx, words[i]);\n idx += strlen(words[i]);\n if (i != end - 1) {\n int spaces = spaceBetweenWords + (extraSpaces > 0 ? 1 : 0);\n extraSpaces--;\n for (int j = 0; j < spaces; j++) {\n result[*returnSize][idx++] = \' \';\n }\n }\n }\n result[*returnSize][maxWidth] = \'\\0\';\n }\n \n (*returnSize)++;\n start = end;\n }\n \n return result;\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<string> fullJustify(vector<string>& words, int maxWidth) {\n vector<string> result;\n int i = 0;\n \n while (i < words.size()) {\n int lineLen = words[i].size();\n int j = i + 1;\n \n // Find the words that can fit in the current line\n while (j < words.size() && lineLen + 1 + words[j].size() <= maxWidth) {\n lineLen += 1 + words[j].size();\n j++;\n }\n \n int numWords = j - i;\n int totalSpaces = maxWidth - lineLen + numWords - 1;\n \n // Construct the formatted line\n string line = words[i];\n if (numWords == 1 || j == words.size()) { // Left-justify\n for (int k = i + 1; k < j; k++) {\n line += " " + words[k];\n }\n line += string(maxWidth - line.size(), \' \'); // Pad with spaces\n } else { // Fully justify\n int spacesBetweenWords = totalSpaces / (numWords - 1);\n int extraSpaces = totalSpaces % (numWords - 1);\n for (int k = i + 1; k < j; k++) {\n int spaces = k - i <= extraSpaces ? spacesBetweenWords + 1 : spacesBetweenWords;\n line += string(spaces, \' \') + words[k];\n }\n }\n \n result.push_back(line);\n i = j;\n }\n \n return result;\n }\n};\n```\n```Typescript []\nfunction fullJustify(words: string[], maxWidth: number): string[] {\n let res = [], str = "", i = 0, n = words.length, x = 0;\n while( i < n ){\n if( (str + words[i]).length === maxWidth ){\n str += words[i++];\n res.push(str);\n str = "";\n x = i;\n }\n else if( (str + words[i]).length > maxWidth ){\n let j = x, cnt = maxWidth - (str.length - 1);\n while( cnt > 0 && j < i - 1 ){\n words[j++] += " ";\n cnt--;\n if( j === i - 1 && cnt > 0 )j = x\n }\n let tempStr = ""; j = x;\n while( j < i )tempStr += j < i - 1 ? words[j++] + " " : words[j++];\n while( tempStr.length < maxWidth )tempStr += " "\n res.push(tempStr);\n str = "";\n x = i;\n }\n else str += words[i++] + " ";\n }\n if( str.length > 0 ){\n let cnt = maxWidth - str.length;\n while( cnt > 0 ){\n str += " ";\n cnt--;\n }\n res.push(str)\n }\n return res\n};\n```\n```Java []\nclass Solution {\n public List<String> fullJustify(String[] words, int maxWidth) {\n List<String> result = new ArrayList<>();\n int index = 0;\n\n while (index < words.length) {\n int lineStart = index;\n int lineLength = words[index].length();\n index++;\n\n while (index < words.length && lineLength + words[index].length() + (index - lineStart) <= maxWidth) {\n lineLength += words[index].length();\n index++;\n }\n\n int totalSpaces = maxWidth - lineLength;\n int numWords = index - lineStart;\n\n StringBuilder line = new StringBuilder(words[lineStart]);\n \n if (numWords == 1 || index == words.length) { // Left-justify last line or single-word lines\n for (int i = lineStart + 1; i < index; i++) {\n line.append(\' \').append(words[i]);\n }\n line.append(String.valueOf(\' \').repeat(maxWidth - line.length())); // Add extra spaces at the end\n } else {\n int spacesBetweenWords = totalSpaces / (numWords - 1);\n int extraSpaces = totalSpaces % (numWords - 1);\n \n for (int i = lineStart + 1; i < index; i++) {\n int spaces = spacesBetweenWords + (extraSpaces-- > 0 ? 1 : 0);\n line.append(String.valueOf(\' \').repeat(spaces)).append(words[i]);\n }\n }\n\n result.add(line.toString());\n }\n\n return result;\n }\n}\n```\n```Python []\nclass Solution(object):\n def fullJustify(self, words, maxWidth):\n result = []\n line = []\n line_length = 0\n \n for word in words:\n if line_length + len(line) + len(word) > maxWidth:\n # Justify the current line\n spaces_to_add = maxWidth - line_length\n if len(line) == 1:\n result.append(line[0] + \' \' * spaces_to_add)\n else:\n num_gaps = len(line) - 1\n spaces_per_gap = spaces_to_add // num_gaps\n extra_spaces = spaces_to_add % num_gaps\n justified_line = line[0]\n for i in range(1, len(line)):\n spaces = spaces_per_gap + (1 if i <= extra_spaces else 0)\n justified_line += \' \' * spaces + line[i]\n result.append(justified_line)\n \n # Reset line and line_length\n line = []\n line_length = 0\n \n line.append(word)\n line_length += len(word)\n \n # Left-justify the last line\n last_line = \' \'.join(line)\n last_line += \' \' * (maxWidth - len(last_line))\n result.append(last_line)\n \n return result\n```\n```Python3 []\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n result = []\n line = [] # Stores words for the current line\n line_length = 0\n \n for word in words:\n # Check if adding the current word to the line exceeds the maxWidth\n if line_length + len(line) + len(word) > maxWidth:\n # Distribute extra spaces between words\n num_words = len(line)\n total_spaces = maxWidth - line_length\n \n if num_words == 1:\n # Left-justify if there\'s only one word in the line\n result.append(line[0] + \' \' * (maxWidth - len(line[0])))\n else:\n # Calculate even and extra spaces\n spaces_per_word = total_spaces // (num_words - 1)\n extra_spaces = total_spaces % (num_words - 1)\n \n # Create the justified line\n justified_line = ""\n for i in range(num_words - 1):\n justified_line += line[i] + \' \' * spaces_per_word\n if extra_spaces > 0:\n justified_line += \' \'\n extra_spaces -= 1\n justified_line += line[num_words - 1]\n result.append(justified_line)\n \n # Reset line variables for the next line\n line = []\n line_length = 0\n \n line.append(word)\n line_length += len(word)\n \n # Last line: left-justify and no extra spaces\n result.append(\' \'.join(line) + \' \' * (maxWidth - line_length - len(line) + 1))\n \n return result\n```\n```C# []\npublic class Solution {\n public IList<string> FullJustify(string[] words, int maxWidth) {\n List<string> result = new List<string>();\n int startIndex = 0;\n\n while (startIndex < words.Length) {\n int endIndex = startIndex;\n int lineLength = 0;\n\n // Find the range of words that can fit in the current line\n while (endIndex < words.Length && lineLength + words[endIndex].Length + (endIndex - startIndex) <= maxWidth) {\n lineLength += words[endIndex].Length;\n endIndex++;\n }\n\n // Calculate the number of total spaces and gaps between words\n int totalSpaces = maxWidth - lineLength;\n int totalGaps = endIndex - startIndex - 1;\n \n StringBuilder lineBuilder = new StringBuilder();\n\n // If it\'s the last line or only one word in the line, left-justify\n if (endIndex == words.Length || totalGaps == 0) {\n for (int i = startIndex; i < endIndex; i++) {\n lineBuilder.Append(words[i]);\n if (i < endIndex - 1) {\n lineBuilder.Append(\' \');\n }\n }\n while (lineBuilder.Length < maxWidth) {\n lineBuilder.Append(\' \');\n }\n } else {\n int spacesPerGap = totalSpaces / totalGaps;\n int extraSpaces = totalSpaces % totalGaps;\n\n for (int i = startIndex; i < endIndex; i++) {\n lineBuilder.Append(words[i]);\n if (i < endIndex - 1) {\n int spacesToAdd = spacesPerGap + (i - startIndex < extraSpaces ? 1 : 0);\n lineBuilder.Append(\' \', spacesToAdd);\n }\n }\n }\n\n result.Add(lineBuilder.ToString());\n startIndex = endIndex;\n }\n\n return result;\n }\n}\n```\n```Javascript []\nvar fullJustify = function(words, maxWidth) {\n let result = [];\n \n let line = [];\n let lineLength = 0;\n \n for(let i = 0; i < words.length; i++) {\n let w = words[i];\n \n if(lineLength === 0 && w.length <= maxWidth) {\n\t\t\t// Note: We add first word assuming no space will be added after it. As we know this is not the case. \n\t\t\t// The space for first word will be accounted for by our last word in the line & \n\t\t\t// the lack of space after last word is accounted for by this first word.\n line.push(w);\n lineLength += w.length;\n } else if(lineLength + w.length + 1 <= maxWidth){\n\t\t\t// we add word and consider it\'s length plus a space following it\n line.push(w);\n lineLength += (w.length + 1);\n } else {\n\t\t\t//OUR LINE IS FULL AND SHOULD BE ADDED TO THE RESULT\n\t\t\t\n // add the required single space after each word except last one\n line = addMinSpace(line);\n \n // find remaining space to distribute\n let remainingSpace = maxWidth - lineLength;\n \n // add remaining space to each word expect last one\n line = distributeSpaces(line, remainingSpace);\n\n // turn array into a single string\n let temp = line.join("")\n \n // If the line only had one large word, we add remaining spaces to it\'s end just like how we would later do for last line\n if(line.length === 1) temp = addRemainingSpaces(temp, remainingSpace)\n \n result.push(temp);\n \n // reset the line and it\'s length\n line = [];\n lineLength = 0;\n \n // add this new word like it\'s the first one\n line.push(w);\n lineLength += w.length;\n }\n }\n \n \n // pad our final line\n line = addMinSpace(line);\n \n // create final string\n let temp = line.join("")\n \n // find remaining padding \n let remainingSpace = maxWidth - lineLength;\n \n // add remaining padding to end of our final line\n temp = addRemainingSpaces(temp, remainingSpace)\n \n // add final line to result\n result.push(temp);\n \n // return result\n return result;\n \n\t// Adds single space after each word except last one\n function addMinSpace(line) {\n for(let i = 0; i < line.length - 1; i++) line[i] += " ";\n return line;\n }\n \n\t// add remaining spaces to end of line\n function addRemainingSpaces(line, spaces) {\n while(spaces > 0) {\n line += " ";\n spaces--;\n }\n return line;\n }\n \n\t// distribute remaining spaces from left to right\n function distributeSpaces(arr, spaces) {\n while(spaces > 0 && arr.length > 1) {\n for(let i = 0; i < arr.length - 1; i++) {\n if(spaces <= 0) break;\n arr[i] = arr[i] + " ";\n spaces --;\n } \n }\n return arr;\n }\n};\n```\n```Kotlin []\nclass Solution {\n fun fullJustify(words: Array<String>, maxWidth: Int): List<String> {\n val result = mutableListOf<String>()\n var lineWords = mutableListOf<String>()\n var lineLength = 0\n \n for (word in words) {\n if (lineLength + lineWords.size + word.length <= maxWidth) {\n lineWords.add(word)\n lineLength += word.length\n } else {\n result.add(constructLine(lineWords, maxWidth, lineLength))\n lineWords.clear()\n lineWords.add(word)\n lineLength = word.length\n }\n }\n \n // Last line\n if (lineWords.isNotEmpty()) {\n val lastLine = lineWords.joinToString(" ")\n result.add(lastLine.padEnd(maxWidth))\n }\n \n return result\n }\n \n private fun constructLine(words: List<String>, maxWidth: Int, lineLength: Int): String {\n val numWords = words.size\n if (numWords == 1) {\n return words[0].padEnd(maxWidth)\n }\n \n val totalSpaces = maxWidth - lineLength\n val spaceSlots = numWords - 1\n val baseSpace = totalSpaces / spaceSlots\n val extraSpaceSlots = totalSpaces % spaceSlots\n \n val lineBuilder = StringBuilder()\n for (i in 0 until numWords - 1) {\n lineBuilder.append(words[i])\n lineBuilder.append(" ".repeat(baseSpace))\n if (i < extraSpaceSlots) {\n lineBuilder.append(" ")\n }\n }\n lineBuilder.append(words.last())\n \n return lineBuilder.toString()\n }\n}\n```\n```PHP []\nclass Solution {\n /**\n * @param String[] $words\n * @param Integer $maxWidth\n * @return String[]\n */\n function fullJustify($words, $maxWidth) {\n $result = [];\n $line = [];\n $lineWidth = 0;\n \n foreach ($words as $word) {\n // Check if adding the next word exceeds maxWidth\n if ($lineWidth + count($line) + strlen($word) > $maxWidth) {\n $formattedLine = $this->formatLine($line, $lineWidth, $maxWidth);\n $result[] = $formattedLine;\n \n $line = [];\n $lineWidth = 0;\n }\n \n $line[] = $word;\n $lineWidth += strlen($word);\n }\n \n // Handle the last line\n $lastLine = implode(\' \', $line);\n $lastLine .= str_repeat(\' \', $maxWidth - strlen($lastLine));\n $result[] = $lastLine;\n \n return $result;\n }\n \n // Helper function to format a line\n private function formatLine($line, $lineWidth, $maxWidth) {\n $numWords = count($line);\n $numSpaces = $maxWidth - $lineWidth;\n \n if ($numWords === 1) {\n return $line[0] . str_repeat(\' \', $numSpaces);\n }\n \n $avgSpaces = floor($numSpaces / ($numWords - 1));\n $extraSpaces = $numSpaces % ($numWords - 1);\n \n $formattedLine = $line[0];\n \n for ($i = 1; $i < $numWords; $i++) {\n $numPaddingSpaces = $avgSpaces + ($i <= $extraSpaces ? 1 : 0);\n $formattedLine .= str_repeat(\' \', $numPaddingSpaces) . $line[$i];\n }\n \n return $formattedLine;\n }\n}\n```\n\n\n---\n![download.jpg]()\n\n--- | 6,658 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 6,622 | 47 | We\'ll build the result array line by line while iterating over words in the input. Whenever the current line gets too big, we\'ll appropriately format it and proceed with the next line until for loop is over. Last but not least, we\'ll need to left-justify the last line.\n\nTime complexity is **O(n)**:\nThere is just one for loop, which iterates over words provided as input.\nSpace complexity: **O(n + l)**\nWhere **n** is lenght of words, and **l** max length of words in one line. Worst case scenario **l = n**, which will add up to **O(2n)** but in asymptotic analysis we don\'t care about constants so final complexity is linear: **O(n)**\n\n```\nclass Solution:\n\t# Why slots: \n # TLDR: 1. faster attribute access. 2. space savings in memory.\n # For letcode problems this can save ~ 0.1MB of memory <insert is something meme>\n __slots__ = ()\n\t\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n\t # Init return array in which, we\'ll store justified lines\n lines = []\n\t\t# current line width\n width = 0\n\t\t# current line words\n line = []\n \n for word in words:\n\t\t\t# Gather as many words that will fit under maxWidth restrictions.\n\t\t\t# Line length is a sum of:\n\t\t\t# 1) Current word length\n\t\t\t# 2) Sum of words already in the current line\n\t\t\t# 3) Number of spaces (each word needs to be separated by at least one space)\n if (len(word) + width + len(line)) <= maxWidth:\n width += len(word)\n line.append(word)\n continue\n \n\t\t\t# If the current line only contains one word, fill the remaining string with spaces.\n if len(line) == 1:\n\t\t\t\t# Use the format function to fill the remaining string with spaces easily and readable.\n\t\t\t\t# For letcode police, yes you could do something like:\n\t\t\t\t# line = " ".join(line)\n\t\t\t\t# line += " " * (maxWidth - len(line))\n\t\t\t\t# lines.append(line)\n\t\t\t\t# to be more "raw", but I see no point in that.\n lines.append(\n "{0: <{width}}".format( " ".join(line), width=maxWidth)\n )\n else:\n\t\t\t # Else calculate how many common spaces and extra spaces are there for the current line.\n\t\t\t\t# Example:\n # line = [\'a\', \'computer.\', \'Art\', \'is\']\n\t\t\t\t# width left in line equals to: maxWidth - width: 20 - 15 = 5\n\t\t\t\t# len(line) - 1 because to the last word, we aren\'t adding any spaces\n\t\t\t\t# Now divmod will give us how many spaces are for all words and how many extra to distribute.\n\t\t\t\t# divmod(5, 3) = 1, 2\n\t\t\t\t# This means there should be one common space for each word, and for the first two, add one extra space.\n space, extra = divmod(\n maxWidth - width,\n len(line) - 1\n )\n \n i = 0\n\t\t\t\t# Distribute extra spaces first\n\t\t\t\t# There cannot be a case where extra spaces count is greater or equal to number words in the current line.\n while extra > 0:\n line[i] += " "\n extra -= 1\n i += 1\n \n\t\t\t\t# Join line array into a string by common spaces, and append to justified lines.\n lines.append(\n (" " * space).join(line)\n )\n \n\t\t\t# Create new line array with the current word in iteration, and reset current line width as well.\n line = [word]\n width = len(word)\n \n\t\t# Last but not least format last line to be left-justified with no extra space inserted between words.\n\t\t# No matter the input, there always be the last line at the end of for loop, which makes things even easier considering the requirement.\n lines.append(\n "{0: <{width}}".format(" ".join(line), width=maxWidth)\n )\n \n return lines\n``` | 6,669 |
Text Justification | text-justification | Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified and no extra space is inserted between words. Note: | Array,String,Simulation | Hard | null | 3,210 | 17 | ***Hello it would be my pleasure to introduce myself Darian.***\n\n***Java***\n```\nclass Solution {\n public List<String> fullJustify(String[] words, int maxWidth) {\n int left = 0; List<String> result = new ArrayList<>();\n \n while (left < words.length) {\n int right = findRight(left, words, maxWidth);\n result.add(justify(left, right, words, maxWidth));\n left = right + 1;\n }\n \n return result;\n }\n \n private int findRight(int left, String[] words, int maxWidth) {\n int right = left;\n int sum = words[right++].length();\n \n while (right < words.length && (sum + 1 + words[right].length()) <= maxWidth)\n sum += 1 + words[right++].length();\n \n return right - 1;\n }\n \n private String justify(int left, int right, String[] words, int maxWidth) {\n if (right - left == 0) return padResult(words[left], maxWidth);\n \n boolean isLastLine = right == words.length - 1;\n int numSpaces = right - left;\n int totalSpace = maxWidth - wordsLength(left, right, words);\n \n String space = isLastLine ? " " : blank(totalSpace / numSpaces);\n int remainder = isLastLine ? 0 : totalSpace % numSpaces;\n \n StringBuilder result = new StringBuilder();\n for (int i = left; i <= right; i++)\n result.append(words[i])\n .append(space)\n .append(remainder-- > 0 ? " " : "");\n \n return padResult(result.toString().trim(), maxWidth);\n }\n \n private int wordsLength(int left, int right, String[] words) {\n int wordsLength = 0;\n for (int i = left; i <= right; i++) wordsLength += words[i].length();\n return wordsLength;\n }\n \n private String padResult(String result, int maxWidth) {\n return result + blank(maxWidth - result.length());\n }\n \n private String blank(int length) {\n return new String(new char[length]).replace(\'\\0\', \' \');\n }\n}\n```\n\n***JavaScript***\n```\nvar fullJustify = function(words, maxWidth) {\n let result = [];\n \n let line = [];\n let lineLength = 0;\n \n for(let i = 0; i < words.length; i++) {\n let w = words[i];\n \n if(lineLength === 0 && w.length <= maxWidth) {\n\t\t\t// Note: We add first word assuming no space will be added after it. As we know this is not the case. \n\t\t\t// The space for first word will be accounted for by our last word in the line & \n\t\t\t// the lack of space after last word is accounted for by this first word.\n line.push(w);\n lineLength += w.length;\n } else if(lineLength + w.length + 1 <= maxWidth){\n\t\t\t// we add word and consider it\'s length plus a space following it\n line.push(w);\n lineLength += (w.length + 1);\n } else {\n\t\t\t//OUR LINE IS FULL AND SHOULD BE ADDED TO THE RESULT\n\t\t\t\n // add the required single space after each word except last one\n line = addMinSpace(line);\n \n // find remaining space to distribute\n let remainingSpace = maxWidth - lineLength;\n \n // add remaining space to each word expect last one\n line = distributeSpaces(line, remainingSpace);\n\n // turn array into a single string\n let temp = line.join("")\n \n // If the line only had one large word, we add remaining spaces to it\'s end just like how we would later do for last line\n if(line.length === 1) temp = addRemainingSpaces(temp, remainingSpace)\n \n result.push(temp);\n \n // reset the line and it\'s length\n line = [];\n lineLength = 0;\n \n // add this new word like it\'s the first one\n line.push(w);\n lineLength += w.length;\n }\n }\n \n \n // pad our final line\n line = addMinSpace(line);\n \n // create final string\n let temp = line.join("")\n \n // find remaining padding \n let remainingSpace = maxWidth - lineLength;\n \n // add remaining padding to end of our final line\n temp = addRemainingSpaces(temp, remainingSpace)\n \n // add final line to result\n result.push(temp);\n \n // return result\n return result;\n \n\t// Adds single space after each word except last one\n function addMinSpace(line) {\n for(let i = 0; i < line.length - 1; i++) line[i] += " ";\n return line;\n }\n \n\t// add remaining spaces to end of line\n function addRemainingSpaces(line, spaces) {\n while(spaces > 0) {\n line += " ";\n spaces--;\n }\n return line;\n }\n \n\t// distribute remaining spaces from left to right\n function distributeSpaces(arr, spaces) {\n while(spaces > 0 && arr.length > 1) {\n for(let i = 0; i < arr.length - 1; i++) {\n if(spaces <= 0) break;\n arr[i] = arr[i] + " ";\n spaces --;\n } \n }\n return arr;\n }\n};\n```\n\n***C++***\n```\nclass Solution {\npublic:\n vector<string> fullJustify(vector<string>& words, int maxWidth) {\n vector<string> result;\n const int totalWords = words.size()-1;\n for (int begin=0, moreWords=0; begin<=totalWords; begin=moreWords) {\n string currentBlock(maxWidth, \' \');\n /* In problem statement, it is specified that each word is guaranteed to be\n * grether than 0 and not exceed maxWidth, so I can safely add first word. */\n currentBlock.replace(0, words[begin].size(), words[begin]);\n /* Now current block of text is ready with first word and remainig spaces,\n * I just need to calculate how many more words I can fit in this block. */\n int remainingSpace = maxWidth - words[begin].size();\n for (moreWords=begin+1; moreWords <=totalWords && words[moreWords].size() < remainingSpace; moreWords++) {\n /* First word in current block is already added before this for loop.\n * Additional word(s) can be added in current justification block. As this\n * is additional word, at least one space is needed in calculation\n * for remaining space. Above \'<\' condition make sure that we have space for\n * one additional space */\n remainingSpace -= words[moreWords].size()+1;\n }\n /* Word joints are total separating gap between words, for which we need to do\n * space management */\n int wordJoints = moreWords - begin -1;\n if (wordJoints) {\n /*Ok so we have more than one word in this justification block*/\n int evenlyDistributedSpace = 1; /*One space is already provisioned in above loop */\n int unEvenSpace = 0;\n if (moreWords <= totalWords) {\n /* Control is here means current justification block is not the last\n * block, so we need to do some mathematics on remaining space and evenly\n * distribute it between the words (word joints). Remember for last block\n * this is not needed as it is left aligned and additional words are only\n * placed one white space apart */\n evenlyDistributedSpace += remainingSpace / wordJoints;\n unEvenSpace = remainingSpace % wordJoints;\n }\n for (int i=begin+1, index=words[begin].size(); i < moreWords; i++) {\n index += evenlyDistributedSpace + (unEvenSpace-- > 0);\n currentBlock.replace(index, words[i].size(), words[i]);\n index += words[i].size();\n }\n }\n result.push_back(currentBlock);\n }\n return result;\n }\n};\n```\n\n***Python***\n```\nclass Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n ans, cur = [], []\n chars = 0\n \n for word in words:\n # if cur is empty or the total chars + total needed spaces + next word fit\n if not cur or (len(word) + chars + len(cur)) <= maxWidth:\n cur.append(word)\n chars += len(word)\n else:\n # place spaces, append the line to the ans, and move on\n line = self.placeSpacesBetween(cur, maxWidth - chars)\n ans.append(line)\n cur.clear()\n cur.append(word)\n chars = len(word)\n \n # left justify any remaining text, which is easy\n if cur:\n extra_spaces = maxWidth - chars - len(cur) + 1\n ans.append(\' \'.join(cur) + \' \' * extra_spaces)\n \n return ans\n \n \n def placeSpacesBetween(self, words, spaces):\n if len(words) == 1: return words[0] + \' \' * spaces\n \n space_groups = len(words)-1\n spaces_between_words = spaces // space_groups\n extra_spaces = spaces % space_groups\n \n cur = []\n for word in words:\n cur.append(word)\n \n # place the min of remaining spaces or spaces between words plus an extra if available\n cur_extra = min(1, extra_spaces)\n spaces_to_place = min(spaces_between_words + cur_extra, spaces)\n\n cur.append(\' \' * spaces_to_place)\n \n if extra_spaces: extra_spaces -= 1\n spaces -= spaces_to_place\n \n return \'\'.join(cur)\n```\n\n***Kotlin***\n```\nclass Solution {\n private val SEPARATOR = " " \n \n fun fullJustify(words: Array<String>, maxWidth: Int): List<String> {\n\n val result = mutableListOf<String>() // keeps the lines as a sting in a paragraph\n val currentLineWords = mutableListOf<String>()// keeps track of all the words for the current line\n var availableSpacePerLine = maxWidth // keeps track of the available space in the current line\n\n words.forEach { word ->\n availableSpacePerLine -= word.length\n when {\n (availableSpacePerLine == 0) -> { // the words perfectly fit\n currentLineWords.add(word)\n result.add(toLineString(availableSpacePerLine, currentLineWords))\n\n // Start a new line\n currentLineWords.clear()\n availableSpacePerLine = maxWidth\n }\n (availableSpacePerLine < 0) -> { // too much words in a line adjust!\n availableSpacePerLine += (word.length + 1) //remove the claimed space for current\n result.add(toLineString(availableSpacePerLine, currentLineWords))\n\n // Start a new line\n currentLineWords.clear()\n currentLineWords.add(word)\n availableSpacePerLine = maxWidth - (word.length + 1)\n }\n (availableSpacePerLine > 0) -> { // space is still available in the current line\n currentLineWords.add(word)\n availableSpacePerLine--\n }\n }\n }\n\n // Process the last line if there is one\n if (currentLineWords.isNotEmpty()) {\n result.add(toLineString(availableSpacePerLine + 1, currentLineWords, true))\n }\n return result\n }\n \n\n private fun toLineString(\n noOfSpaceToBeDistributed: Int,\n wordsInLine: MutableList<String>,\n isLastLine: Boolean = false\n ): String {\n return if (wordsInLine.size == 1 || isLastLine) { // if there is only one word in a line or if the line is the last one , all the remaining spaces should just go to the end of the sentence\n wordsInLine.joinToString(SEPARATOR) + SEPARATOR.repeat(noOfSpaceToBeDistributed)\n } else { // other wise we have to evenly distribute the remaining lines\n val spaceToBeAddedToAllWords = (Math.floorDiv(\n noOfSpaceToBeDistributed,\n wordsInLine.lastIndex\n )) + 1 // the +1 is because we already take in to consideration a space when calculating noOfSpaceToBeDistributed\n \n for (i in 0 until noOfSpaceToBeDistributed % wordsInLine.lastIndex) {\n wordsInLine[i] += SEPARATOR\n }\n wordsInLine.joinToString(SEPARATOR.repeat(spaceToBeAddedToAllWords))\n }\n }\n \n \n}\n```\n\n***Swift***\n```\nclass Solution {\n func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {\n var res: [String] = []\n var i = 0\n \n while i < words.count {\n var j = i\n var tmpLength = 0\n \n while j < words.count {\n tmpLength += words[j].count + ((j > i) ? 1 : 0)\n \n if tmpLength <= maxWidth { j += 1 } \n else {\n res.append(stringWithWords(words, maxWidth, i, j))\n break\n }\n }\n \n if j == words.count {\n res.append(stringWithWords(words, maxWidth, i, j))\n }\n i = j\n }\n \n return res\n }\n\n\n func stringWithWords(_ words: [String], _ maxWidth: Int, _ i: Int, _ j: Int) -> String {\n var length = 0\n var string = ""\n \n func space(_ n: Int) -> String {\n var string = ""\n for _ in 0..<n { string += " " }\n return string\n }\n \n func space(_ index: Int, _ count: Int, _ length: Int, _ maxWidth: Int, _ isLast: Bool) -> String {\n if isLast { return index == count - 1 ? space(maxWidth - length - count + 1) : " " }\n if count == 1 { return space(maxWidth - length) }\n if index == count - 1 { return "" }\n return space((maxWidth - length) / (count - 1)) + (index < ((maxWidth - length) % (count - 1)) ? " " : "")\n }\n\n for k in i..<j { length += words[k].count }\n \n for k in i..<j {\n string += words[k] + space(k - i, j - i, length, maxWidth, j == words.count)\n }\n \n return string\n }\n\n}\n```\n\n***Consider upvote if useful! Hopefully it can be used in your advantage!***\n***Take care brother, peace, love!*** | 6,689 |
Sqrt(x) | sqrtx | Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. | Math,Binary Search | Easy | Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi) | 65,715 | 265 | # Intuition of this Problem:\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. If x is 0, return 0.\n2. Initialize first to 1 and last to x.\n3. While first is less than or equal to last, do the following:\n a. Compute mid as first + (last - first) / 2.\n b. If mid * mid equals x, return mid.\n c. If mid * mid is greater than x, update last to mid - 1.\n d. If mid * mid is less than x, update first to mid + 1.\n4. Return last.\n\n<!-- Describe your approach to solving the problem. -->\n\n\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int mySqrt(int x) {\n if (x == 0)\n return x;\n int first = 1, last = x;\n while (first <= last) {\n int mid = first + (last - first) / 2;\n // mid * mid == x gives runtime error\n if (mid == x / mid)\n return mid;\n else if (mid > x / mid) {\n last = mid - 1;\n }\n else {\n first = mid + 1;\n }\n }\n return last;\n }\n};\n```\n```Java []\nclass Solution {\n public int mySqrt(int x) {\n if (x == 0) {\n return 0;\n }\n int first = 1, last = x;\n while (first <= last) {\n int mid = first + (last - first) / 2;\n if (mid == x / mid) {\n return mid;\n } else if (mid > x / mid) {\n last = mid - 1;\n } else {\n first = mid + 1;\n }\n }\n return last;\n }\n}\n\n```\n```Python []\nclass Solution:\n def mySqrt(self, x: int) -> int:\n if x == 0:\n return 0\n first, last = 1, x\n while first <= last:\n mid = first + (last - first) // 2\n if mid == x // mid:\n return mid\n elif mid > x // mid:\n last = mid - 1\n else:\n first = mid + 1\n return last\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(logn)**\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)$$ --> | 6,705 |
Sqrt(x) | sqrtx | Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. | Math,Binary Search | Easy | Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi) | 611 | 9 | \n\nOne way to solve this would be to check every number starting from 0. Since we could stop once we reach the square root of x, this would run in O(sqrt(n)) time. However, binary search runs in O(log n) time, which, as you can see from the graph below, is superior to O(sqrt n) time.\n\n![Presentation1.png]()\n\nNow, why does binary search run in O(log n) time? Well, with each iteration, we eliminate around half of the array. So now the question is: how many iterations does it take to converge on a single element? In other words, how many times do we need to divide\xA0n\xA0by 2 until we reach 1?\n\nIf\xA0**k**\xA0is the number of times we need to divide\xA0n\xA0by 2 to reach 1, then the equation is:\n\nn / 2<sup>k</sup>\xA0= 1\n\nn = 2<sup>k</sup>\xA0\xA0\xA0(multiply both sides by 2k)\n\nlog<sub>2</sub>n = k \xA0\xA0(definition of logarithms)\n\nSo we know that it takes log<sub>2</sub>n steps in the worst case to find the element. But in Big O notation, we ignore the base, so this ends up running in O(log n) time.\n\n# Code\n```\nclass Solution:\n def mySqrt(self, x: int) -> int:\n left = 0\n right = x\n while left <= right:\n mid = (left + right) // 2\n if mid * mid < x:\n left = mid + 1\n elif mid * mid > x:\n right = mid -1\n else:\n return mid\n \n return right\n``` | 6,710 |
Sqrt(x) | sqrtx | Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5. | Math,Binary Search | Easy | Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi) | 11,962 | 51 | \n\n# 1. Normal Math Approach\n```\nclass Solution:\n def mySqrt(self, x: int) -> int:\n number=1\n while number*number<=x:\n number+=1\n return number\n\n```\n# Binary Search Approach\n```\n\nclass Solution:\n def mySqrt(self, x: int) -> int:\n left,right=1,x\n while left<=right:\n mid=(left+right)//2\n if mid*mid==x:\n return mid\n if mid*mid>x:\n right=mid-1\n else:\n left=mid+1\n return right\n \n\n```\n# please upvote me it would encourage me alot\n\n | 6,739 |
Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | Math,Dynamic Programming,Memoization | Easy | To reach nth step, what could have been your previous steps? (Think about the step sizes) | 87,372 | 1,005 | # Intuition:\nTo calculate the number of ways to climb the stairs, we can observe that when we are on the nth stair, \nwe have two options: \n1. either we climbed one stair from the (n-1)th stair or \n2. we climbed two stairs from the (n-2)th stair. \n\nBy leveraging this observation, we can break down the problem into smaller subproblems and apply the concept of the Fibonacci series. \nThe base cases are when we are on the 1st stair (only one way to reach it) and the 2nd stair (two ways to reach it). \nBy summing up the number of ways to reach the (n-1)th and (n-2)th stairs, we can compute the total number of ways to climb the stairs. This allows us to solve the problem efficiently using various dynamic programming techniques such as recursion, memoization, tabulation, or space optimization.\n\n# Approach 1: Recursion ```\u274C TLE \u274C```\n**Explanation**: The recursive solution uses the concept of Fibonacci numbers to solve the problem. It calculates the number of ways to climb the stairs by recursively calling the `climbStairs` function for (n-1) and (n-2) steps. However, this solution has exponential time complexity (O(2^n)) due to redundant calculations.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n return climbStairs(n-1) + climbStairs(n-2);\n }\n};\n```\n```Java []\nclass Solution {\n public int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n return climbStairs(n-1) + climbStairs(n-2);\n }\n}\n```\n```Python3 []\nclass Solution:\n def climbStairs(self, n: int) -> int:\n if n == 0 or n == 1:\n return 1\n return self.climbStairs(n-1) + self.climbStairs(n-2)\n```\n\n# Approach 2: Memoization\n**Explanation**: The memoization solution improves the recursive solution by introducing memoization, which avoids redundant calculations. We use an unordered map (`memo`) to store the already computed results for each step `n`. Before making a recursive call, we check if the result for the given `n` exists in the memo. If it does, we return the stored value; otherwise, we compute the result recursively and store it in the memo for future reference.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int climbStairs(int n, unordered_map<int, int>& memo) {\n if (n == 0 || n == 1) {\n return 1;\n }\n if (memo.find(n) == memo.end()) {\n memo[n] = climbStairs(n-1, memo) + climbStairs(n-2, memo);\n }\n return memo[n];\n }\n\n int climbStairs(int n) {\n unordered_map<int, int> memo;\n return climbStairs(n, memo);\n }\n};\n```\n```Java []\nclass Solution {\n public int climbStairs(int n) {\n Map<Integer, Integer> memo = new HashMap<>();\n return climbStairs(n, memo);\n }\n \n private int climbStairs(int n, Map<Integer, Integer> memo) {\n if (n == 0 || n == 1) {\n return 1;\n }\n if (!memo.containsKey(n)) {\n memo.put(n, climbStairs(n-1, memo) + climbStairs(n-2, memo));\n }\n return memo.get(n);\n }\n}\n```\n```Python3 []\nclass Solution:\n def climbStairs(self, n: int) -> int:\n memo = {}\n return self.helper(n, memo)\n \n def helper(self, n: int, memo: dict[int, int]) -> int:\n if n == 0 or n == 1:\n return 1\n if n not in memo:\n memo[n] = self.helper(n-1, memo) + self.helper(n-2, memo)\n return memo[n]\n```\n\n# Approach 3: Tabulation\n**Explanation**: The tabulation solution eliminates recursion and uses a bottom-up approach to solve the problem iteratively. It creates a DP table (`dp`) of size n+1 to store the number of ways to reach each step. The base cases (0 and 1 steps) are initialized to 1 since there is only one way to reach them. Then, it iterates from 2 to n, filling in the DP table by summing up the values for the previous two steps. Finally, it returns the value in the last cell of the DP table, which represents the total number of ways to reach the top.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n\n vector<int> dp(n+1);\n dp[0] = dp[1] = 1;\n \n for (int i = 2; i <= n; i++) {\n dp[i] = dp[i-1] + dp[i-2];\n }\n return dp[n];\n }\n};\n```\n```Java []\nclass Solution {\n public int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n\n int[] dp = new int[n+1];\n dp[0] = dp[1] = 1;\n \n for (int i = 2; i <= n; i++) {\n dp[i] = dp[i-1] + dp[i-2];\n }\n return dp[n];\n }\n}\n```\n```Python3 []\nclass Solution:\n def climbStairs(self, n: int) -> int:\n if n == 0 or n == 1:\n return 1\n\n dp = [0] * (n+1)\n dp[0] = dp[1] = 1\n \n for i in range(2, n+1):\n dp[i] = dp[i-1] + dp[i-2]\n return dp[n]\n```\n\n# Approach 4: Space Optimization\n**Explanation**: The space-optimized solution further reduces the space complexity by using only two variables (`prev` and `curr`) instead of an entire DP table. It initializes `prev` and `curr` to 1 since there is only one way to reach the base cases (0 and 1 steps). Then, in each iteration, it updates `prev` and `curr` by shifting their values. `curr` becomes the sum of the previous two values, and `prev` stores the previous value of `curr`.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n int prev = 1, curr = 1;\n for (int i = 2; i <= n; i++) {\n int temp = curr;\n curr = prev + curr;\n prev = temp;\n }\n return curr;\n }\n};\n```\n```Java []\nclass Solution {\n public int climbStairs(int n) {\n if (n == 0 || n == 1) {\n return 1;\n }\n int prev = 1, curr = 1;\n for (int i = 2; i <= n; i++) {\n int temp = curr;\n curr = prev + curr;\n prev = temp;\n }\n return curr;\n }\n}\n```\n```Python3 []\nclass Solution:\n def climbStairs(self, n: int) -> int:\n if n == 0 or n == 1:\n return 1\n prev, curr = 1, 1\n for i in range(2, n+1):\n temp = curr\n curr = prev + curr\n prev = temp\n return curr\n```\n\n![CUTE_CAT.png]()\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.** | 6,800 |
Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | Math,Dynamic Programming,Memoization | Easy | To reach nth step, what could have been your previous steps? (Think about the step sizes) | 74,808 | 421 | # Intuition\nUsing Top - Down Approach -> Recursion + Memorization.\n\n# Approach\nStoring the values of overlapping sub - problems in a vector.\n\n# Complexity\n- Time complexity:\nO(n) -> As we are visiting all values of n atleast 1 time.\n\n- Space complexity:\nO(n) + O(n) - > (Recursive calls + Array of size n)\n\n# Code\n```\nclass Solution {\npublic:\n int solve(int n,vector<int> &dp){\n //base case\n if(n<=2)\n return n;\n \n if(dp[n]!=-1) \n return dp[n]; \n \n dp[n]=solve(n-1,dp)+solve(n-2,dp);\n return dp[n];\n }\n int climbStairs(int n) {\n if(n<=2)\n return n;\n vector<int> dp(n+1,-1);\n return solve(n,dp);\n }\n};\n```\n\n# Intuition\nUsing Bottom - up Approach -> Tabulation.\n\n# Approach\nStoring the values of overlapping sub - problems in a vector.\n\n# Complexity\n- Time complexity:\nO(n) -> As we are traversing the vector atleast 1 time.\n\n- Space complexity:\nO(n) - > (Array of size n)\n\n# Code\n```\nclass Solution {\npublic:\n int climbStairs(int n) {\n if(n<=2)\n return n;\n vector<int> dp(n+1);\n dp[0]=0;\n dp[1]=1;\n dp[2]=2;\n for(int i=3;i<=n;i++)\n dp[i]=dp[i-1]+dp[i-2];\n \n return dp[n];\n }\n};\n```\n\n# Python Code :\nContributed by : Aarya_R\n\n# Complexity\n- Time complexity:\nO(n) -> As we are traversing the vector atleast 1 time.\n\n- Space complexity:\nO(1) \n```\ndef climbStairs(self, n):\n prev = 1\n prev2 = 0\n for i in range(1, n+1):\n curi = prev + prev2\n prev2 = prev\n prev = curi\n return prev \n```\n![upvote.jfif]()\n\n | 6,802 |
Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | Math,Dynamic Programming,Memoization | Easy | To reach nth step, what could have been your previous steps? (Think about the step sizes) | 71,478 | 672 | #####\n### General inutution\n##### \t-> Intution : the next distinict way of climbing stairs is euqal to the sum of the last two distinict way of climbing\n##### \t\tdistinct(n) = distinict(n-1) + distinict(n-2)\n##### This intution can be applied using the following three approach --> ordered from easy to difficult approach\n#####\n##### \n##### \n#### Idea 1 : pure recursive (Can\'t pass the test case :does not work for big number, result time-exced limit)\n##### \t- The base case will be when only 1 or 2 steps left\n##### \t- Result time-exced limit\n##### \n \n\n```\nclass Solution(object):\n def climbStairs(self, n):\n """\n :type n: int\n :rtype: int\n """\n def climb(n):\n if n==1: #only one step option is availble\n return 1\n if n ==2: # two options are possible : to take two 1-stpes or to only take one 2-steps\n return 2\n return climb(n-1) + climb(n-2)\n return climb(n)\n \n```\n##### \n##### \'\'\'\n#### Idea 2 : use dictionary (look-up table) to memorize repeating recursion\n##### - The memory start with the base case and recored every recurssion\n##### \'\'\'\n```\nclass Solution(object):\n def climbStairs(self, n):\n """\n :type n: int\n :rtype: int\n """\n memo ={}\n memo[1] = 1\n memo[2] = 2\n \n def climb(n):\n if n in memo: # if the recurssion already done before first take a look-up in the look-up table\n return memo[n]\n else: # Store the recurssion function in the look-up table and reuturn the stored look-up table function\n memo[n] = climb(n-1) + climb(n-2)\n return memo[n]\n \n return climb(n)\n```\n \n##### \'\'\'\n### Idea 3 : Dynamic programming \n##### --> store the distinct ways in a dynamic table\n##### climb = [climb(0), climb(1), climb(2)=climb(0)+climb(1), climb(3)=climb(2)+climb(1),......climb(n)=climb(n-1)+climb(n-2)]\n##### dp = [ 0, 1, 2, 3, 5, dp(i-1)+dp(i-2])]\n##### return dp[n]\n##### \'\'\'\n\tdef climb(n):\n #edge cases\n if n==0: return 0\n if n==1: return 1\n if n==2: return 2\n dp = [0]*(n+1) # considering zero steps we need n+1 places\n dp[1]= 1\n dp[2] = 2\n for i in range(3,n+1):\n dp[i] = dp[i-1] +dp[i-2]\n print(dp)\n return dp[n]\n\t\t\t\n### ****** upvote as a sign of appriatation ***** | 6,807 |
Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | Math,Dynamic Programming,Memoization | Easy | To reach nth step, what could have been your previous steps? (Think about the step sizes) | 17,944 | 99 | ```\nclass Solution:\n def climbStairs(self, n: int) -> int:\n dp=[-1]*(n+2)\n def solve(i):\n if i==0 or i==1:\n return 1\n if dp[i]!=-1:\n return dp[i]\n left=solve(i-1)\n right=solve(i-2)\n dp[i]=left+right\n return left+right\n return solve(n)\n```\n\n```\nclass Solution:\n def climbStairs(self, n: int) -> int:\n one,two=1,1\n for i in range(n-1):\n temp=one+two\n one=two\n two=temp\n return two\n #please upvote me it would encourage me alot\n\n\n``` | 6,826 |
Climbing Stairs | climbing-stairs | You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | Math,Dynamic Programming,Memoization | Easy | To reach nth step, what could have been your previous steps? (Think about the step sizes) | 664 | 12 | \n\nSince you can only take 1 step or 2 steps, the total number of ways to climb `n` steps can be defined recursively as: the total number of ways to climb `n-1` stairs + the total number of ways to climb `n-2` stairs. Below is the recursive code:\n\n## Recursive Solution\n```\nclass Solution:\n def climbStairs(self, n: int) -> int:\n if n == 1:\n return 1\n if n == 2:\n return 2\n return self.climbStairs(n-1) + self.climbStairs(n-2)\n```\n\nThis works, but the problem is that we make many of the same function calls over and over again, and the algorithm ends up running in O(2<sup>n</sup>) time. So instead, the bottom-up dynamic programming approach calculates the number of ways to climb a certain number of stairs <i>only once</i>, and reuses previous values to build up to the solution. For a visualization, please see the video, but because each calculation only needs to be done once, the runtime is reduced to O(n) time.\n\nWe start by calculating the number of ways to climb 2 steps. `one_before` is the number of ways to climb 1 step, and `two_before` is the number of ways to climb 0 steps (you could argue this should be 0, not 1, but for this problem we need to start with 1). So following the recursive defintion, we know that the number of ways to climb 2 steps is `one_before` + `two_before`. Then we update those two variables and continue building our solution until we reach `n`.\n\n# Dynammic Programming Solution\n```\nclass Solution:\n def climbStairs(self, n: int) -> int:\n if n == 1:\n return 1\n\n one_before = 1\n two_before = 1\n total = 0\n\n for i in range(n-1):\n total = one_before + two_before\n two_before = one_before\n one_before = total\n\n return total\n``` | 6,865 |
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 | 6,269 | 83 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires to convert a given absolute path to a simplified canonical path. The simplified canonical path should have the following format:\n- The path starts with a single slash \'/\'.\n\n- Any two directories are separated by a single slash \'/\'.\n\n- The path does not end with a trailing \'/\'.\n\n- The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period \'.\' or double period \'..\').\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem can be solved using a stack to keep track of the directories in the path. We split the input path by slash \'/\', iterate over the directories, and perform the following operations:\n\n- Ignore the current directory \'.\' and empty directories.\n- Go one level up for double period \'..\' by popping the top element from the stack if it is not empty.\n- For any other directory, push it to the stack.\n- Finally, we join the directories in the stack with slash \'/\' and add a slash at the beginning to form the simplified canonical path.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the algorithm is $$O(n)$$, where n is the length of the input path. This is because we iterate over each directory in the path only once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity of the algorithm is $$O(n)$$ where n is the length of\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 public String simplifyPath(String path) {\n Stack<String> stack = new Stack<>(); // create a stack to keep track of directories\n String[] directories = path.split("/"); // split the path by slash \'/\'\n for (String dir : directories) { // iterate over the directories\n if (dir.equals(".") || dir.isEmpty()) { // ignore the current directory \'.\' and empty directories\n continue;\n } else if (dir.equals("..")) { // go one level up for double period \'..\'\n if (!stack.isEmpty()) { // if stack is not empty, pop the top element\n stack.pop();\n }\n } else { // for any other directory, push it to the stack\n stack.push(dir);\n }\n }\n return "/" + String.join("/", stack); // join the directories in the stack with slash \'/\' and add a slash at the beginning\n }\n}\n```\n```JavaScript []\n/**\n * @param {string} path\n * @return {string}\n */\nvar simplifyPath = function(path) {\n const stack = [];\n const directories = path.split("/");\n for (const dir of directories) {\n if (dir === "." || !dir) {\n continue;\n } else if (dir === "..") {\n if (stack.length > 0) {\n stack.pop();\n }\n } else {\n stack.push(dir);\n }\n }\n return "/" + stack.join("/");\n};\n\n```\n```C++ []\nclass Solution {\npublic:\n string simplifyPath(string path) {\n stack<string> s;\n stringstream ss(path);\n string dir;\n while (getline(ss, dir, \'/\')) {\n if (dir.empty() || dir == ".") {\n continue;\n } else if (dir == "..") {\n if (!s.empty()) {\n s.pop();\n }\n } else {\n s.push(dir);\n }\n }\n string res;\n while (!s.empty()) {\n res = "/" + s.top() + res;\n s.pop();\n }\n return res.empty() ? "/" : res;\n }\n};\n\n```\n``` Python []\nclass Solution(object):\n def simplifyPath(self, path):\n stack = []\n directories = path.split("/")\n for dir in directories:\n if dir == "." or not dir:\n continue\n elif dir == "..":\n if stack:\n stack.pop()\n else:\n stack.append(dir)\n return "/" + "/".join(stack)\n\n```\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n``` | 6,939 |
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 | 11,687 | 74 | # Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Simplify Path` by `Aryan Mittal`\n![lc.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![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n string simplifyPath(string path) {\n vector<string> dirOrFiles;\n stringstream ss(path);\n string dirOrFile;\n while (getline(ss, dirOrFile, \'/\')) {\n if (!dirOrFiles.empty() && dirOrFile == "..") {\n dirOrFiles.pop_back();\n } else if (dirOrFile != "." && dirOrFile != "" && dirOrFile != "..") {\n dirOrFiles.push_back(dirOrFile);\n }\n }\n string simplified_path = "";\n for (string dirOrFile : dirOrFiles) {\n simplified_path += "/" + dirOrFile;\n }\n return simplified_path.empty() ? "/" : simplified_path;\n }\n};\n```\n```Java []\nclass Solution {\n public String simplifyPath(String path) {\n Deque<String> dirOrFiles = new ArrayDeque<>();\n for (String dirOrFile : path.split("/")) {\n if (!dirOrFiles.isEmpty() && dirOrFile.equals("..")) {\n dirOrFiles.removeLast();\n } else if (!dirOrFile.equals(".") && !dirOrFile.equals("") && !dirOrFile.equals("..")) {\n dirOrFiles.addLast(dirOrFile);\n }\n }\n StringBuilder simplified_path = new StringBuilder();\n for (String dirOrFile : dirOrFiles) {\n simplified_path.append("/").append(dirOrFile);\n }\n return simplified_path.length() == 0 ? "/" : simplified_path.toString();\n }\n}\n```\n```Python []\nclass Solution:\n def simplifyPath(self, path):\n dirOrFiles = []\n path = path.split("/")\n for elem in path:\n if dirOrFiles and elem == "..":\n dirOrFiles.pop()\n elif elem not in [".", "", ".."]:\n dirOrFiles.append(elem)\n \n return "/" + "/".join(dirOrFiles)\n```\n | 6,941 |
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 | 5,613 | 45 | # Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am Giving away my premium content videos related to computer science and data science and also will be sharing well-structured assignments and study materials to clear interviews at top companies to my first 10,000 Subscribers. 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\n# Video Solution\n\n**Search \uD83D\uDC49 `Simplify Path by Tech Wired` on YouTube**\n\n![Yellow & Black Earn Money YouTube Thumbnail (14).png]()\n\n\nHappy Learning, Cheers Guys \uD83D\uDE0A\n\n# Approach:\n\n- Initialize an empty stack to hold the directories in the simplified path.\n- Split the input path string into individual directories using the forward slash ("/") as a separator.\nFor each directory:\n- If the directory is a parent directory reference ("..") and the stack is non-empty, pop the last directory off the stack to remove the preceding directory.\n- If the directory is not a special directory reference (i.e. neither ".", "" nor ".."), append it to the stack.\n- Construct the simplified path by joining the directories in the stack with forward slashes ("/") and adding a leading forward slash ("/").\n\n\n# Intuition:\nThe problem asks us to simplify a path in the Unix-style directory format, which consists of a sequence of directory names separated by forward slashes. The path may contain special directory references, such as "." (current directory), "" (empty directory), and ".." (parent directory). We need to remove any redundant directories and parent directory references to simplify the path.\n\nTo solve the problem, we can use a stack to keep track of the directories in the simplified path. We iterate over each directory in the input path and perform the following actions:\n\n- If the directory is a parent directory reference ("..") and the stack is non-empty, we pop the last directory off the stack to remove the preceding directory.\n- If the directory is not a special directory reference, we append it to the stack.\n- We then construct the simplified path by joining the directories in the stack with forward slashes and adding a leading forward slash.\n- Using a stack allows us to keep track of the directories in the path in a last-in-first-out (LIFO) order, which is convenient for removing parent directory references. By only appending non-special directories to the stack, we can ensure that the simplified path does not contain any redundant directories or empty directory references. - Finally, joining the directories in the stack with forward slashes gives us the simplified path in the correct format.\n\n\n```Python []\nclass Solution:\n def simplifyPath(self, path):\n dir_stack = []\n path = path.split("/")\n for elem in path:\n if dir_stack and elem == "..":\n dir_stack.pop()\n elif elem not in [".", "", ".."]:\n dir_stack.append(elem)\n \n return "/" + "/".join(dir_stack)\n\n```\n```Java []\nclass Solution {\n public String simplifyPath(String path) {\n Deque<String> dir_stack = new ArrayDeque<>();\n for (String dir : path.split("/")) {\n if (!dir_stack.isEmpty() && dir.equals("..")) {\n dir_stack.removeLast();\n } else if (!dir.equals(".") && !dir.equals("") && !dir.equals("..")) {\n dir_stack.addLast(dir);\n }\n }\n StringBuilder simplified_path = new StringBuilder();\n for (String dir : dir_stack) {\n simplified_path.append("/").append(dir);\n }\n return simplified_path.length() == 0 ? "/" : simplified_path.toString();\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n string simplifyPath(string path) {\n vector<string> dir_stack;\n stringstream ss(path);\n string dir;\n while (getline(ss, dir, \'/\')) {\n if (!dir_stack.empty() && dir == "..") {\n dir_stack.pop_back();\n } else if (dir != "." && dir != "" && dir != "..") {\n dir_stack.push_back(dir);\n }\n }\n string simplified_path = "";\n for (string dir : dir_stack) {\n simplified_path += "/" + dir;\n }\n return simplified_path.empty() ? "/" : simplified_path;\n }\n};\n\n```\n![image.png]()\n\n# Please UPVOTE \uD83D\uDC4D\n\n | 6,947 |
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 | 2,539 | 27 | # Approach\n1. Create a Stack of String with following condition.\n2. Iterate the loop till you doesn\'t reaches the end of string.\n3. If you encounter a "/" then ignore it.\n4. Create a temp String & Iterate the while loop till you doesn\'t find "/" and append it to temp.\n4. Now check if temp == "." , then ignore it.\n5. If temp == ".." then pop the element from the stack if it exists.\n6. If no of the above 2 matches push temp to stack as you find a valid path.\n7. Check out temp string on basis of above conditions till you doesn\'t find "/".\n8. Now add all stack elements to result as res = "/" + st.top() + res\n9. If res.size() is 0 then return "/" if no directory or file is present.\nAt last return res.\n```\n**See This Testcase for better understanding **\ninput : "/home/../foo/" output : "/foo"\ninput : "/home/test/../foo/" output : "/home/foo"\ninput : "/home/...//foo/" output : "/home/.../foo"\n```\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n $$O(n)$$\n\n```C++ []\nclass Solution {\npublic:\nclass Solution\n{\npublic:\n string simplifyPath(string path)\n {\n\n stack<string> st;\n string res;\n\n for (int i = 0; i < path.size(); ++i)\n {\n if (path[i] == \'/\')\n continue;\n string temp;\n\n while (i < path.size() && path[i] != \'/\')\n {\n temp += path[i];\n ++i;\n }\n if (temp == ".")\n continue;\n else if (temp == "..")\n {\n if (!st.empty())\n st.pop();\n }\n else\n st.push(temp);\n }\n\n while (!st.empty())\n {\n res = "/" + st.top() + res;\n st.pop();\n }\n\n if (res.size() == 0)\n return "/";\n\n return res;\n }\n};\n```\n```Java []\nclass Solution\n{\npublic\n String simplifyPath(String path)\n {\n Stack<String> stack = new Stack<>(); \n String[] directories = path.split("/"); \n for (String dir : directories)\n { \n if (dir.equals(".") || dir.isEmpty())\n { \n continue;\n }\n else if (dir.equals(".."))\n { \n if (!stack.isEmpty())\n { \n stack.pop();\n }\n }\n else\n { \n stack.push(dir);\n }\n }\n return "/" + String.join("/", stack); \n }\n}\n```\n```python []\nclass Solution(object):\n def simplifyPath(self, path):\n stack = []\n directories = path.split("/")\n for dir in directories:\n if dir == "." or not dir:\n continue\n elif dir == "..":\n if stack:\n stack.pop()\n else:\n stack.append(dir)\n return "/" + "/".join(stack)\n```\n![Screenshot 2023-04-12 at 11.31.36 AM.png]()\n | 6,956 |
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 | 1,303 | 5 | # Code\n```\nclass Solution:\n def simplifyPath(self, path: str) -> str:\n return __import__(\'os\').path.abspath(path)\n``` | 6,979 |