question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spiral-matrix-ii | Java | Simulation | Beats 100% | 15 lines | java-simulation-beats-100-15-lines-by-ju-a6a9 | Complexity\n- Time complexity: O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n^2)\n Add your space complexity here, e.g. O(n) \n\n | judgementdey | NORMAL | 2023-05-10T05:48:38.589696+00:00 | 2023-05-10T20:29:29.715228+00:00 | 393 | false | # Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int x = 0, y = -1, cnt = 1;\n var xMoves = new int[] {n};\n var yMoves = new int[] {n+1};\n var mat = new int[n][n];\n\n for (var d = 0; cnt <= n*n; d = (d+1) % 4) {\n var moves = d % 2 == 0 ? yMoves : xMoves;\n moves[0]--;\n\n for (var i = 0; i < moves[0]; i++) {\n switch(d) {\n case 0 : y++; break;\n case 1 : x++; break;\n case 2 : y--; break;\n case 3 : x--; break;\n }\n mat[x][y] = cnt++;\n }\n }\n return mat;\n }\n}\n```\nIf you like my solution, please upvote it! | 5 | 0 | ['Matrix', 'Simulation', 'Java'] | 0 |
spiral-matrix-ii | Easy JAVA Code || Beats 100% | easy-java-code-beats-100-by-ayush__jain-drsi | \nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] ans = new int[n][n];\n //right -> bottom -> left -> top\n int top | Ayush__jain | NORMAL | 2023-05-10T04:10:50.831911+00:00 | 2023-05-10T04:12:52.998948+00:00 | 865 | false | ```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] ans = new int[n][n];\n //right -> bottom -> left -> top\n int top = 0, left = 0;\n int bottom = n-1, right = n-1;\n int k = 1;\n while(top<=bottom && left<=right){\n //right\n for(int i=left;i<=right;i++){\n ans[top][i] = k++ ;\n }\n top++;\n //bottom\n for(int i=top;i<=bottom;i++){\n ans[i][right] = k++;\n }\n right--;\n if(top<=bottom){\n //left\n for(int i=right;i>=left;i--){\n ans[bottom][i] = k++;\n }\n bottom--;\n }\n if(left<=right){\n //top\n for(int i=bottom;i>=top;i--){\n ans[i][left] = k++;\n } \n left++;\n }\n \n }\n \n return ans;\n \n }\n}\n``` | 5 | 0 | ['Array', 'Matrix', 'Java'] | 0 |
spiral-matrix-ii | Javascript || Easy to understand || Intuition Explained | javascript-easy-to-understand-intuition-2kepc | Intuition -> This problem is similar to Spiral matrix I in which we take 4 pointers and move them as per the condition, in this problem the pointer part in same | jitendra_jaria | NORMAL | 2022-04-13T05:36:33.665993+00:00 | 2022-04-13T05:45:54.222818+00:00 | 732 | false | **Intuition** -> This problem is similar to [Spiral matrix I](https://leetcode.com/problems/spiral-matrix/) in which we take 4 pointers and move them as per the condition, in this problem the pointer part in same only thing that has been changed is how many times the outer loop will run and how efficiently we can manage , below is the code hope it helps.\n```\nvar generateMatrix = function(n) {\n let c1=0;\n let c2=n-1;\n let r1=0;\n let r2=n-1;\n \n let arr=Array.from(Array(n),()=>Array(n));\n let i=1;\n while(i<=n*n){\n \n for(let c=c1;c<=c2;c++){\n arr[r1][c]=i;\n i++;\n }\n r1++;\n for(let r=r1;r<=r2;r++){\n arr[r][c2]=i;\n i++;\n }\n c2--;\n for(let c=c2;c>=c1;c--){\n arr[r2][c]=i;\n i++;\n }\n r2--;\n for(let r=r2;r>=r1;r--){\n arr[r][c1]=i;\n i++;\n }\n c1++; \n }\n return arr;\n};\n```\n\n***Please upvote if you like the solution \uD83D\uDE80*** | 5 | 0 | ['Array', 'JavaScript'] | 0 |
spiral-matrix-ii | Java | Simple | Reuse LC 54 | java-simple-reuse-lc-54-by-prashant404-aoyz | Idea: \n This question is near identical to LC 54. Spiral Matrix and the solution can be reused. \n Fill the matrix in this order: First Row \u279D Last Column | prashant404 | NORMAL | 2022-04-13T01:50:36.781158+00:00 | 2023-05-10T18:02:26.662355+00:00 | 589 | false | **Idea:** \n* This question is near identical to [LC 54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/discuss/3502622/Java-or-Simple-or-Explained) and the solution can be reused. \n* Fill the matrix in this order: First Row \u279D Last Column \u279D Last Row \u279D First Column\n* Repeat till a cross-over happends between rows or columns\n>**T/S:** O(n\xB2)/O(1)\n```\npublic int[][] generateMatrix(int n) {\n\tvar matrix = new int[n][n];\n\tvar firstRow = 0;\n\tvar firstCol = 0;\n\tvar lastRow = n - 1;\n\tvar lastCol = n - 1;\n\tvar x = 1;\n\n\twhile (firstRow <= lastRow && firstCol <= lastCol) {\n\t\t// first row\n\t\tfor (var j = firstCol; j <= lastCol; j++)\n\t\t\tmatrix[firstRow][j] = x++;\n\t\tfirstRow++;\n\n\t\t// last col\n\t\tfor (var i = firstRow; i <= lastRow; i++)\n\t\t\tmatrix[i][lastCol] = x++;\n\t\tlastCol--;\n\n\t\tif (firstRow > lastRow || firstCol > lastCol)\n\t\t\tbreak;\n\n\t\t// last row\n\t\tfor (var j = lastCol; j >= firstCol; j--)\n\t\t\tmatrix[lastRow][j] = x++;\n\t\tlastRow--;\n\n\t\t// first col\n\t\tfor (var i = lastRow; i >= firstRow; i--)\n\t\t\tmatrix[i][firstCol] = x++;\n\t\tfirstCol++;\n\t}\n\n\treturn matrix;\n}\n```\n***Please upvote if this helps*** | 5 | 0 | ['Java'] | 0 |
spiral-matrix-ii | [Golang] simple solution with rotation | golang-simple-solution-with-rotation-by-o88ss | We basically need to walk through the matrix, changing direction if we either a) got out of bounds, or b) got previously filled cell.\n\ngo\nfunc generateMatrix | oizg | NORMAL | 2022-04-13T00:10:25.697707+00:00 | 2022-04-13T00:10:25.697750+00:00 | 626 | false | We basically need to walk through the matrix, changing direction if we either a) got out of bounds, or b) got previously filled cell.\n\n```go\nfunc generateMatrix(n int) [][]int {\n res := make([][]int, n)\n for i := 0; i < n; i++ { res[i] = make([]int, n) }\n \n dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}\n \n i, j, d := 0, 0, 0 \n for k := 1; k <= n*n; k++ {\n res[i][j] = k\n \n di, dj := dirs[d%4][0], dirs[d%4][1]\n if i+di < 0 || i+di >= n || j+dj < 0 || j+dj >= n || res[i+di][j+dj] != 0 {\n d++\n di, dj = dirs[d%4][0], dirs[d%4][1]\n }\n \n i, j = i+di, j+dj\n }\n \n return res\n}\n``` | 5 | 0 | ['Go'] | 0 |
spiral-matrix-ii | Spiral Matrix II | Python | O(n2) | Simple Offset | spiral-matrix-ii-python-on2-simple-offse-csx1 | The following solution keeps track of an x-y position (location in the resulting array) and an offset (used to move spiral toward the center).\n\n\nclass Soluti | alpeople | NORMAL | 2020-12-08T00:59:43.747746+00:00 | 2020-12-08T00:59:52.977344+00:00 | 583 | false | The following solution keeps track of an x-y position (location in the resulting array) and an offset (used to move spiral toward the center).\n\n```\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n spiral = [[0]*n for i in range(n)]\n x, y, off = 0, 0, 0\n \n for i in range(1, n*n +1):\n spiral[y][x] = i\n \n if x == (n-1-off) and y < (n-1-off): y += 1 # Right Edge\n elif y == (n-1-off) and x > off: x -=1 # Bottom Edge\n elif x == off and y > off: # Left Edge\n y -= 1\n if y == off+1: off += 1\n else: x += 1 # Top Edge\n\n return spiral\n```\n\nThe above solution runs in *`O(n2)`* time. \nThe above solution takes *`O(n2)`* space. | 5 | 0 | ['Python'] | 1 |
spiral-matrix-ii | [C++] Simulation: self-explained without comment | c-simulation-self-explained-without-comm-j3pb | \nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n, vector<int>(n));\n int begX = 0, endX = | codedayday | NORMAL | 2020-12-07T16:20:46.558703+00:00 | 2020-12-07T16:20:46.558736+00:00 | 235 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n, vector<int>(n));\n int begX = 0, endX = n - 1;\n int begY = 0, endY = n - 1;\n int counter = 0;\n while(true){\n for(int j = begX; j <= endX; j++) ans[begY][j] = ++counter;\n if(++begY>endY) break;\n for(int j = begY; j <= endY; j++) ans[j][endX] = ++counter;\n if(begX>--endX) break;\n for(int j = endX; j >= begX; j--) ans[endY][j] = ++counter;\n if(begY>--endY) break;\n for(int j = endY; j >= begY; j--) ans[j][begX] = ++counter;\n if(++begX>endY) break;\n }\n return ans;\n }\n};\n``` | 5 | 0 | [] | 1 |
spiral-matrix-ii | C++ #minimalizm | c-minimalizm-by-votrubac-7om9 | Track the direction (left, down, right, and up). When your next position is out of bouds, or there is already a number, we change the direction.\n\ncpp\nint ds[ | votrubac | NORMAL | 2020-03-27T06:31:20.820066+00:00 | 2020-03-27T07:05:23.718595+00:00 | 147 | false | Track the direction (left, down, right, and up). When your next position is out of bouds, or there is already a number, we change the direction.\n\n```cpp\nint ds[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};\nvector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> res(n, vector<int>(n));\n for (auto i = 0, j = 0, k = 1, d = 0; k <= n * n; i += ds[d][0], j += ds[d][1]) {\n res[i][j] = k++;\n auto ni = i + ds[d][0], nj = j + ds[d][1];\n if (ni < 0 || ni == n || nj < 0 || nj == n || res[ni][nj] != 0)\n d = (++d) % 4;\n }\n return res;\n}\n``` | 5 | 0 | [] | 0 |
spiral-matrix-ii | Clean JavaScript solution | clean-javascript-solution-by-hongbo-miao-w0tx | Reference from a similar question https://leetcode.com/problems/spiral-matrix/discuss/20573/A-concise-C++-implementation-based-on-Directions\n\n\n// When traver | hongbo-miao | NORMAL | 2019-10-19T20:48:27.234523+00:00 | 2020-09-02T15:44:16.270200+00:00 | 1,507 | false | Reference from a similar question https://leetcode.com/problems/spiral-matrix/discuss/20573/A-concise-C++-implementation-based-on-Directions\n\n```\n// When traversing the matrix in the spiral order, at any time we follow one out of the following four directions:\n// RIGHT DOWN LEFT UP. Suppose we are working on a 5 x 3 matrix as such:\n// 0 1 2 3 4 5\n// 6 7 8 9 10\n// 11 12 13 14 15\n//\n// Imagine a cursor starts off at (0, -1), i.e. the position at \'0\', then we can achieve the spiral order by doing\n// the following:\n// 1. Go right 5 times\n// 2. Go down 2 times\n// 3. Go left 4 times\n// 4. Go up 1 times.\n// 5. Go right 3 times\n// 6. Go down 0 times -> quit\n\nconst generateMatrix = (n) => {\n const matrix = [...Array(n)].map(() => Array(n).fill(null));\n const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up\n const steps = [n, n - 1];\n\n let num = 1;\n let dir = 0;\n let x = 0;\n let y = -1;\n\n while (steps[dir % 2] > 0) {\n for (let i = 0; i < steps[dir % 2]; i++) {\n x += dirs[dir][0];\n y += dirs[dir][1];\n matrix[x][y] = num++;\n }\n\n steps[dir % 2]--;\n dir = (dir + 1) % 4;\n }\n return matrix;\n};\n```\n | 5 | 0 | ['JavaScript'] | 3 |
spiral-matrix-ii | (( Swift )) Beating All ((Linear Solution)) [[KewL LewpZ]] ((Hacker Rank)) Scared Money | swift-beating-all-linear-solution-kewl-l-64fg | \nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n \n var m = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)\n | nraptis | NORMAL | 2019-06-11T03:39:21.320626+00:00 | 2019-06-11T03:39:21.320665+00:00 | 146 | false | ```\nclass Solution {\n func generateMatrix(_ n: Int) -> [[Int]] {\n \n var m = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)\n \n var l = 0, r = n - 1, t = 0, b = n - 1, x = 0, y = 0, val = 1\n \n while t <= b {\n \n x = l; y = t\n while x <= r { m[t][x] = val; val += 1; x += 1 }\n \n t += 1; y = t\n while y <= b { m[y][r] = val; val += 1; y += 1 }\n \n r -= 1; x = r\n while x >= l { m[b][x] = val; val += 1; x -= 1 }\n \n b -= 1; y = b\n while y >= t { m[y][l] = val; val += 1; y -= 1 }\n \n l += 1\n }\n \n return m\n }\n}\n```\n\nBig big big big big big big big man. | 5 | 1 | [] | 0 |
spiral-matrix-ii | A Better Solution than Switching Directions | a-better-solution-than-switching-directi-8n55 | Rotate the Matrix is more easier :)\n\n\tpublic class Solution {\n\t\tint[][] step = {{0,1},{1,0},{0,-1},{-1,0}};\n\t\tint cnt = 1;\n\t\tvoid vortex(int[][] res | blue_y | NORMAL | 2014-09-26T09:59:36+00:00 | 2014-09-26T09:59:36+00:00 | 1,836 | false | Rotate the Matrix is more easier :)\n\n\tpublic class Solution {\n\t\tint[][] step = {{0,1},{1,0},{0,-1},{-1,0}};\n\t\tint cnt = 1;\n\t\tvoid vortex(int[][] res, int len, int wid, int x, int y, int sg){\n\t\t\tif(len == 0) return;\n\t\t\tfor(int i = 0; i < len; ++i){\n\t\t\t\tx += step[sg][0];\n\t\t\t\ty += step[sg][1];\n\t\t\t\tres[x][y] = cnt++;\n\t\t\t}\n\t\t\tsg = (sg+1)%4;\n\t\t\tvortex(res,--wid,len, x, y, sg);\n\t\t}\n\t public int[][] generateMatrix(int n) {\n\t int[][] res = new int[n][n];\n\t vortex(res,n,n,0,-1,0);\n\t return res;\n\t }\n\t} | 5 | 0 | ['Java'] | 2 |
spiral-matrix-ii | ✅100%RUNTIME | 95.96%MEMORY | Easiest & Standard Intuition and traversalal | TimeO(N^2) | Space O(1) | 100runtime-9596memory-easiest-standard-i-thz8 | optimal solution for the spiral traversal in a matrix🧠 IntuitionWe need to generate an n x n matrix filled with numbers from 1 to n^2 in a spiral order 🌀.To ach | himanshukansal101 | NORMAL | 2025-02-27T21:15:24.740878+00:00 | 2025-02-27T21:15:24.740878+00:00 | 481 | false | # optimal solution for the spiral traversal in a matrix
# 🧠 Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need to generate an n x n matrix filled with numbers from 1 to n^2 in a spiral order 🌀.
To achieve this, we can divide the problem into four movement directions:
1️⃣ Left → Right (Top Row)
2️⃣ Top → Bottom (Rightmost Column)
3️⃣ Right → Left (Bottom Row)
4️⃣ Bottom → Top (Leftmost Column)
We maintain boundaries (top, bottom, left, right) to ensure we don’t overwrite previously filled numbers.
# 🚀 Approach
<!-- Describe your approach to solving the problem. -->
1️⃣ Initialize a n x n matrix with zeros.
2️⃣ Define boundaries:
top = 0, bottom = n - 1
left = 0, right = n - 1
3️⃣ Use a counter cnt starting from 1 up to n^2.
4️⃣ Iterate in four directions:
Move left to right ➡️ along the top row.
Move top to bottom ⬇️ along the right column.
Move right to left ⬅️ along the bottom row (if applicable).
Move bottom to top ⬆️ along the left column (if applicable).
5️⃣ Update boundaries after each traversal to avoid overwriting.
6️⃣ Continue until all numbers are filled.
# Complexity
- Time complexity:O(n^2)🕒 (Each element is filled exactly once.)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1) 📦 (Only the result matrix is used, no extra space.)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# 🎉 Summary
✅ Used boundaries to control matrix filling.
✅ Traversed in four directions to maintain a spiral order.
✅ Optimized with O(n^2)time and O(1) extra space.
This is an efficient and elegant solution for generating a spiral matrix! 🔥🚀


# Code
```cpp []
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>ans(n,vector<int>(n,0));
int top = 0;
int bottom = n-1;
int left = 0;
int right = n-1;
int cnt = 1;
while(top<=bottom && left<=right){
for(int i=left;i<=right;i++){
ans[top][i] = cnt++;
}
top++;
for(int i=top;i<=bottom;i++){
ans[i][right] = cnt++;
}
right--;
if(top<=bottom){
for(int i=right;i>=left;i--){
ans[bottom][i] = cnt++;
}
bottom--;
}
if(left<=right){
for(int i=bottom;i>=top;i--){
ans[i][left] = cnt++;
}
left++;
}
}
return ans;
}
};
``` | 4 | 0 | ['C++'] | 0 |
spiral-matrix-ii | 0 ms || Beats 100% || Easy to understand || C++ | 0-ms-beats-100-easy-to-understand-c-by-h-swzv | Intuition\n Describe your first thoughts on how to solve this problem. \nThe generateMatrix function creates an n x n matrix filled with numbers from 1 to n^2 i | hardik-chauhan | NORMAL | 2024-08-08T10:54:05.080468+00:00 | 2024-08-08T10:54:05.080487+00:00 | 285 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe generateMatrix function creates an n x n matrix filled with numbers from 1 to n^2 in a spiral order. It starts at the top-left corner of the matrix and moves right across the top row, then down the rightmost column, then left across the bottom row, and finally up the leftmost column. After completing one loop around the perimeter, the process continues inward until the entire matrix is filled. The function uses boundaries (top, bottom, left, right) to keep track of where to fill next, ensuring that all positions are visited in a spiral sequence.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMatrix Initialization:\n\nStart by creating an empty n x n matrix filled with zeros or uninitialized values. This matrix will be filled with numbers from 1 to n^2.\nBoundary Pointers:\n\nUse four pointers: top, bottom, left, and right to keep track of the current boundaries of the matrix that need to be filled.\nInitialize top = 0, bottom = n - 1, left = 0, and right = n - 1.\nFilling the Matrix in Spiral Order:\n\nTop Row: Traverse from left to right along the top row and fill the elements. After filling, increment the top pointer (top++) to move the boundary inward.\nRight Column: Traverse from top to bottom along the rightmost column and fill the elements. Then, decrement the right pointer (right--) to move the boundary inward.\nBottom Row: If there are rows left to process (top <= bottom), traverse from right to left along the bottom row and fill the elements. Decrement the bottom pointer (bottom--) afterward.\nLeft Column: If there are columns left to process (left <= right), traverse from bottom to top along the leftmost column and fill the elements. Increment the left pointer (left++) afterward.\nRepeat Until Complete:\n\nContinue the process of filling the matrix while updating the boundary pointers until all elements from 1 to n^2 are placed in the matrix.\nReturn the Matrix:\n\nOnce the entire matrix is filled, return it as the result.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n if(n<=0) return {};\n vector<vector<int>> matrix(n,vector<int> (n));\n int num=1;\n int top=0,bottom=n-1,left=0,right=n-1;\n while(top<=bottom && left<=right){\n //for top row\n for(int i=left;i<=right;i++){\n matrix[top][i]=num++;\n }\n top++;\n // for right column\n for(int i=top;i<=bottom;i++){\n matrix[i][right]=num++;\n }\n right--;\n //for bottom row\n if(top<=bottom){\n for(int i=right;i>=left;i--){\n matrix[bottom][i]=num++;\n }\n bottom--;\n }\n //for left column \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``` | 4 | 0 | ['C++'] | 1 |
spiral-matrix-ii | Spiral Matrix II - Java Solution (Beats 100%) | spiral-matrix-ii-java-solution-beats-100-oe09 | Intuition\n Describe your first thoughts on how to solve this problem. \nMy intuition for generating the matrix in spiral order involves systematically filling | Naveen-NaS | NORMAL | 2024-01-06T15:41:27.528244+00:00 | 2024-01-17T12:22:37.269722+00:00 | 573 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy intuition for generating the matrix in spiral order involves systematically filling each side of the current spiral boundary by iteratively moving in the top, right, bottom, and left directions. The approach ensures that each element is visited and assigned a value in a sequential manner, covering the entire matrix without missing or revisiting any elements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach involves simulating the process of traversing a matrix in a spiral order by iteratively filling its elements while adjusting the boundaries for each side of the current spiral. Following Steps are :\n- Initialize an empty matrix of size n x n, where n is the given positive integer.\n- Initialize a variable num to keep track of the values to be filled in the matrix, starting from 1.\n- Initialize four variables top, bottom, left, and right to represent the boundaries of the current spiral.\n- Iterate through the matrix in a spiral order, filling in the values as you go.\n\nFor better understanding you can also see my solution for similar problem of this i.e. Problem No. 54 "Spiral Matrix" - [https://leetcode.com/problems/spiral-matrix/solutions/4055455/spiral-matrix-java-solution-beats-100]()\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of your code is **O(n^2)**, where n is the size of the matrix. This is because we visit each cell in the matrix exactly once during the process of filling it in a spiral order.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is **O(n^2)**, as we are using a 2D Array and other varaible uses constant space.\n# Code\n```\nclass Solution {\n public int[][] generateMatrix(int n) {\n int[][] matrix = new int[n][n];\n int num = 1;\n int top = 0, bottom = n - 1, left = 0, right = n - 1;\n\n while (top <= bottom && left <= right) {\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``` | 4 | 0 | ['Java'] | 3 |
spiral-matrix-ii | Beats 100% || Easiest Approach | beats-100-easiest-approach-by-rishi_2330-s9fk | 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 | Rishi_2330 | NORMAL | 2024-01-01T18:03:35.361353+00:00 | 2024-01-01T18:05:07.333535+00:00 | 31 | false | # 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:\nO(n*n)\n\n- Space complexity:\nO(n*n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> arr(n, vector<int>(n, 0));\n int minRow = 0;\n int maxRow = n-1;\n int minCol = 0;\n int maxCol = n-1;\n\n int count = 1;\n while(count<=n*n){\n for(int c=minCol ; c<=maxCol ; c++){\n arr[minRow][c] = count++;\n }\n for(int r=minRow + 1 ; r<=maxRow ; r++){\n arr[r][maxCol] = count++;\n }\n for(int c=maxCol - 1; c>=minCol ; c--){\n arr[maxRow][c] = count++;\n }\n for(int r=maxRow - 1; r>minRow; r--){\n arr[r][minCol] = count++;\n }\n minRow++;\n maxRow--;\n minCol++;\n maxCol--;\n }\n return arr;\n }\n};\n``` | 4 | 0 | ['Math', 'Matrix', 'C++'] | 1 |
spiral-matrix-ii | Best O(N^2) Solution | best-on2-solution-by-kumar21ayush03-k9u6 | Approach\nTraversal\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>> gen | kumar21ayush03 | NORMAL | 2023-09-24T09:55:09.972363+00:00 | 2023-09-24T09:55:09.972383+00:00 | 842 | false | # Approach\nTraversal\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> mat (n, vector<int>(n));\n int num = 1;\n int r1 = 0, r2 = n - 1, c1 = n - 1, c2 = 0;\n while (num <= n * n) {\n for (int i = r1; i <= r2; i++) {\n mat[r1][i] = num;\n num++;\n }\n r1++;\n for (int i = c2 + 1; i <= c1; i++) {\n mat[i][c1] = num;\n num++;\n }\n c1--;\n for (int i = r2 - 1; i >= r1 - 1; i--) {\n mat[r2][i] = num;\n num++;\n }\n r2--;\n for (int i = c1; i >= c2 + 1; i--) {\n mat[i][c2] = num;\n num++;\n }\n c2++;\n }\n return mat;\n }\n};\n``` | 4 | 0 | ['C++'] | 1 |
spiral-matrix-ii | beats 100% || beginner friendly | beats-100-beginner-friendly-by-wtfcoder-oqt5 | Intuition\n Describe your first thoughts on how to solve this problem. \ntraverse through matrix hit right when you hit a visited node or go out of limits. brea | wtfcoder | NORMAL | 2023-06-18T11:59:15.259891+00:00 | 2023-06-18T11:59:15.259914+00:00 | 25 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ntraverse through matrix hit right when you hit a visited node or go out of limits. break when count goes to n^2 +1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nmaintain n*n matrix. change direction when you hit a visited node or go out of limits. increment count after every insertion \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N2)\n\nPlease upvote if you find it helpful \n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n vector<vector<int>> visited(n, vector<int>(n, 0)); int c = 1; \n vector<vector<int>> res(n, vector<int>(n, 0)); int x = 0; int y = 0; char d = \'r\'; \n while( c != n*n+1){\n if(d == \'r\'){\n res[x][y] = c; visited[x][y] = 1; y++; c++; \n if(y>=n||visited[x][y] == 1) {y--; x++; d = \'d\'; continue; }\n }\n else if(d == \'d\'){\n res[x][y] = c; visited[x][y] = 1; x++; c++; \n if(x>=n || visited[x][y] == 1) {x--; y--; d = \'l\'; continue; }\n }\n else if(d == \'l\'){\n res[x][y] = c; visited[x][y] = 1; y--; c++;\n if(y<0 || visited[x][y] == 1) { y++; x--; d = \'u\'; continue; }\n }\n else if(d == \'u\'){\n res[x][y] = c; visited[x][y] = 1; x--; c++;\n if(x<0 || visited[x][y] == 1) {x++; y++; d = \'r\'; continue; }\n }\n }\n\n // cout << x << y << d ; \n\n return res; \n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
spiral-matrix-ii | C++|| Beats 100% || Easy || Like if it helps you || Fast || | c-beats-100-easy-like-if-it-helps-you-fa-23re | Intuition\n Describe your first thoughts on how to solve this problem. \nMatrix Simulation type question.\n# Approach\n Describe your approach to solving the pr | iamshreyash28 | NORMAL | 2023-05-10T11:13:57.888377+00:00 | 2023-05-13T20:46:05.558293+00:00 | 25 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMatrix Simulation type question.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n#Define a N*N vector initiated with value 0. And then move forward in the matrix in the directions of top->bottom, right->left, left->right, bottom->top. \n\n#The loop runs till we reach number limit of n^2. \n\n#Looking for openions for optimizing my solution.\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> grid(n, vector<int> (n,0));\n int dir=1;\n int num=1;\n int top=0,bottom=n-1,right=n-1,left=0;\n while(num<=pow(n,2))\n {\n if(dir==1)\n {\n for(int i=left;i<=right;i++)\n {\n grid[top][i]=num;\n num++;\n }\n top++;\n dir=2;\n }\n\n else if(dir==2)\n {\n for(int i=top;i<=bottom;i++)\n {\n grid[i][right]=num;\n num++;\n }\n right--;\n dir=3;\n }\n else if(dir==3)\n {\n for(int i=right;i>=left;i--)\n {\n grid[bottom][i]=num;\n num++;\n }\n bottom--;\n dir=4;\n }\n\n else if(dir==4)\n {\n for(int i=bottom;i>=top;i--)\n {\n grid[i][left]=num;\n num++;\n }\n left++;\n dir=1;\n }\n }\n return grid;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
spiral-matrix-ii | [Kotlin][2D Array] EASY solution with GREAT explanation! | kotlin2d-array-easy-solution-with-great-xjh3d | Intuition\nI solved this task yesterday lol, i just need to advance it :)\n\n# Approach\nSo, we need to initialize n * n matrix/grid with zeroes on each positio | 4wl2d | NORMAL | 2023-05-10T09:41:40.150180+00:00 | 2023-05-10T09:42:00.791482+00:00 | 1,182 | false | # Intuition\nI solved this task yesterday lol, i just need to advance it :)\n\n# Approach\nSo, we need to initialize `n * n` matrix/grid with zeroes on each position(which is our result, we need to edit this matrix/grid)\n\nNext we need to declare `direction` variable, which is equal to `\'R\'`, because start direction is `"Right"`.\n\nAfter that we can declare our borders on each side:\n`borderLeft`, `borderUp` and etc.\nNotice, that `borderUp` is equal to 1, because on start we already fill first line, so we need to move border.\n\nI used to `matrix[i][j]`, so i created iterables `i` which is a **Column**, and `j` which is a **Row**!\n\nNow we can start to travel in Matrix from `0` to `n * n` because we need to fill each cell from `1` to `n * n`, so in each step we are going to `matrix[i][j] = k + 1`(we could start from `1` to `n * n + 1`, because `until` works like: `1 <= until < (n * n + 1)`).\n\nI hope you understand =)\nLet\'s continue!\n\nIn Kotlin we have `when` statement, it\'s equals to `switch`, but in my opinion much better :)\nWe could do `when (direction) { /* TODO */ }`, but if we needed to write some `if` statements in `when` -> we can\'t use mentioned before expression.\n\nWe\'ll use `when` statement to check `direction` each time we go to somewhere. And so, if `direction == \'R\'`, we are going to move to the right with `j`(like `matrix[i][j++]`). And each time we are checking if we contact the `border` with `j`, if we contacted -> we are switching our direction according to statement to `\'D\'` and decrease possible `border`.\n\nNow we need to do the same with all directions. After `for` just return our edited matrix :)\n\n**If u liked my explanation please vote for this solution, its important to me!**\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```kotlin []\nclass Solution {\n fun generateMatrix(n: Int): Array<IntArray> {\n var matrix = Array(n) { IntArray(n) }\n var direction = \'R\'\n var borderLeft = 0\n var borderRight = n - 1\n var borderUp = 1\n var borderDown = n - 1\n var i = 0\n var j = 0\n for (k in 0 until n * n) {\n matrix[i][j] = k + 1\n when {\n direction == \'R\' -> {\n j++\n if (j == borderRight) {\n direction = \'D\'\n borderRight--\n }\n }\n direction == \'D\' -> {\n i++\n if (i == borderDown) {\n direction = \'L\'\n borderDown--\n }\n }\n direction == \'L\' -> {\n j--\n if (j == borderLeft) {\n direction = \'U\'\n borderLeft++\n }\n }\n direction == \'U\' -> {\n i--\n if (i == borderUp) {\n direction = \'R\'\n borderUp++\n }\n }\n }\n }\n return matrix\n }\n}\n``` | 4 | 0 | ['Array', 'Matrix', 'Kotlin'] | 0 |
spiral-matrix-ii | C++ || EASY TO UNDERSTAND || MATRIX | c-easy-to-understand-matrix-by-ganeshkum-ripp | sr : starting of row\ner : end of row\nsc : starting of row\nec : end of columns\n\n{first traverse first row increment starting row by one\nsecond traversal fo | ganeshkumawat8740 | NORMAL | 2023-05-10T05:33:53.757124+00:00 | 2023-05-10T05:33:53.757162+00:00 | 1,188 | false | sr : starting of row\ner : end of row\nsc : starting of row\nec : end of columns\n\n{first traverse first row increment starting row by one\nsecond traversal for insert last columns decrement last columns by 1\nthird time insert last row decrement last row by one\nfourth time insert first row increment 1st column by row}\nrepeat these all four steps untill sr <= er && sc <= ec.\n\n# Complexity\n- Time complexity:\nO(n*n)\n\n- Space complexity:\nO(n*n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int sr = 0, sc = 0, er = n-1,ec = n-1,x=1,i;\n vector<vector<int>> v(n,vector<int>(n));\n while(sr<=er && sc <= ec){\n for(i = sc; i <= ec && sr<=er; i++){\n v[sr][i] = x++;\n }\n sr++;\n for(i = sr; i <= er && sc<=ec; i++){\n v[i][ec] = x++;\n }\n ec--;\n for(i = ec; i >= sc && sr<=er; i--){\n v[er][i] = x++;\n }\n er--;\n for(i = er; i >= sr && sc<=ec; i--){\n v[i][sc] = x++;\n }\n sc++;\n }\n return v;\n }\n};\n``` | 4 | 0 | ['Array', 'Matrix', 'C++'] | 0 |
spiral-matrix-ii | 🔥C++ ✅✅ Best Solution ( 🔥 O(N*N) 🔥 ) Easy to Understand💯💯 ⬆⬆⬆ | c-best-solution-onn-easy-to-understand-b-kq7m | # Intuition \n\n\n# Approach\n\nHere we have total nn element for making nn matrix in spiral order.\nSo we can follow this 4 step\n\nStep-1 : printing the sta | Sandipan58 | NORMAL | 2023-05-10T02:23:14.127816+00:00 | 2023-05-10T02:23:14.127899+00:00 | 777 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere we have total n*n element for making n*n matrix in spiral order.\nSo we can follow this **4 step**\n\n***Step-1*** : printing the starting row\n***Step-2*** : printing the ending column\n***Step-3*** : printing the ending row\n***Step-4*** : printing the starting column\n\n# Dry Run\nlet n=3\nSo we have total 3*3 = 9 elements\ninitial our matrix is : \n>0 0 0\n0 0 0\n0 0 0\n\n**step-1:** *starting row*\n>1 2 3\n0 0 0\n0 0 0\n\n**step-2:** *ending column*\n>1 2 3\n0 0 4\n0 0 5\n\n**step-3:** *ending row*\n>1 2 3\n0 0 4\n7 6 5\n\n**step-4:** *starting column*\n>1 2 3\n8 0 4\n7 6 5\n\n**HERE 4 STEP IS COMPLETED BUT THE MATRIX IS NOT FILLED BY N*N ELEMENTS SO WE HAVE TO REPET THIS 4 STAPES AGAIN WHILE THERE IS LESS THEN N*N ELEMENTS**\n\n**step-1:** *starting row*\n>1 2 3\n8 9 4\n7 6 5\nThis is our answer\n\n# Complexity\n- Time complexity: $$O(n*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n, vector<int>(n));\n int srow = 0, erow = n-1, scol = 0, ecol = n-1, element = 1, total = n*n;\n while(element <= total) {\n // step-1 : starting row\n for(int i=scol; i<=ecol && element<=total; i++) {\n ans[srow][i] = element++;\n }\n srow++;\n\n // step-2 : ending column\n for(int i=srow; i<=erow && element<=total; i++) {\n ans[i][ecol] = element++;\n }\n ecol--;\n\n // step-3 : ending row\n for(int i=ecol; i>=scol && element<=total; i--) {\n ans[erow][i] = element++;\n }\n erow--;\n\n // step-4 : starting column\n for(int i=erow; i>=srow && element<=total; i--) {\n ans[i][scol] = element++;\n }\n scol++;\n }\n\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Interactive', 'C++'] | 0 |
spiral-matrix-ii | ✔ [C++ / Python3] Solution | Clean & Concise | c-python3-solution-clean-concise-by-saty-d5pb | Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(n^2)\n\n# Code\ncpp []\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\ | satyam2001 | NORMAL | 2023-01-30T12:18:26.088214+00:00 | 2023-01-30T12:18:59.135044+00:00 | 691 | false | # Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n^2)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> M(n, vector<int>(n));\n int val = 1;\n for(int i = 0; i < (n + 1) / 2; i++) {\n for(int j = i; j < n - i; j++) M[i][j] = val++;\n for(int j = i + 1; j < n - i; j++) M[j][n - i - 1] = val++;\n for(int j = n - i - 2; j >= i; j--) M[n - i - 1][j] = val++;\n for(int j = n - i - 2; j > i; j--) M[j][i] = val++;\n }\n return M;\n }\n};\n```\n```python []\nclass Solution:\n def generateMatrix(self, n):\n M = [[0] * n for _ in range(n)]\n val = 0\n for i in range((n + 1) // 2):\n for j in range(i, n - i): M[i][j] = (val := val + 1)\n for j in range(i + 1, n - i): M[j][n - i - 1] = (val := val + 1)\n for j in range(n - i - 2, i - 1, -1): M[n - i - 1][j] = (val := val + 1)\n for j in range(n - i - 2, i, -1): M[j][i] = (val := val + 1)\n return M\n```\n | 4 | 0 | ['Matrix', 'Python', 'C++', 'Python3'] | 1 |
spiral-matrix-ii | ✔ C++ simple and concise solution || 0ms || 100% faster | c-simple-and-concise-solution-0ms-100-fa-rv6l | \nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n,vector<int>(n,0));\n int strow=0,endrow=n | vikas__6511 | NORMAL | 2022-08-08T14:18:57.572277+00:00 | 2022-08-08T14:18:57.572302+00:00 | 59 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> ans(n,vector<int>(n,0));\n int strow=0,endrow=n-1,stcol=0,endcol=n-1;\n int val=1;\n while(strow<=endrow && stcol<=endcol ){\n //first row\n for(int i= stcol; i<=endcol; ans[strow][i++]=val++);\n strow++;\n \n // last column\n for(int i=strow; i<=endrow; ans[i++][endcol]=val++);\n endcol--;\n \n //lastrow\n for(int i=endcol; i>=stcol; ans[endrow][i--]=val++);\n endrow--;\n \n //first column\n for(int i= endrow; i>=strow; ans[i--][stcol]=val++);\n stcol++;\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['C', 'Simulation'] | 0 |
spiral-matrix-ii | Python | Beginner Friendly | Similar to Spiral Matrix - 1 | python-beginner-friendly-similar-to-spir-k1ex | Please upvote if you like the post\n\n\n class Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in rang | pvrittesh | NORMAL | 2022-05-30T05:22:33.900534+00:00 | 2022-05-30T05:22:49.075387+00:00 | 211 | false | Please upvote if you like the post\n\n```\n class Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n matrix_size = n * n\n up = left = value = 0\n right = n - 1\n down = n - 1\n \n while value != matrix_size:\n \n for col in range(left, right + 1):\n value += 1\n matrix[up][col] = value\n \n for row in range(up + 1, down + 1):\n value += 1\n matrix[row][right] = value\n \n if up != down:\n for col in range(right - 1, left - 1, -1):\n value += 1\n matrix[down][col] = value\n \n if left != right:\n for row in range(down - 1, up, -1):\n value += 1\n matrix[row][left] = value\n \n left += 1\n right -= 1\n up += 1\n down -= 1\n\n return matrix\n \n``` | 4 | 0 | ['Python'] | 0 |
spiral-matrix-ii | Python optimized spiral traversal in a few lines explained | python-optimized-spiral-traversal-in-a-f-yblu | We fill the matrix following a spiral pattern, changing direction when going outside of the matrix or when encountering a non-zero value.\nUsing nexton an itert | reupiey | NORMAL | 2022-04-13T08:08:43.815109+00:00 | 2022-04-13T08:08:43.815139+00:00 | 341 | false | We fill the matrix following a spiral pattern, changing direction when going outside of the matrix or when encountering a non-zero value.\nUsing `next`on an `itertools.cycle` is far easier to read than using modulos IMO.\n\n```python\nclass Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n matrix = [[0] * n for _ in range(n)]\n directions = cycle([(0, 1), (1, 0), (0, -1), (-1, 0)])\n row, col = 0, 0\n x, y = next(directions)\n for i in range(1, n ** 2 + 1):\n matrix[row][col] = i\n if not (0 <= row + x < n and 0 <= col + y < n and matrix[row + x][col + y] == 0):\n x, y = next(directions)\n row += x\n col += y \n return matrix\n``` | 4 | 0 | ['Python'] | 1 |
spiral-matrix-ii | ✅ [C] || 100% || Simple Solution || O(n^2) | c-100-simple-solution-on2-by-bezlant-nsmn | \nint** generateMatrix(int n, int* returnSize, int** returnColumnSizes)\n{\n *returnSize = n;\n *returnColumnSizes = malloc(sizeof(int) * n);\n int **r | bezlant | NORMAL | 2022-04-13T05:41:07.820412+00:00 | 2022-04-13T05:41:07.820440+00:00 | 328 | false | ```\nint** generateMatrix(int n, int* returnSize, int** returnColumnSizes)\n{\n *returnSize = n;\n *returnColumnSizes = malloc(sizeof(int) * n);\n int **res = malloc(sizeof(int*) * n);\n for (int i = 0; i < n; i++) {\n (*returnColumnSizes)[i] = n;\n res[i] = malloc(sizeof(int) * n);\n }\n \n int top = 0;\n int bot = n - 1;\n int left = 0;\n int right = n - 1;\n \n int j = 1;\n while (j <= n * n) {\n for (int i = left; i <= right; i++, j++)\n res[top][i] = j;\n top++;\n\n for (int i = top; i <= bot; i++, j++)\n res[i][right] = j;\n right--;\n\n for (int i = right; i >= left; i--, j++)\n res[bot][i] = j;\n bot--;\n\n for (int i = bot; i >= top; i--, j++)\n res[i][left] = j;\n left++;\n }\n\n return res;\n}\n```\n\n**If this was helpful, don\'t hesitate to upvote! :)**\nHave a nice day! | 4 | 0 | ['C'] | 2 |
spiral-matrix-ii | C++|| 0ms|| 100% faster|| Easy and simple | c-0ms-100-faster-easy-and-simple-by-aash-6m6h | Here, we just have to understand the trend of matrix.\nLike how we are filling the matrix.\nfirst we are doing first column to last column,\nthen first row +1 t | aashuchoudhary52 | NORMAL | 2022-04-13T04:21:35.098751+00:00 | 2022-04-13T04:21:35.098794+00:00 | 44 | false | Here, we just have to understand the trend of matrix.\nLike how we are filling the matrix.\nfirst we are doing first column to last column,\nthen first row +1 to last row then again last column to first column and same with last row to first row...this way we can approach this question.\n\nyou will have more understanding after viewing the code.\n\nhope you like it.\n\n\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> v(n,vector<int>(n,0));\n if(n==0)\n {\n return v;\n }\n int firstRow=0;\n int firstColumn=0;\n int lastRow=n-1;\n int lastColumn=n-1;\n int i=1;\n int num=n*n;\n \n while(firstRow<=lastRow && firstColumn<=lastColumn)\n {\n for(int j=firstColumn;j<=lastColumn;j++)\n { \n v[firstRow][j]=i;\n i++;\n }\n if(i>num)break;\n for(int j=firstRow+1;j<=lastRow;j++)\n {\n v[j][lastColumn]=i;\n i++;\n }\n if(i>num)break;\n for(int j=lastColumn-1;j>=firstColumn;j--)\n { \n v[lastRow][j]=i;\n i++; \n }\n if(i>num)break; \n for(int j=lastRow-1;j>firstRow;j--)\n {\n v[j][firstColumn]=i;\n i++; \n }\n if(i>num)break;\n firstRow++;\n firstColumn++;\n lastRow--;\n lastColumn--;\n }\n return v;\n }\n};\n``` | 4 | 1 | ['Matrix'] | 0 |
spiral-matrix-ii | Easy C++ Solution 100% fast | easy-c-solution-100-fast-by-apurvat18-cwid | ```\nclass Solution {\npublic:\n vector> generateMatrix(int n) {\n // Defining the boundaries of the matrix.\n int top = 0, bottom = n-1, right | apurvat18 | NORMAL | 2022-04-13T03:16:19.903080+00:00 | 2022-04-13T03:17:09.007327+00:00 | 33 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n // Defining the boundaries of the matrix.\n int top = 0, bottom = n-1, right = n-1, left = 0;\n // Defining the direction in which the array is to be traversed.\n int dir = 1, val = 1;\n vector<vector<int>> matirx (n, vector<int>(n, 0));\n while( top <= bottom && left <= right){\n // moving left->right\n if(dir == 1){\n for(int i=left; i <= right; i++){\n matirx[top][i]=val;\n val++;\n }\n }\n // Since we have traversed the whole first\n // row, move down to the next row.\n dir = 2;\n top++;\n // moving top->bottom\n if(dir == 2){\n for(int i=top; i <= bottom; i++){\n matirx[i][right]=val;\n val++;\n }\n }\n // Since we have traversed the whole last\n // column, move left to the previous column.\n dir = 3;\n right--;\n // moving right->left\n if(dir == 3){\n for(int i=right; i >= left; i--){\n matirx[bottom][i] = val;\n val++;\n }\n }\n // Since we have traversed the whole last\n // row, move up to the previous row.\n dir = 4;\n bottom--;\n // moving bottom->up\n if(dir == 4){\n for(int i=bottom; i>= top; i--){\n matirx[i][left]=val;\n val++;\n }\n }\n // Since we have traversed the whole first\n // col, move right to the next column.\n dir = 1;\n left ++;\n \n }\n \n return matirx;\n \n }\n};\n | 4 | 0 | [] | 0 |
spiral-matrix-ii | Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-shs7 | Time Complexity : O(N * N)\n Space Complexity : O(1), because space taken for outputing the result doesn\'t count as space complexity*\n\n\nclass Solution {\npu | __KR_SHANU_IITG | NORMAL | 2022-04-13T01:48:47.146737+00:00 | 2022-04-13T01:48:47.146781+00:00 | 319 | false | * ***Time Complexity : O(N * N)***\n* ***Space Complexity : O(1), because space taken for outputing the result doesn\'t count as space complexity***\n\n```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n vector<vector<int>> mat(n, vector<int> (n, 0));\n \n int k = 1;\n \n int top = 0;\n \n int bottom = n - 1;\n \n int left = 0;\n \n int right = n - 1;\n \n while(left <= right && top <= bottom)\n {\n if(top <= bottom)\n {\n for(int i = left; i <= right; i++)\n {\n mat[top][i] = k;\n \n k++;\n }\n \n top++;\n }\n \n if(left <= right)\n {\n for(int i = top; i <= bottom; i++)\n {\n mat[i][right] = k;\n \n k++;\n }\n \n right--;\n }\n \n if(top <= bottom)\n {\n for(int i = right; i >= left; i--)\n {\n mat[bottom][i] = k;\n \n k++;\n }\n \n bottom--;\n }\n \n if(left <= right)\n {\n for(int i = bottom; i >= top; i--)\n {\n mat[i][left] = k;\n \n k++;\n }\n \n left++;\n }\n }\n \n return mat;\n }\n};\n``` | 4 | 0 | ['C', 'Matrix'] | 0 |
spiral-matrix-ii | Easy-Understanding Java Solution | easy-understanding-java-solution-by-lmeb-7oiq | ```\nprivate int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\tprivate int direction = 0;\n\tpublic int[][] generateMatrix(int n) {\n\t\tint[][] r | lmebo | NORMAL | 2022-03-01T19:01:15.022627+00:00 | 2022-03-01T19:01:15.022662+00:00 | 103 | false | ```\nprivate int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };\n\tprivate int direction = 0;\n\tpublic int[][] generateMatrix(int n) {\n\t\tint[][] res = new int[n][n];\n\t\tres[0][0] = 1;\n\t\tint row = 0;\n\t\tint col = 0;\n\t\tint count = 2;\n\t\twhile (count <= n * n) {\n\t\t\tif (canGo(row + dirs[direction][0], col + dirs[direction][1],res)){\n\t\t\t\trow += dirs[direction][0];\n\t\t\t\tcol += dirs[direction][1];\n\t\t\t\tres[row][col] = count;\n\t\t\t\tcount++;\n\t\t\t} else {\n\t\t\t\tdirection++;\n\t\t\t\tdirection = direction % 4;\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tprivate boolean canGo(int i, int j, int[][] res) {\n\t\tif (i > res.length - 1 || i < 0 || j > res[0].length - 1 || j < 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif(res[i][j] != 0) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t} | 4 | 1 | ['Java'] | 0 |
spiral-matrix-ii | Python solution | python-solution-by-lexieeeee-cy2x | Need to be careful for the corner element traversal. \n```\nclass Solution(object):\n def generateMatrix(self, n):\n top, bottom, left, right = 0, n-1 | lexieeeee | NORMAL | 2022-02-13T06:09:25.279051+00:00 | 2022-02-13T06:09:25.279083+00:00 | 184 | false | Need to be careful for the corner element traversal. \n```\nclass Solution(object):\n def generateMatrix(self, n):\n top, bottom, left, right = 0, n-1, 0, n-1\n num = 1 \n if not n:\n return \n matrix = [[0]*n for _ in xrange(n)]\n while left <= right and top <= bottom:\n for i in xrange(left, right+1):\n matrix[top][i] = num\n num += 1\n top += 1 \n \n for i in xrange(top, bottom+1):\n matrix[i][right] = num\n num += 1 \n right -= 1 \n \n for i in xrange(right, left-1, -1):\n matrix[bottom][i] = num\n num += 1\n bottom -= 1 \n \n for i in xrange(bottom, top-1, -1):\n matrix[i][left] = num\n num += 1 \n left += 1\n \n return matrix | 4 | 0 | ['Python'] | 0 |
spiral-matrix-ii | c++ 100 % | Each and Every steps Explained | Easy | Efficient | c-100-each-and-every-steps-explained-eas-amn3 | class Solution {\npublic:\n vector> generateMatrix(int n) {\n \n vector> a(n,vector(n,0));\n int val=1,r=0,c=0,m=n,i;\n \n \n / | ConsistentCoder27 | NORMAL | 2021-10-03T11:27:28.808938+00:00 | 2021-10-03T11:41:37.623626+00:00 | 343 | false | class Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n vector<vector<int>> a(n,vector<int>(n,0));\n int val=1,r=0,c=0,m=n,i;\n \n \n /* r - starting row index\n m - ending row index\n c - starting column index\n n - ending column index\n i - iterator\n */\n \n while (r < m && c < n) {\n /* Assigning value to first row from\n the remaining rows */\n for (i = c; i < n; ++i) {\n a[r][i] = val++;\n }\n r++;\n \n /* Assigning value to last column\n from the remaining columns */\n for (i = r; i < m; ++i) {\n a[i][n - 1] = val++;\n }\n n--;\n \n /* Assigning value to last row from\n the remaining rows */\n if (r < m) {\n for (i = n - 1; i >= c; --i) {\n a[m - 1][i] = val++;\n }\n m--;\n }\n \n /* Assigning value to first column from\n the remaining columns */\n if (c < n) {\n for (i = m - 1; i >= r; --i) {\n a[i][c] = val++;\n }\n c++;\n }\n }\n return a;\n }\n}; | 4 | 0 | ['C', 'Matrix', 'C++'] | 0 |
spiral-matrix-ii | [faster than 100.00%][beginner friendly][easy understanding] | faster-than-10000beginner-friendlyeasy-u-xfw5 | \n//Runtime: 0 ms, faster than 100.00%\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int cnt=0;\n int rs=0,re=n-1; | rajat_gupta_ | NORMAL | 2020-12-12T13:57:01.708157+00:00 | 2020-12-12T13:57:01.708193+00:00 | 340 | false | ```\n//Runtime: 0 ms, faster than 100.00%\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n int cnt=0;\n int rs=0,re=n-1;\n int cs=0,ce=n-1;\n int j=1;\n vector<vector<int>>res(n,vector<int>(n,0));\n while(rs <= re && cs <= ce){\n for(int i=cs;i<=ce;i++){\n res[rs][i]=j++;\n }\n rs++;\n for(int i=rs;i<=re;i++){\n res[i][ce]=j++;\n }\n ce--;\n if (rs <= re)\n for(int i=ce;i>=cs;i--){\n res[re][i]=j++;\n }\n re--;\n if (cs <= ce)\n for(int i=re;i>=rs;i--){\n res[i][cs]=j++;\n }\n cs++;\n }\n return res;\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n | 4 | 0 | ['C', 'C++'] | 1 |
spiral-matrix-ii | [c++] "0ms" solution, easy to understand | c-0ms-solution-easy-to-understand-by-its-uuiv | \'\'\'\nclass Solution {\npublic:\n vector> generateMatrix(int n) {\n vector>v(n,vector(n));\n int count=0;\n for(int i=0;i<n;i++)\n | its_pro_deep | NORMAL | 2020-12-08T06:44:33.037658+00:00 | 2020-12-08T06:44:33.037686+00:00 | 115 | false | \'\'\'\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>>v(n,vector<int>(n));\n int count=0;\n for(int i=0;i<n;i++)\n {\n for(int j=i;j<n-i;j++){ //left to right\n v[i][j]=++count;\n }\n for(int k=i+1;k<n-i-1;k++){ //top to bottom\n v[k][n-i-1]=++count;\n }\n for(int l=n-1-i;l>i;l--){ // right to left\n v[n-i-1][l]=++count;\n }\n for(int m=n-1-i;m>i;m--){ //bottom to top\n v[m][i]=++count;\n }\n }\n return v;\n }\n};\n\'\'\' | 4 | 0 | [] | 1 |
spiral-matrix-ii | Python | python-by-gsan-swki | We do as told and construct the matrix via traversing the spiral.\n\npython\nclass Solution:\n def generateMatrix(self, n):\n ans = [[0]*n for _ in ra | gsan | NORMAL | 2020-12-07T08:21:53.692394+00:00 | 2020-12-07T08:22:19.695357+00:00 | 437 | false | We do as told and construct the matrix via traversing the spiral.\n\n```python\nclass Solution:\n def generateMatrix(self, n):\n ans = [[0]*n for _ in range(n)]\n x = y = j = 0\n dirs = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in range(1,n**2+1):\n ans[x][y] = i\n dx, dy = dirs[j]\n if 0<=x+dx<=n-1 and 0<=y+dy<=n-1 and ans[x+dx][y+dy]==0:\n x, y = x+dx, y+dy\n else:\n j = (j+1)%4\n dx, dy = dirs[j]\n x, y = x+dx, y+dy \n return ans\n``` | 4 | 0 | [] | 0 |
spiral-matrix-ii | JAVA - My EASY Solution | java-my-easy-solution-by-anubhavjindal-wdhp | \npublic int[][] generateMatrix(int n) {\n\tint sol[][] = new int[n][n], count = 1;\n\tint rowMin = 0, colMin = 0, rowMax = n-1, colMax = n-1;\n\twhile(rowMin < | anubhavjindal | NORMAL | 2020-02-14T04:10:16.095357+00:00 | 2020-02-14T04:10:16.095407+00:00 | 168 | false | ```\npublic int[][] generateMatrix(int n) {\n\tint sol[][] = new int[n][n], count = 1;\n\tint rowMin = 0, colMin = 0, rowMax = n-1, colMax = n-1;\n\twhile(rowMin <= rowMax && colMin <= colMax) {\n\t\tfor(int i = colMin; i <= colMax; i++) \n\t\t\tsol[rowMin][i] = count++;\n\t\trowMin++;\n\t\tfor(int i = rowMin; i <= rowMax; i++) \n\t\t\tsol[i][colMax] = count++;\n\t\tcolMax--;\n\t\tfor(int i = colMax; i >= colMin; i--)\n\t\t\tsol[rowMax][i] = count++;\n\t\trowMax--;\n\t\tfor(int i = rowMax; i >= rowMin; i--)\n\t\t\tsol[i][colMin] = count++;\n\t\tcolMin++;\n\t}\n\treturn sol;\n}\n``` | 4 | 1 | [] | 2 |
spiral-matrix-ii | Javascript solution beats 60% | javascript-solution-beats-60-by-ggoranta-saew | Here is my solution to solve this problem in JS.\n\n\n\n/* startColumn endColumn\n startRow 1 2 3\n 4 | ggorantala | NORMAL | 2019-10-01T05:21:48.635182+00:00 | 2019-10-01T05:39:58.645363+00:00 | 174 | false | Here is my solution to solve this problem in JS.\n\n```\n\n/* startColumn endColumn\n startRow 1 2 3\n 4 5 6\n endRow 7 8 9\n */\nconst spiral = n => {\n const results = [];\n\n for (let i = 0; i < n; i++) {\n results.push([]);\n }\n\n let startRow = 0,\n endRow = n - 1,\n startColumn = 0,\n endColumn = n - 1,\n count = 1;\n\n while (startRow <= endRow && startColumn <= endColumn) {\n //Top Row\n for (let i = startColumn; i <= endColumn; i++) {\n results[startRow][i] = count;\n count++;\n }\n startRow++;\n\n //Right Column\n for (let i = startRow; i <= endRow; i++) {\n results[i][endColumn] = count;\n count++;\n }\n endColumn--;\n\n //bottom row\n for (let i = endColumn; i >= startColumn; i--) {\n results[endRow][i] = count;\n count++;\n }\n endRow--;\n\n //Left Column\n for (let i = endRow; i >= startRow; i--) {\n results[i][startColumn] = count;\n count++;\n }\n startColumn++;\n }\n return results;\n};\n\nconsole.log(spiral(3));\n``` | 4 | 0 | ['JavaScript'] | 0 |
spiral-matrix-ii | C++ clean! | c-clean-by-raunit-dnmx | \nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) \n {\n if(!n)\n return {};\n int rowStart = 0, rowEnd = n | raunit | NORMAL | 2019-09-17T19:18:52.518856+00:00 | 2019-09-24T19:29:07.925131+00:00 | 241 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) \n {\n if(!n)\n return {};\n int rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1;\n int count = 1;\n vector<vector<int>> result(n, vector<int>(n));\n while(count <= n * n)\n {\n for(int i = colStart; i <= colEnd && count <= n * n; result[rowStart][i++] = count++);\n for(int i = ++rowStart; i <= rowEnd && count <= n * n; result[i++][colEnd] = count++);\n for(int i = --colEnd; i >= colStart && count <= n * n; result[rowEnd][i--] = count++);\n for(int i = --rowEnd; i >= rowStart && count <= n * n; result[i--][colStart] = count++);\n ++colStart;\n }\n return result;\n }\n};\n``` | 4 | 0 | [] | 0 |
spiral-matrix-ii | {{{ C++ }}} 100% Beat ((Using Smart Loops + Smart Memories)) [[ SUPER HACK VIDEO RENTAL ]] O(N) | c-100-beat-using-smart-loops-smart-memor-l6ga | \nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n vector<vector<int>> aResult(n, vector<int>(n));\n \n | nraptis | NORMAL | 2019-06-10T05:05:19.051896+00:00 | 2019-06-10T05:05:19.051927+00:00 | 108 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> generateMatrix(int n) {\n \n vector<vector<int>> aResult(n, vector<int>(n));\n \n int _U = 0, _R = n - 1, _D = n - 1, _L = 0, x = 0, y = 0, VAL = 1;\n \n while (_L <= _R) {\n \n x = _L; y = _U;\n \n //Sweep right across the top.\n while (x <= _R) { aResult[y][x++] = VAL++; }\n _U += 1; y = _U;\n \n //Sweep down the right side.\n while (y <= _D) { aResult[y++][_R] = VAL++; }\n _R -= 1; x = _R;\n \n //Swipe left across the bottom.\n while (x >= _L) { aResult[_D][x--] = VAL++; }\n _D -= 1; y = _D;\n \n //Sweep up the left side.\n while (y >= _U) { aResult[y--][_L] = VAL++; }\n _L += 1;\n }\n \n return aResult;\n }\n};\n```\n\nDecided to try with all the variables being named in terrible ways. I am not sure how you can clock more speed given that the result needs to be a vector of vectors. | 4 | 1 | [] | 0 |
spiral-matrix-ii | Ruby Solution | ruby-solution-by-renyijiu-gfps | the solution learns from the discuss, here is the code:\n\n```ruby\n\ndef generate_matrix(n)\n arr = Array.new(n){ Array.new(n) }\n \n i, j, di, dj = 0, 0, 0 | renyijiu | NORMAL | 2019-02-17T08:00:00.617889+00:00 | 2019-02-17T08:00:00.617965+00:00 | 146 | false | the solution learns from the discuss, here is the code:\n\n```ruby\n\ndef generate_matrix(n)\n arr = Array.new(n){ Array.new(n) }\n \n i, j, di, dj = 0, 0, 0, 1\n (0...n*n).each do |k|\n arr[i][j] = k + 1 \n \n di, dj = dj, -di if arr[(i+di)%n][(j+dj)%n]\n \n i += di\n j += dj\n end\n \n arr\nend\n | 4 | 0 | [] | 1 |
spiral-matrix-ii | C++ template for Spiral Matrix & Spiral Matrix II | c-template-for-spiral-matrix-spiral-matr-xvsk | Spiral Matrix II code:\n\n class Solution {\n public:\n vector> generateMatrix(int n) {\n vector> result(n, vector(n, 0));\n | rainbowsecret | NORMAL | 2016-02-22T02:37:51+00:00 | 2016-02-22T02:37:51+00:00 | 883 | false | Spiral Matrix II code:\n\n class Solution {\n public:\n vector<vector<int>> generateMatrix(int n) {\n vector<vector<int>> result(n, vector<int>(n, 0));\n int l=0, r=n-1, u=0, d=n-1;\n int k=1;\n while(true){\n for(int i=l; i<=r; i++) result[u][i]=k++;\n if(++u>d) break;\n \n for(int i=u; i<=d; i++) result[i][r]=k++;\n if(r--<l) break;\n \n for(int i=r; i>=l; i--) result[d][i]=k++;\n if(--d<u) break;\n \n for(int i=d; i>=u; i--) result[i][l]=k++;\n if(++l>r) break;\n }\n return result;\n }\n };\n\nSpiral Matrix Code:\n\n class Solution {\n public:\n vector<int> spiralOrder(vector<vector<int>>& matrix) {\n if(matrix.empty()) return {};\n int m=matrix.size(), n=matrix[0].size();\n vector<int> spiral(m*n);\n int u=0, d=m-1, l=0, r=n-1, k=0;\n while(true){\n /** up **/\n for(int col=l; col<=r; col++) spiral[k++]=matrix[u][col];\n if(++u>d) break;\n /** right **/\n for(int row=u; row<=d; row++) spiral[k++]=matrix[row][r];\n if(--r<l) break;\n /** down **/\n for(int col=r; col>=l; col--) spiral[k++]=matrix[d][col];\n if(--d<u) break;\n /** left **/\n for(int row=d; row>=u; row--) spiral[k++]=matrix[row][l];\n if(++l>r) break;\n }\n return spiral;\n }\n }; | 4 | 0 | [] | 0 |
spiral-matrix-ii | 🌟 Spiral Matrix II | Elegant Simulation for Clockwise Traversal 🌀 | spiral-matrix-ii-elegant-simulation-for-is70m | Intuition:
To generate a spiral matrix, we fill an n×n grid in a spiral order starting at the top-left corner and moving clockwise. The key is to manage the dir | rshohruh | NORMAL | 2025-01-03T03:02:53.525496+00:00 | 2025-01-03T05:07:08.328424+00:00 | 234 | false | **Intuition:**
To generate a spiral matrix, we fill an $$n \times n$$ grid in a **spiral order** starting at the top-left corner and moving clockwise. The key is to manage the direction of movement dynamically when we encounter boundaries or already-filled cells.
---
**Approach:**
1. **Matrix Initialization:** Create an $$n \times n$$ grid initialized to zeros.
2. **Direction Management:** Use two variables to control movement:
- `dx`: Change in row direction.
- `dy`: Change in column direction.
Initially, set `dx = 0` and `dy = 1` to move right.
3. **Fill the Matrix:**
- Start from the top-left corner.
- For each step, check if the next position is out of bounds or already filled.
- If so, reverse direction by swapping `dx` and `dy` and negating one of them to rotate clockwise.
- Continue filling numbers from `1` to `n^2`.
4. **Stop Condition:** Stop when all cells are filled.
---
**Complexity:**
- **Time Complexity:** $$O(n^2)$$, as we visit each cell once.
- **Space Complexity:** $$O(1)$$, ignoring the output matrix.
---
**Code:**
```cpp
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector grid(n, vector(n, 0)); // Initialize the grid
for (int cur = 1, x = 0, y = 0, dx = 0, dy = 1; cur <= n * n; x += dx, y += dy) {
// Check boundaries or if cell is already filled
if (max(x, y) >= n || min(x, y) < 0 || grid[x][y] != 0) {
x -= dx; // Step back
y -= dy;
swap(dx, dy); // Change direction
dx *= -1; // Rotate clockwise
} else {
grid[x][y] = cur++; // Fill the current cell
}
}
return grid;
}
};
```
---
**Example:**
**Input:**
`n = 3`
**Output:**
`[[1, 2, 3], [8, 9, 4], [7, 6, 5]]`
**Explanation:**
1. Fill numbers from `1` to `3` moving right.
2. Fill `6` and `9` moving down.
3. Fill `8` and `7` moving left.
4. Fill `4` and `5` moving up.
---
**Edge Cases:**
1. **n = 1:** Output is `[[1]]`.
2. **Even n:** Works naturally for all $$n \geq 2$$.
3. **Large n:** Efficient traversal ensures no redundant operations.
---
**Tips for Interviews:**
- Use direction vectors to manage movement dynamically.
- Write modular code with clear handling for boundary conditions.
- Test your code with small and edge-case inputs during the interview. | 3 | 0 | ['Dynamic Programming', 'Matrix', 'Simulation', 'C++'] | 0 |
spiral-matrix-ii | Easy JS.sol 👀 | easy-jssol-by-starboy609-pnxm | Intuition\n Describe your first thoughts on how to solve this problem. \nEasy && Simple \n\n# Approach\n Describe your approach to solving the problem. \nStep 1 | starboy609 | NORMAL | 2024-09-09T16:00:29.467783+00:00 | 2024-09-09T16:00:29.467820+00:00 | 206 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEasy && Simple \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1 : Create a 2D Array of length (m * n) and initialize the cells with \'-1\'\n```javascript []\nconst matrix = Array.from({length : m}, () => Array(n).fill(-1));\n```\nStep 2 : Take four variables for iteration purpose \n```javascript []\nlet top = 0; // Top\nlet btm = m - 1; // Bottom \nlet lft = 0; // Left\nlet ryt = n - 1; // Right\n```\nstep 3 : Take a variable num = 1 and increment the num, fil the num in the matrix cells\n```javascript []\nlet num = 1; // after every iteration increment the num\n```\nStep 4 : Run a while loop untill the \'top\' or \'left\' reaches the \'bottom\' or \'right\'\n```javascript []\nwhile(top <= btm && lft <= ryt)\n{\n // Step 5;\n}\n```\nStep 5 : In the While, use the \'for\' loop with variable \'i\'... Now look at the Main code , Bye!\n\n\n# Complexity\n- Time complexity: O(n * n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number} n\n * @return {number[][]}\n */\nvar generateMatrix = function(n) {\n const mat = Array.from({length : n}, () => Array(n).fill(0));\n\n let t = 0;\n let b = n - 1;\n let l = 0;\n let r = n - 1;\n\n let a = 1;\n while(t <= b && l <= r) // Step 5\n {\n for(let i = l; i <= r; i++) mat[t][i] = a++; t++;\n\n for(let i = t; i <= b; i++) mat[i][r] = a++; r--;\n\n for(let i = r; i >= l; i--) mat[b][i] = a++; b--;\n\n for(let i = b; i >= t; i--) mat[i][l] = a++; l++;\n } \n\n return mat;\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
longest-increasing-subsequence-ii | [Python] Explanation with pictures, Segment Tree | python-explanation-with-pictures-segment-967n | We store the longest increasing subsequence ended by each number in array LIS (1-indexed). Let\'s say the input nums = [4,2,4,5,9]. Initailly, LIS[i] = 0 as we | Bakerston | NORMAL | 2022-09-11T04:02:18.463792+00:00 | 2022-09-11T04:53:08.721074+00:00 | 15,199 | false | We store the longest increasing subsequence ended by each number in array `LIS` **(1-indexed)**. Let\'s say the input `nums = [4,2,4,5,9]`. Initailly, `LIS[i] = 0` as we haven\'t add any number yet.\n\n\n\n> The key is for a given value `a`, we should find the maximum value from `LIS[a - k: a]` ), then `LIS[a] = 1 + max(LIS[a - k : a])`.\n\n---\n\nTake the pictures below as an example:\n\nFor the first number `4`, the maximum length is the maximum of `LIS[1], LIS[2], LIS[3]` plus `1` (4 itself). Thus we shall look for the `max(LIS[1:4])` . Apparently, `LIS[4] = 1` which stands for `4` itself.\n\n\n\nThen update LIS for `2`, we shall look for `max(LIS[1:2])`, notice the corner case that left end always larger than 0.\n\n\n\nThen update LIS for `4`, we look for `max(LIS[1:4])`, since there is an `2` updated in `LIS`, thus the maximum value from the same range `LIS[1:4]` gives us 1. Then we can update `LIS[4] = 2`, implying a subsequence of `2, 4`.\n\n\n\nThen update LIS for `5`, we look for `max(LIS[2:5])`, `LIS[5] = LIS[4] + 1 = 3`, implying a subsequence of `2, 4, 5`.\n\n\n\n\nThen update LIS for `9`, we look for `max(LIS[6:9])`.\n\n\n\nso on so forth...\n\nHowever, brute force ends up with O(n^2) time, we shall look for a better approach.\n\nIts range queries of min/max value, thus we can use segment tree.\n\n**python**\n\n```\nclass SEG:\n def __init__(self, n):\n self.n = n\n self.tree = [0] * 2 * self.n\n \n def query(self, l, r):\n l += self.n\n r += self.n\n ans = 0\n while l < r:\n if l & 1:\n ans = max(ans, self.tree[l])\n l += 1\n if r & 1:\n r -= 1\n ans = max(ans, self.tree[r])\n l >>= 1\n r >>= 1\n return ans\n \n def update(self, i, val):\n i += self.n\n self.tree[i] = val\n while i > 1:\n i >>= 1\n self.tree[i] = max(self.tree[i * 2], self.tree[i * 2 + 1])\n\nclass Solution:\n def lengthOfLIS(self, A: List[int], k: int) -> int:\n n, ans = max(A), 1\n seg = SEG(n)\n for a in A:\n a -= 1\n premax = seg.query(max(0, a - k), a)\n ans = max(ans, premax + 1)\n seg.update(a, premax + 1)\n return ans\n``` | 215 | 1 | [] | 26 |
longest-increasing-subsequence-ii | [C++] Segment tree with illustration/explanation | c-segment-tree-with-illustrationexplanat-73bn | We use a segment tree to keep track of the max length of all the valid numbers that can come before this one.\nFor example, if k = 3 and the current number is 5 | ayman_eltemmsahy | NORMAL | 2022-09-11T04:00:29.653699+00:00 | 2022-09-13T18:28:49.161755+00:00 | 9,904 | false | We use a segment tree to keep track of the max length of all the valid numbers that can come before this one.\nFor example, if `k = 3` and the current number is `5`, then the valid numbers before it are `2, 3, 4`. We query the segment tree in `O(logM)` to get the longest sequence out of the 3 numbers and we add `1` to it.\n\n#### Example\n```\nnums = [4,2,1,4,3,4,5,8], k = 3\n```\n1. `index=0`, `val = 4`\nget the max sequence length from `[1, 2, 3]`.\n`max value = 0`\n`current value = 0 + 1 = 1`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***0***|***0***|***0***|0|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|0|0|0|***1***|0|0|0|0|\n\n\n2. `index=1`, `val = 2`\nget the max sequence length from `[1]`.\n`max value = 0`\n`current value = 0 + 1 = 1`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***0***|0|0|1|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|0|***1***|0|1|0|0|0|0|\n\n\n3. `index=2`, `val = 1`\nnothing can come before it\n`max value = 0`\n`current value = 0 + 1 = 1`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|0|1|0|1|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***1***|1|0|1|0|0|0|0|\n\n\n4. `index=3`, `val = 4`\nget the max sequence length from `[1, 2, 3]`.\n`max value = 1`\n`current value = 1 + 1 = 2`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***1***|***1***|***0***|1|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|0|***2***|0|0|0|0|\n\n\n5. `index=4`, `val = 3`\nget the max sequence length from `[1, 2]`.\n`max value = 1`\n`current value = 1 + 1 = 2`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***1***|***1***|0|2|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|***2***|2|0|0|0|0|\n\n\n6. `index=5`, `val = 4`\nget the max sequence length from `[1, 2, 3]`.\n`max value = 2`\n`current value = 2 + 1 = 3`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|***1***|***1***|***2***|2|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|2|***3***|0|0|0|0|\n\n\n7. `index=6`, `val = 5`\nget the max sequence length from `[2, 3, 4]`.\n`max value = 3`\n`current value = 3 + 1 = 4`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|***1***|***2***|***3***|0|0|0|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|2|3|***4***|0|0|0|\n\n8. `index=7`, `val = 8`\nget the max sequence length from `[5, 6, 7]`.\n`max value = 4`\n`current value = 4 + 1 = 5`\n\n_Tree_ (before)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|2|3|***4***|***0***|***0***|0|\n\n_Tree_ (after)\n|num|1|2|3|4|5|6|7|8|\n|-|-|-|-|-|-|-|-|-|\n|max|1|1|2|3|4|0|0|***5***|\n\n#### Complexity:\n```\nTime : O(NlogN)\nSpace: O(N)\n```\n\n#### Code\n\n```c++\nclass MaxSegmentTree {\n public:\n int n;\n vector<int> tree;\n MaxSegmentTree(int n_) : n(n_) {\n int size = (int)(ceil(log2(n)));\n size = (2 * pow(2, size)) - 1;\n tree = vector<int>(size);\n }\n \n int max_value() { return tree[0]; }\n\n int query(int l, int r) { return query_util(0, l, r, 0, n - 1); }\n\n int query_util(int i, int qL, int qR, int l, int r) {\n if (l >= qL && r <= qR) return tree[i];\n if (l > qR || r < qL) return INT_MIN;\n\n int m = (l + r) / 2;\n return max(query_util(2 * i + 1, qL, qR, l, m), query_util(2 * i + 2, qL, qR, m + 1, r));\n }\n\n void update(int i, int val) { update_util(0, 0, n - 1, i, val); }\n void update_util(int i, int l, int r, int pos, int val) {\n if (pos < l || pos > r) return;\n if (l == r) {\n tree[i] = max(val, tree[i]);\n return;\n }\n\n int m = (l + r) / 2;\n update_util(2 * i + 1, l, m, pos, val);\n update_util(2 * i + 2, m + 1, r, pos, val);\n tree[i] = max(tree[2 * i + 1], tree[2 * i + 2]);\n }\n};\n\nclass Solution {\n public:\n int lengthOfLIS(vector<int>& nums, int k) {\n MaxSegmentTree tree(1e5 + 1);\n for (int i : nums) {\n int lower = max(0, i - k);\n int cur = 1 + tree.query(lower, i - 1);\n tree.update(i, cur);\n }\n\n return tree.max_value();\n }\n};\n```\n\n**Upvote if you find it helpful :)** | 122 | 1 | ['Tree', 'C'] | 13 |
longest-increasing-subsequence-ii | Segment Tree || C++ | segment-tree-c-by-yowaimo-7bg5 | The number that can be behind number X is in the range [X - k, X - 1], and the best value for the LIS than ends with X is the maximum value in that range + 1, 1 | Yowaimo | NORMAL | 2022-09-11T04:00:27.942989+00:00 | 2022-09-11T04:06:34.198273+00:00 | 6,335 | false | The number that can be behind number **X** is in the range **[X - k, X - 1]**, and the best value for the LIS than ends with **X** is the maximum value in that range + 1, 1 for the current element **X**.\nSo we use a segment tree to find the maximum value in the range and update the current value for further use and calculate the result with every iteration.\n```\nclass Solution {\npublic:\n vector<int> seg;\n //Segment tree to return maximum in a range\n void upd(int ind, int val, int x, int lx, int rx) {\n if(lx == rx) {\n seg[x] = val;\n return;\n }\n int mid = lx + (rx - lx) / 2;\n if(ind <= mid)\n upd(ind, val, 2 * x + 1, lx, mid);\n else \n upd(ind, val, 2 * x + 2, mid + 1, rx);\n seg[x] = max(seg[2 * x + 1], seg[2 * x + 2]);\n }\n int query(int l, int r, int x, int lx, int rx) {\n if(lx > r or rx < l) return 0;\n if(lx >= l and rx <= r) return seg[x];\n int mid = lx + (rx - lx) / 2;\n return max(query(l, r, 2 * x + 1, lx, mid), query(l, r, 2 * x + 2, mid + 1, rx));\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int x = 1;\n while(x <= 200000) x *= 2;\n seg.resize(2 * x, 0);\n \n int res = 1;\n for(int i = 0; i < nums.size(); ++i) {\n int left = max(1, nums[i] - k), right = nums[i] - 1;\n int q = query(left, right, 0, 0, x - 1); // check for the element in the range of [nums[i] - k, nums[i] - 1] with the maximum value\n res = max(res, q + 1);\n upd(nums[i], q + 1, 0, 0, x - 1); //update current value\n }\n return res;\n }\n};\n``` | 49 | 2 | ['Tree', 'C'] | 13 |
longest-increasing-subsequence-ii | [C++/Java] Segment Tree (Max Range Query) | cjava-segment-tree-max-range-query-by-st-8qfr | Strategy\nFor every element A[i], we check the range [A[i]-k, A[i]-1] for the current best length and add 1. \nThe problem here is that, we also need to update | Student2091 | NORMAL | 2022-09-11T04:02:38.631435+00:00 | 2022-09-12T08:47:57.367203+00:00 | 4,713 | false | #### Strategy\nFor every element `A[i]`, we check the range `[A[i]-k, A[i]-1]` for the current best length and add 1. \nThe problem here is that, we also need to update the max and it is not a prefix range from 0 to some number, so fenwick tree won\'t work.\n\nI figure segment tree is good for this because it supports update and query in both `O(logn)`. \n\n`Time O(log(max(A[i])) * N)`\n`Space O(max(A[i]))`\n\n#### C++\n```C++\nconstexpr int N = 100001;\nclass Solution {\npublic: \n array<int, 2*N> seg{};\n \n void update(int pos, int val){ // update max\n pos += N;\n seg[pos] = val;\n \n while (pos > 1) {\n pos >>= 1;\n seg[pos] = max(seg[2*pos], seg[2*pos+1]);\n }\n }\n \n int query(int lo, int hi){ // query max [lo, hi)\n lo += N;\n hi += N;\n int res = 0;\n \n while (lo < hi) {\n if (lo & 1) {\n res = max(res, seg[lo++]);\n }\n if (hi & 1) {\n res = max(res, seg[--hi]);\n }\n lo >>= 1;\n hi >>= 1;\n }\n return res;\n }\n \n int lengthOfLIS(vector<int>& A, int k) {\n int ans = 0;\n for (int i = 0; i < size(A); ++i){\n int l = max(0, A[i]-k);\n int r = A[i];\n int res = query(l, r) + 1; // best res for the current element\n ans = max(res, ans);\n update(A[i], res); // and update it here\n }\n \n return ans;\n }\n};\n```\n\n</br>\n\n_____________________________\n\n#### Java\n```Java\nclass Solution {\n\n int N = 100001;\n int[] seg = new int[2*N];\n \n void update(int pos, int val){ // update max\n pos += N;\n seg[pos] = val;\n \n while (pos > 1) {\n pos >>= 1;\n seg[pos] = Math.max(seg[2*pos], seg[2*pos+1]);\n }\n }\n \n int query(int lo, int hi){ // query max [lo, hi)\n lo += N;\n hi += N;\n int res = 0;\n \n while (lo < hi) {\n if ((lo & 1)==1) {\n res = Math.max(res, seg[lo++]);\n }\n if ((hi & 1)==1) {\n res = Math.max(res, seg[--hi]);\n }\n lo >>= 1;\n hi >>= 1;\n }\n return res;\n }\n \n public int lengthOfLIS(int[] A, int k) {\n int ans = 0;\n for (int i = 0; i < A.length; ++i){\n int l = Math.max(0, A[i]-k);\n int r = A[i];\n int res = query(l, r) + 1; // best res for the current element\n ans = Math.max(res, ans);\n update(A[i], res); // and update it here\n }\n return ans;\n }\n}\n``` | 25 | 2 | ['Tree', 'C', 'Java'] | 8 |
longest-increasing-subsequence-ii | Segment Tree | segment-tree-by-votrubac-9nff | Can be solved by DP, where dp[nums[i]] = max(dp[1] ... dp[nums[i] - 1]).\n\nHowever, this leads to a quadratic solution, and we need to do it in O(n log n) base | votrubac | NORMAL | 2022-09-15T06:47:58.021424+00:00 | 2022-09-17T11:43:14.058142+00:00 | 2,389 | false | Can be solved by DP, where `dp[nums[i]] = max(dp[1] ... dp[nums[i] - 1])`.\n\nHowever, this leads to a quadratic solution, and we need to do it in O(n log n) based on the problem constraints. \n\nI wasted a lot of time trying to adapt a monostack LIS solution, but only to realize that we must use DP. \n\nWe just need to make the max range query to run in O(log n) instead of O(n). This can be done using a segment tree.\n\nNote that, for canonical LIS, we can also use the Fenwick tree. With `k`, Fenwick tree would not work as it can only answer min/max queries on the `[0, r]` interval (min/max are not commutative operations).\n\nIt\'s possible to use a pair of Fenwick trees to answer mini/max queries on `[l, r]` interval, but the solution would be much more complicated, compared to a segment tree.\n\n**C++**\n```cpp\nint st[2 * (1 << 17)] = {}; // 2 ^ 16 < 100000 < 2 ^ 17\nint query(int l, int r, int p = 1, int tl = 0, int tr = 100000) {\n if (l > r) \n return 0;\n if (l == tl && r == tr)\n return st[p];\n int tm = (tl + tr) / 2;\n return max(query(l, min(r, tm), p * 2, tl, tm), query(max(l, tm + 1), r, p * 2 + 1, tm + 1, tr));\n}\nint update(int pos, int new_val, int p = 1, int tl = 0, int tr = 100000) {\n if (tl == tr)\n return st[p] = new_val;\n int tm = (tl + tr) / 2;\n if (pos <= tm)\n return st[p] = max(update(pos, new_val, p * 2, tl, tm), st[p * 2 + 1]);\n return st[p] = max(st[p * 2], update(pos, new_val, p * 2 + 1, tm + 1, tr));\n} \nint lengthOfLIS(vector<int>& nums, int k) {\n return accumulate(begin(nums), end(nums), 0, [&](int res, int n){ \n return update(n, query(max(0, n - k), n - 1) + 1);\n });\n}\n``` | 16 | 1 | ['C'] | 2 |
longest-increasing-subsequence-ii | Clean Java | clean-java-by-rexue70-2ekc | It is similar to https://leetcode.com/problems/count-of-smaller-numbers-after-self/\nand https://leetcode.com/problems/range-sum-query-mutable/\nIf you did ques | rexue70 | NORMAL | 2022-09-11T05:04:31.266268+00:00 | 2022-09-11T05:04:31.266305+00:00 | 3,152 | false | It is similar to https://leetcode.com/problems/count-of-smaller-numbers-after-self/\nand https://leetcode.com/problems/range-sum-query-mutable/\nIf you did question above, it should be similar to find range sum/max/avg\n```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n SegmentTree root = new SegmentTree(1, 100000);\n int res = 0;\n for (int num : nums) {\n int preMax = root.rangeMaxQuery(root, num - k, num - 1);\n root.update(root, num, preMax + 1);\n res = Math.max(res, preMax + 1);\n }\n return res;\n }\n}\n\nclass SegmentTree {\n SegmentTree left, right;\n int start, end, val;\n public SegmentTree(int start, int end) {\n this.start = start;\n this.end = end;\n setup(this, start, end);\n }\n public void setup(SegmentTree node, int start, int end) {\n if (start == end) return;\n int mid = start + (end - start) / 2;\n if (node.left == null) {\n node.left = new SegmentTree(start, mid);\n node.right = new SegmentTree(mid + 1, end);\n }\n setup(node.left, start, mid);\n setup(node.right, mid + 1, end);\n node.val = Math.max(node.left.val, node.right.val);\n }\n \n public void update(SegmentTree node, int index, int val) {\n if (index < node.start || index > node.end) return;\n if (node.start == node.end && node.start == index) {\n node.val = val;\n return;\n }\n update(node.left, index, val);\n update(node.right, index, val);\n node.val = Math.max(node.left.val, node.right.val);\n }\n \n public int rangeMaxQuery(SegmentTree node, int start, int end) {\n if (node.start > end || node.end < start) return 0;\n if (node.start >= start && node.end <= end) return node.val;\n return Math.max(rangeMaxQuery(node.left, start, end), rangeMaxQuery(node.right, start, end));\n }\n}\n``` | 15 | 0 | ['Tree', 'Java'] | 4 |
longest-increasing-subsequence-ii | Segemet Tree || C++ || Max Range Query | segemet-tree-c-max-range-query-by-surajp-ep4b | \n\n\tclass SegmentTree{\n\t\tpublic:\n vector<int> t;\n int n;\n \n SegmentTree(int n){\n this->n = n;\n t.as | surajpatel | NORMAL | 2022-09-11T04:03:26.047112+00:00 | 2022-09-11T04:10:22.007987+00:00 | 2,120 | false | ```\n\n\tclass SegmentTree{\n\t\tpublic:\n vector<int> t;\n int n;\n \n SegmentTree(int n){\n this->n = n;\n t.assign(4*n,0);\n }\n \n int get(int v,int l,int r,int tl,int tr){\n if(l>r) return 0;\n\n if(l==tl&&tr==r){\n return t[v];\n }\n\n int m = (tl+tr)/2;\n\n int left = get(2*v,l,min(m,r),tl,m);\n int right = get(2*v+1,max(m+1,l),r,m+1,tr);\n\n return max(left,right);\n }\n void update(int v, int tl, int tr, int pos, int new_val) {\n if (tl == tr) {\n t[v] = new_val;\n } \n else {\n int tm = (tl + tr) / 2;\n if (pos <= tm)\n update(v*2, tl, tm, pos, new_val);\n else\n update(v*2+1, tm+1, tr, pos, new_val);\n t[v] = max(t[v*2], t[v*2+1]);\n }\n }\n \n };\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n SegmentTree tr(100002);\n int ans = 0;\n for(int i : nums){\n int val = tr.get(1, max(i-k,0), max(i-1,0), 0, 1e5);\n ans = max(ans,val+1);\n tr.update(1, 0, 1e5, i, val+1);\n }\n return ans; \n }\n\n\n``` | 13 | 1 | ['C'] | 3 |
longest-increasing-subsequence-ii | Approach of this question if asked in Interview. | approach-of-this-question-if-asked-in-in-ra2x | Think of the brute-force solution for this problem: for each element nums[i], you compare it with all previous elements nums[j]. If nums[i] is greater than nums | gaurav621 | NORMAL | 2024-10-21T19:33:04.719079+00:00 | 2024-10-21T19:33:04.719118+00:00 | 836 | false | 1. Think of the brute-force solution for this problem: for each element `nums[i]`, you compare it with all previous elements `nums[j]`. If `nums[i]` is greater than `nums[j]` and the difference between them is less than or equal to k, you can extend the subsequence. To keep track of the length of subsequences, you store the results in a temp array. Initially, each element has a subsequence length of 1 (itself). As you check each pair of elements, you update the length of the subsequence by adding 1 to the value in `temp[j]` and storing it in `temp[i]`. This way, for the next element, you already know the length of the longest subsequence ending at each point, and you can build on that result. Finally, you keep track of the maximum subsequence length found so far.\n \n# Code\n```java []\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n int[] temp = new int[nums.length];\n int ans = 1;\n Arrays.fill(temp, 1);\n for(int i = 1; i < nums.length; i++) {\n for(int j = 0; j < i; j++) {\n if(nums[i] > nums[j] && nums[i] - nums[j] <= k) {\n temp[i] = Math.max(temp[i], temp[j] + 1);\n ans = Math.max(temp[i], ans);\n }\n }\n }\n return ans;\n }\n}\n```\nTime Complexity : $$O(n^2)$$ \nSpace Complexity: $$O(n)$$ \n\n2. Now you can think to optimize this, for that instead of comparing every element `nums[i]` with all previous elements, you limit the range of comparisons to just the numbers between `nums[i] - k` and `nums[i] - 1`. This reduces unnecessary checks. For each `nums[i]`, you update a temp array that stores the length of the subsequence ending at each number. You check all potential previous elements in the range, update `temp[nums[i]]` by adding 1 to the maximum value found in that range, and store the result. This way, you build the subsequence efficiently and track the longest subsequence found.\n```java []\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n int[] temp = new int[100001];\n int ans = 1;\n for(int i = 0; i < nums.length; i++) {\n for(int j = Math.max(0, nums[i] - k); j < nums[i]; j++) {\n temp[nums[i]] = Math.max(temp[nums[i]], temp[j] + 1);\n }\n ans = Math.max(ans, temp[nums[i]]);\n }\n return ans;\n }\n}\n```\nTime Complexity : $$O(n*k)$$ \nSpace Complexity: $$O(100001)$$ \n\n3. Now if you noticed here you can optimized this further if you can store max subsequence for last `k` elements and also updates it when result change for any element within that range.\n`Ahh, range update means SEGMENT TREE`\nIn this further optimized solution, a segment tree is used to efficiently track and update the lengths of subsequences. The segment tree helps manage ranges of values and allows fast querying of the maximum subsequence length in a given range.\n\nFor each element `nums[i]`, instead of checking all previous elements, you query the segment tree to get the maximum subsequence length in the range `(nums[i] - k, nums[i] - 1)`. This value is then incremented by 1, representing the length of the subsequence ending at `nums[i]`. You update the tree with this new value, ensuring future queries can quickly find the updated subsequence length. The segment tree enables efficient querying and updating, making the solution faster by avoiding direct comparisons with every previous element.\n# Code\n```java []\nclass Node {\n Node leftChild;\n Node rightChild;\n int start;\n int end;\n int value;\n\n public Node(int start, int end, int value) {\n this.start = start;\n this.end = end;\n this.value = value;\n }\n}\n\nclass Solution {\n Node buildSegmentTree(int start, int end) {\n if (start == end)\n return new Node(start, end, 0);\n Node node = new Node(start, end, 0);\n int mid = (start + end) / 2;\n node.leftChild = buildSegmentTree(start, mid);\n node.rightChild = buildSegmentTree(mid + 1, end);\n return node;\n }\n\n int queryRangeMax(Node node, int l, int r) {\n if (node == null || l > node.end || r < node.start)\n return 0; // Return 0 for out-of-bound queries\n if (l <= node.start && r >= node.end)\n return node.value; // Total overlap\n // Partial overlap\n return Math.max(queryRangeMax(node.leftChild, l, r), queryRangeMax(node.rightChild, l, r));\n }\n\n void updateSegmentTree(Node node, int index, int value) {\n if (node == null || index < node.start || index > node.end)\n return; // Out of bounds\n node.value = Math.max(value, node.value); // Update the current node\n if (node.start != node.end) { // If it\'s not a leaf node\n updateSegmentTree(node.leftChild, index, value);\n updateSegmentTree(node.rightChild, index, value);\n }\n }\n\n public int lengthOfLIS(int[] nums, int k) {\n Node root = buildSegmentTree(0, 100001);\n int ans = 1;\n for (int num : nums) {\n int maxValInRange = queryRangeMax(root, Math.max(0, num - k), num - 1) + 1;\n ans = Math.max(ans, maxValInRange);\n updateSegmentTree(root, num, maxValInRange);\n }\n return ans;\n }\n}\n```\nTime Complexity : $$O(nlogn)$$ \nSpace Complexity: $$O(n)$$ \n\n*You can also use array for implementing segment tree.\n | 12 | 0 | ['Java'] | 2 |
longest-increasing-subsequence-ii | why can't we use DP | why-cant-we-use-dp-by-dr-blue-cyber-h6pb | I trying my dp approach to solve this problem and hence it took me nearly 1 hour and 15 minutes and able to solve only two problems this time\n\nmy question is | dr-blue-cyber | NORMAL | 2022-09-11T04:25:01.912708+00:00 | 2022-09-11T04:25:01.912745+00:00 | 4,268 | false | I trying my dp approach to solve this problem and hence it took me nearly 1 hour and 15 minutes and able to solve only two problems this time\n\n**my question is that, why aren\'t we use DP here ??** | 9 | 1 | [] | 11 |
longest-increasing-subsequence-ii | C++ | Segment Tree | Cleanest Code | Easiest to understand | c-segment-tree-cleanest-code-easiest-to-gjslz | \nconst int N=100005;\nclass Solution {\npublic:\n vector<int> tree;\n void update(int p,int val,int idx,int l,int r){\n if(p<l or p>r){\n | GeekyBits | NORMAL | 2022-10-30T14:04:15.711596+00:00 | 2022-10-30T14:04:15.711632+00:00 | 1,084 | false | ```\nconst int N=100005;\nclass Solution {\npublic:\n vector<int> tree;\n void update(int p,int val,int idx,int l,int r){\n if(p<l or p>r){\n return;\n }\n if(l==r){\n tree[idx]=val;\n return;\n }\n int mid=(l+r)>>1;\n update(p,val,2*idx+1,l,mid);\n update(p,val,2*idx+2,mid+1,r);\n tree[idx]=max(tree[2*idx+1],tree[2*idx+2]);\n }\n int query(int ql,int qr,int idx,int l,int r){\n if(ql>r or qr<l){\n return INT_MIN;\n }\n if(ql<=l and qr>=r){\n return tree[idx];\n }\n int mid=(l+r)>>1;\n int lt=query(ql,qr,2*idx+1,l,mid);\n int rt=query(ql,qr,2*idx+2,mid+1,r);\n return max(lt,rt);\n }\n int lengthOfLIS(vector<int>& nums, int k) {\n int n=nums.size();\n int res=0;\n tree=vector<int> (4*N,0);\n //normally if we had to write dp arroach what would we have done\n //we would have checked if the LIS ends at our current nums[i]\n //then we would iterate over from 0 till i-1 and consider those nums[i] whose diff with this nums[i] is atmost k\n //and take the longest one among them and add 1\n //but this would result in TLE here,so here we optimized that query using segment tree\n for(int i=0;i<nums.size();i++){\n int left=max(0,nums[i]-k);\n int right=nums[i]-1;\n int q=query(left,right,0,0,1e5);\n res=max(res,q+1);\n update(nums[i],q+1,0,0,1e5);\n }\n return res;\n }\n};\n``` | 8 | 0 | [] | 1 |
longest-increasing-subsequence-ii | Python Easy Solution Well Explained | python-easy-solution-well-explained-by-s-1zcp | \n# Iterative Segment Tree\nclass SegmentTree:\n def __init__(self, n, fn):\n self.n = n\n self.fn = fn\n self.tree = [0] * (2 * n)\n | shiv-codes | NORMAL | 2022-09-11T11:12:39.792573+00:00 | 2022-09-13T07:19:17.013200+00:00 | 2,621 | false | ```\n# Iterative Segment Tree\nclass SegmentTree:\n def __init__(self, n, fn):\n self.n = n\n self.fn = fn\n self.tree = [0] * (2 * n)\n \n def query(self, l, r):\n l += self.n\n r += self.n\n res = 0\n while l < r:\n if l & 1:\n res = self.fn(res, self.tree[l])\n l += 1\n if r & 1:\n r -= 1\n res = self.fn(res, self.tree[r])\n l >>= 1\n r >>= 1\n return res\n \n def update(self, i, val):\n i += self.n\n self.tree[i] = val\n while i > 1:\n i >>= 1\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\nclass Solution:\n # Inspired from the solution of Bakerston\n # Basically we make an array to store nums in increasing order and find what is the size of the LIS ending there\n\t# Our array is 0 to max element from the given nums\n # We need to find the elements smaller than n till the limit k which are in nums before this num\n # so simply all the elements previous to our current num are smaller(till k smaller)\n # now how to find LIS\'s size?\n # Since we are updating elements left to right in our array we know the LIS\'s size of elements smaller\n # than our current num\n # we just need to find the largest LIS size in range (num - k, num) from our array\n # This is a range query and can be efficiently answered using Segment Trees.\n \n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = max(nums)\n res = 1\n tree = SegmentTree(n, max)\n for num in nums:\n num -= 1\n mm = tree.query(max(0, num - k), num)\n tree.update(num, mm + 1)\n res = max(res, mm + 1)\n return res\n``` | 8 | 0 | ['Tree', 'Python', 'Python3'] | 2 |
longest-increasing-subsequence-ii | 💥Memory beats 100% [EXPLAINED] | memory-beats-100-explained-by-r9n-ywo6 | IntuitionFind the longest increasing subsequence where the difference between any two adjacent numbers is at most k. To solve it, we need a data structure that | r9n | NORMAL | 2024-12-24T11:35:38.841635+00:00 | 2024-12-24T11:35:38.841635+00:00 | 257 | false | # Intuition
Find the longest increasing subsequence where the difference between any two adjacent numbers is at most k. To solve it, we need a data structure that can efficiently store and update the maximum length of valid subsequences for each possible number.
# Approach
I've used a segment tree to maintain the maximum subsequence length for every possible number, and for each element in the input array, we query the tree to find the longest subsequence that can end with a number less than or equal to the current number, ensuring the difference constraint is satisfied.
# Complexity
- Time complexity:
O(n log N), where n is the size of the input array, and N is the range of possible values (up to 100000). This is because each update and query operation in the segment tree takes O(log N) time.
- Space complexity:
O(N) due to the segment tree storage, where N is the range of values in the input array.
# Code
```csharp []
public class SegmentTree {
private int[] st;
private int n;
// Constructor initializes the segment tree with a size based on the input range
public SegmentTree(int n) {
this.n = n;
st = new int[4 * n];
}
// Public method to update the segment tree with a new value at index 'i'
public void Update(int i, int value) {
Update(1, 0, n - 1, i, value);
}
// Helper method to propagate the update in the segment tree
private void Update(int node, int beg, int end, int i, int value) {
if (beg == end) {
st[node] = Math.Max(st[node], value); // Store the maximum value at this index
return;
}
int mid = (beg + end) / 2;
// Recursively update the left or right segment based on the index
if (i <= mid) Update(2 * node, beg, mid, i, value);
else Update(2 * node + 1, mid + 1, end, i, value);
// After the update, recalculate the maximum value for the current node
st[node] = Math.Max(st[2 * node], st[2 * node + 1]);
}
// Public method to query the maximum value in the range [i, j]
public int Query(int i, int j) {
return Query(1, 0, n - 1, i, j);
}
// Helper method to query the segment tree for the maximum value in the range [i, j]
private int Query(int node, int beg, int end, int i, int j) {
if (end < i || beg > j) return 0; // No overlap, return 0
if (i <= beg && end <= j) return st[node]; // Fully inside the range, return value at this node
int mid = (beg + end) / 2;
// Recursively query the left and right segments and return the maximum
return Math.Max(Query(2 * node, beg, mid, i, j), Query(2 * node + 1, mid + 1, end, i, j));
}
}
public class Solution {
public int LengthOfLIS(int[] a, int k) {
int n = a.Length;
var tree = new SegmentTree((int)1e5 + 1); // Initialize segment tree with range size
int maxLength = 0;
// Iterate through the array to calculate the LIS
for (int i = 0; i < n; i++) {
int left = Math.Max(0, a[i] - k); // Find the left bound for the query
int right = a[i] - 1; // Find the right bound for the query
int dpValue = tree.Query(left, right) + 1; // Calculate the LIS for this element
tree.Update(a[i], dpValue); // Update the segment tree with the new LIS value
maxLength = Math.Max(maxLength, dpValue); // Keep track of the maximum LIS length
}
return maxLength; // Return the longest increasing subsequence length
}
}
``` | 7 | 0 | ['Array', 'Divide and Conquer', 'Dynamic Programming', 'Binary Indexed Tree', 'Segment Tree', 'Queue', 'C#'] | 0 |
longest-increasing-subsequence-ii | C++ | Sqrt Decomposition + dp | O(n*sqrt(n)) | explanation | c-sqrt-decomposition-dp-onsqrtn-explanat-hpwj | \nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int ma=0,dp[318][318];\n memset(dp,0,sizeof(dp));\n for(int | SunGod1223 | NORMAL | 2022-09-11T19:30:47.391604+00:00 | 2022-09-11T19:30:47.391642+00:00 | 1,658 | false | ```\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int ma=0,dp[318][318];\n memset(dp,0,sizeof(dp));\n for(int i=0;i<nums.size();++i){\n if(i&&nums[i]==nums[i-1])continue;\n int v=nums[i]-1,t=max(nums[i]-k,0),vh=v%317,vn=v/317,vnh=nums[i]%317,vnn=nums[i]/317;\n if(vn==t/317)\n for(int j=v%317;j>=t%317;--j)\n dp[vnn][vnh]=max(dp[vn][j]+1,dp[vnn][vnh]);\n else{\n for(int j=v%317;j>=0;--j)\n dp[vnn][vnh]=max(dp[vn][j]+1,dp[vnn][vnh]);\n for(int j=vn-1;j>t/317;--j)\n dp[vnn][vnh]=max(dp[j][317]+1,dp[vnn][vnh]);\n for(int j=316;j>=t%317;--j)\n dp[vnn][vnh]=max(dp[t/317][j]+1,dp[vnn][vnh]);\n }\n dp[vnn][317]=max(dp[vnn][vnh],dp[vnn][317]);\n ma=max(ma,dp[vnn][vnh]);\n }\n return ma;\n }\n};\n```\n1. DP[i] means the LIS ending with i\n2. DP[i] = max(DP[i], DP[i-1~i-k]) \n3. Let dp[i][j] = DP[i*m+j] (0 < j < m)\n4. Let dp[i][317] = max value of i*317 + 0~316\n5. dp[i][j] = value of i*317 + 0~316\n6. If k is big: search dp[i][317]\n else: search each dp[i][j] | 7 | 0 | ['Dynamic Programming', 'C'] | 3 |
longest-increasing-subsequence-ii | Python Binary Search and dp without segment tree | python-binary-search-and-dp-without-segm-2mdz | \nfrom collections import defaultdict\nfrom bisect import insort, bisect_left\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n | chinmaybharti00 | NORMAL | 2022-09-11T06:14:05.782534+00:00 | 2022-09-11T06:16:18.580855+00:00 | 2,925 | false | ```\nfrom collections import defaultdict\nfrom bisect import insort, bisect_left\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n \n dp_tracker = defaultdict(list)\n n = len(nums)\n dp = [1]*n\n max_till_now = 1\n for i in range(n):\n temp_ans = 1\n max_ans = 0\n \n for j in range(max_till_now, 0, -1):\n ind = bisect_left(dp_tracker[j], nums[i])\n if ind != 0:\n if k >= (nums[i] - dp_tracker[j][ind-1]) > 0:\n max_ans = j\n break\n \n dp[i] = temp_ans + max_ans\n bisect.insort(dp_tracker[dp[i]], nums[i])\n \n max_till_now = max(max_till_now, dp[i])\n \n return max(dp)\n``` | 7 | 1 | ['Binary Search', 'Dynamic Programming', 'Python'] | 3 |
longest-increasing-subsequence-ii | [Python] n^2 solution but AC - numpy | python-n2-solution-but-ac-numpy-by-penol-j4so | I\'m sorry that using numpy \n\npython\nimport numpy as np\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n\t\t# original thinking | penolove | NORMAL | 2022-09-11T04:38:06.826460+00:00 | 2022-09-11T04:45:28.258381+00:00 | 949 | false | I\'m sorry that using numpy \n\n```python\nimport numpy as np\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n\t\t# original thinking, but I know it must TLE\n # len_mapping = {}\n # max_len = 0\n # for i in nums:\n # len_mapping[i] = max([c + 1 for v, c in len_mapping.items() if (i - v) >= 0 and (i - v) <= k], default=1)\n # max_len = max(len_mapping[i], max_len)\n # return max_len\n\t\t\n\t\t# but I don\'t want to implement segement tree, so I give numpy a try\n\t\t# while in the inteview you should always use the segment tree which lead to nlogn instead of n^2\n len_mapping = np.array([0] * (10** 5 + 2))\n max_len = 0\n for i in nums:\n start_idx = max(i - k, 0)\n len_mapping[i] = (len_mapping[start_idx:i].max()) + 1\n max_len = max(len_mapping[i], max_len)\n return max_len\n```\n | 7 | 2 | [] | 2 |
longest-increasing-subsequence-ii | [Python] Segment Tree - Clean & Concise | python-segment-tree-clean-concise-by-hie-v3ze | Intuition\n- Use Segment Tree to query maximum of element in range [num-k, num-1], which mean to find the maximum existed Longest Increase Subsequence such that | hiepit | NORMAL | 2022-12-15T00:45:17.123551+00:00 | 2022-12-15T00:46:58.552916+00:00 | 749 | false | # Intuition\n- Use Segment Tree to query maximum of element in range [num-k, num-1], which mean to find the maximum existed Longest Increase Subsequence such that the maximum difference between consecutives element <= k.\n\n# Complexity\n- Time: `O(N * logMAX + MAX)`, where `N <= 10^5` is length of nums array, `MAX <= 10^5` is maximum element in nums array.\n- Space complexity: `O(MAX)`\n\n# Code\n```python\nclass SegmentTree:\n def __init__(self, n):\n self.n = n\n self.tree = [0] * 4 * self.n\n\n def query(self, left, right, index, qleft, qright):\n if qright < left or qleft > right:\n return 0\n\n if qleft <= left and right <= qright:\n return self.tree[index]\n\n mid = (left + right) // 2\n resLeft = self.query(left, mid, 2*index+1, qleft, qright)\n resRight = self.query(mid+1, right, 2*index+2, qleft, qright)\n return max(resLeft, resRight)\n\n def update(self, left, right, index, pos, val):\n if left == right:\n self.tree[index] = val\n return\n\n mid = (left + right) // 2\n if pos <= mid:\n self.update(left, mid, 2*index+1, pos, val)\n else:\n self.update(mid+1, right, 2*index+2, pos, val)\n self.tree[index] = max(self.tree[2*index+1], self.tree[2*index+2])\n\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n mx = max(nums)\n segmentTree = SegmentTree(mx + 1)\n ans = 0\n for num in nums:\n subLongest = segmentTree.query(0, segmentTree.n-1, 0, num-k, num-1) + 1\n ans = max(ans, subLongest)\n segmentTree.update(0, segmentTree.n-1, 0, num, subLongest)\n return ans\n``` | 5 | 0 | ['Segment Tree', 'Python3'] | 2 |
longest-increasing-subsequence-ii | C++ || Fast || Easy || Segment Tree | c-fast-easy-segment-tree-by-kniccknacc-nmo9 | Link to the submission stats:\nhttps://leetcode.com/submissions/detail/797375784/\n\n\nclass Solution {\npublic:\n vector<int> seg;\nvector<int> ar;\nint x;\ | kniccknacc | NORMAL | 2022-09-11T19:39:53.365405+00:00 | 2022-09-11T19:39:53.365443+00:00 | 1,860 | false | Link to the submission stats:\nhttps://leetcode.com/submissions/detail/797375784/\n\n```\nclass Solution {\npublic:\n vector<int> seg;\nvector<int> ar;\nint x;\n\nvoid build(int v, int l, int r) {\n if (l == r) {\n seg[v] = ar[l];\n }\n else {\n int mid = (l + r) / 2;\n build(2 * v, l, mid);\n build(2 * v + 1, mid + 1, r);\n seg[v] = max(seg[2 * v], seg[2 * v + 1]);\n }\n}\n\nint f(int v, int a, int b, int l, int r) {\n //cout << a << " " << b << " " << l << " " << r << endl;\n if (l > r) {return 0;}\n if (a == l && b == r) {return seg[v];}\n if(l==r){return seg[l];}\n int mid = (a + b) / 2;\n return max(\n f(2 * v, a, mid, l, min(mid, r)),\n f(2 * v + 1, mid + 1, b, max(l, mid + 1), r)\n );\n}\n\nvoid update(int a, int k) {\n if(a==1){\n int xx=x;\n while(xx>=1){seg[xx]=max(seg[xx],1);xx/=2;}\n return;\n }\n int val = f(1, x, 2 * x - 1, max(x, x - 1 + a - k), max(x, x - 1 + a - 1));\n int nn = x - 1 + a;\n val = max(val + 1, 1);\n //cout << val << endl;\n while (nn >= 1) {\n seg[nn] = max(seg[nn],val); nn /= 2;\n }\n}\n\nint lengthOfLIS(vector<int>& nums, int k) {\n x = 0; for (int xx : nums) {x = max(x, xx);}\n int xx = log2(x);\n if ((1 << xx) != x) {\n xx++;\n }\n ar = nums;\n x = 1 << xx;\n while (ar.size() < x) {ar.push_back(0);}\n seg.resize(2 * x);\n for (int i = 0; i < 2 * x; i++) {seg[i] = 0;}\n\n //build(1, 0, x - 1);\n /* for (int i = 1; i < 2 * x; i++) {\n cout << seg[i] << " ";\n if ((1 << ((int)log2(i + 1)) - 1) == (1 << ((int)log2(i)))) {cout << endl;}\n }\n cout << endl;*/\n //return 0;\n int ans = 0;\n for (int a : nums) {\n update(a, k);\n /* for (int i = 1; i < 2 * x; i++) {\n cout << seg[i] << " ";\n if ((1 << ((int)log2(i + 1)) - 1) == (1 << ((int)log2(i)))) {cout << endl;}\n }\n cout << endl;*/\n ans = max(ans, seg[a + x - 1]);\n }\n return ans;\n}\n};\n``` | 5 | 0 | [] | 2 |
longest-increasing-subsequence-ii | Java Easy Segment Tree | java-easy-segment-tree-by-gurkaran_s-eh1l | ```\nclass Solution {\n int N = 1_00_001;\n int seg[];\n void update(int idx , int x , int low , int high , int i){\n if(low == high){\n | gurkaran_s | NORMAL | 2022-09-11T05:56:30.117669+00:00 | 2022-09-11T05:56:30.117706+00:00 | 783 | false | ```\nclass Solution {\n int N = 1_00_001;\n int seg[];\n void update(int idx , int x , int low , int high , int i){\n if(low == high){\n seg[idx] = x;\n return;\n }\n int mid = low + (high - low) / 2;\n if(i <= mid){\n update(2 * idx + 1 , x , low , mid , i);\n }\n else{\n update(2 * idx + 2 , x , mid + 1 , high , i);\n }\n seg[idx] = Math.max(seg[2 * idx + 1], seg[2 * idx + 2]);\n }\n int query(int l , int r , int low , int high , int idx){ // max query\n if(l > high || r < low){\n return Integer.MIN_VALUE;\n }\n if(low >= l && high <= r){\n return seg[idx];\n }\n int mid = low + (high - low) / 2;\n int left = query(l , r , low , mid , 2 * idx + 1);\n int right = query(l , r , mid + 1 , high , 2 * idx + 2);\n return Math.max(left , right);\n }\n public int lengthOfLIS(int[] a, int k) {\n int n = a.length;\n int max = 0;\n seg = new int[4 * N];\n for(int i = 0; i < n; i++){\n int l = Math.max(0 , a[i] - k);\n int r = a[i] - 1;\n int res = query(l , r , 0 , N - 1 , 0) + 1; // search in all the possible previous elements ([l , r]) and add \'1\' to the max length with this previous\n max = Math.max(max , res); // update max\n update(0 , res , 0 , N - 1 , a[i]); // update segment tree\'s a[i]th index with res\n }\n return max;\n }\n} | 5 | 0 | ['Tree', 'Java'] | 1 |
longest-increasing-subsequence-ii | Python | Easy | Queue | Longest Increasing Subsequence II | python-easy-queue-longest-increasing-sub-2vsi | \nsee the Successfully Accepted Submission\nPython\n# Define a MaxSegmentTree class with a constructor that takes the size \'n\' as input.\nclass MaxSegmentTree | Khosiyat | NORMAL | 2023-10-11T15:19:48.008395+00:00 | 2023-10-11T15:19:48.008419+00:00 | 384 | false | \n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1071709047/)\n```Python\n# Define a MaxSegmentTree class with a constructor that takes the size \'n\' as input.\nclass MaxSegmentTree:\n def __init__(self, n):\n # Store the size \'n\' as an instance variable.\n self.n = n\n # Initialize the tree as a list with 4 times the size \'n\' filled with zeros.\n self.tree = [0] * (4 * n)\n\n # Define a method to get the maximum value of the tree.\n def max_value(self):\n return self.tree[0]\n\n # Define a query method that takes left and right query boundaries \'qL\' and \'qR\' as inputs.\n def query(self, qL, qR):\n # Call the query_util method to perform the query operation.\n return self.query_util(0, 0, self.n - 1, qL, qR)\n\n # Define a recursive utility function for the query operation.\n def query_util(self, i, l, r, qL, qR):\n # If the current segment [l, r] is completely inside the query range [qL, qR], return the value at node \'i\'.\n if l >= qL and r <= qR:\n return self.tree[i]\n # If the current segment [l, r] is completely outside the query range [qL, qR], return negative infinity.\n if l > qR or r < qL:\n return float(\'-inf\')\n\n # Calculate the middle index \'m\' of the current segment.\n m = (l + r) // 2\n # Recursively query the left and right subtrees and return the maximum of the two results.\n return max(\n self.query_util(2 * i + 1, l, m, qL, qR),\n self.query_util(2 * i + 2, m + 1, r, qL, qR)\n )\n\n # Define an update method that takes a position \'pos\' and a value \'val\' as inputs.\n def update(self, pos, val):\n # Call the update_util method to update the tree.\n self.update_util(0, 0, self.n - 1, pos, val)\n\n # Define a recursive utility function for updating the tree.\n def update_util(self, i, l, r, pos, val):\n # If the position \'pos\' is outside the current segment [l, r], return.\n if pos < l or pos > r:\n return\n # If the current segment [l, r] has a single element (leaf node), update it with the maximum of \'val\' and the current value at node \'i\'.\n if l == r:\n self.tree[i] = max(val, self.tree[i])\n return\n\n # Calculate the middle index \'m\' of the current segment.\n m = (l + r) // 2\n # Recursively update the left and right subtrees.\n self.update_util(2 * i + 1, l, m, pos, val)\n self.update_util(2 * i + 2, m + 1, r, pos, val)\n # Update the current node \'i\' with the maximum of its left and right children.\n self.tree[i] = max(self.tree[2 * i + 1], self.tree[2 * i + 2])\n\n# Define a Solution class.\nclass Solution:\n # Define a method \'lengthOfLIS\' that takes \'nums\' and \'k\' as inputs.\n def lengthOfLIS(self, nums, k):\n # Create an instance of the MaxSegmentTree class with a size of (10^5 + 1).\n tree = MaxSegmentTree(int(1e5) + 1)\n # Iterate through the elements in \'nums\'.\n for i in nums:\n # Calculate the lower bound for the query.\n lower = max(0, i - k)\n # Query the tree for the maximum value within the specified range.\n cur = 1 + tree.query(lower, i - 1)\n # Update the tree at position \'i\' with the calculated value \'cur\'.\n tree.update(i, cur)\n\n # Return the maximum value in the tree, which represents the length of the longest increasing subsequence.\n return tree.max_value()\n```\n\n\n | 4 | 0 | ['Queue', 'Python'] | 0 |
longest-increasing-subsequence-ii | Does anyone know a monotonic queue solution? | does-anyone-know-a-monotonic-queue-solut-av4w | Does anyone know a monotonic queue solution? | roishevah | NORMAL | 2023-06-22T07:08:38.948317+00:00 | 2023-06-22T07:08:38.948340+00:00 | 325 | false | Does anyone know a monotonic queue solution? | 4 | 0 | ['Monotonic Queue'] | 1 |
longest-increasing-subsequence-ii | Q (Help) | Why python segment tree is TLE | q-help-why-python-segment-tree-is-tle-by-kfaj | I don\'t understand why this python Segment Tree solution TLE\'s.\n\nWhat am I doing wrong? help will be appreciated\n\n\nclass SegmentTree:\n \n def __in | nadaralp | NORMAL | 2022-09-11T09:06:20.957134+00:00 | 2022-09-11T09:07:11.773498+00:00 | 897 | false | I don\'t understand why this python Segment Tree solution TLE\'s.\n\nWhat am I doing wrong? help will be appreciated\n\n```\nclass SegmentTree:\n \n def __init__(self, A: list[int]):\n n = len(A)\n closest_2_power = math.ceil(math.log2(n))\n # pad\n A += [0] * ((2 << (closest_2_power-1)) - n)\n \n self._closest_2_power = closest_2_power\n self._arr = A\n self.tree = [0] * (2*len(A) - 1)\n \n self._build_segtree(0, 0, len(self._arr) - 1)\n \n \n # Building maximum query segment tree\n def _build_segtree(self, tree_index, left, right):\n # Leaf node\n if left == right:\n self.tree[tree_index] = self._arr[left]\n return self.tree[tree_index]\n \n mid = left + (right - left) // 2\n left_seg = self._build_segtree(tree_index * 2 + 1, left, mid)\n right_seg = self._build_segtree(tree_index * 2 + 2, mid + 1, right)\n return max(left_seg, right_seg)\n \n def query(self, query_left, query_right, tree_index = None, seg_left = None, seg_right = None):\n # default values\n if seg_left is None:\n seg_left = 0\n if seg_right is None:\n seg_right = len(self._arr) - 1\n if tree_index is None:\n tree_index = 0\n \n # if segment interval is fully contained by query\n if query_left <= seg_left and query_right >= seg_right:\n return self.tree[tree_index]\n \n # if not contained\n if query_right < seg_left or query_left > seg_right:\n return 0\n \n # else divide and conquer both sides\n mid = seg_left + (seg_right - seg_left) // 2\n left_seg = self.query(query_left, query_right, tree_index*2+1, seg_left, mid)\n right_seg = self.query(query_left, query_right, tree_index*2+2, mid + 1, seg_right)\n return max(left_seg, right_seg)\n \n \n def update(self, original_index, new_value):\n first_leaf_index = (2 ** self._closest_2_power) - 1\n tree_index = first_leaf_index + original_index\n self.tree[tree_index] = new_value\n \n # update parent interval\n parent_index = (tree_index - 1) // 2\n while parent_index >= 0:\n self.tree[parent_index] = max(self.tree[parent_index], new_value)\n parent_index = (parent_index - 1) // 2\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n MAX = max(nums)\n A = [0] * (MAX + 1)\n \n seg_tree = SegmentTree(A)\n ans = 0\n \n for v in nums:\n max_interval_sum = seg_tree.query(max(0, v-k), v-1)\n v_lis = max(1, 1 + max_interval_sum)\n seg_tree.update(v, v_lis)\n ans = max(ans, v_lis)\n return ans\n``` | 4 | 0 | ['Python'] | 4 |
longest-increasing-subsequence-ii | [Python3] MonoQ Without SegTree, 100% TC | python3-monoq-without-segtree-100-tc-by-j3m5h | Intuition\nWould it be easier if we change the constraint from 0 < nums[i]-nums[j] <= k to 0 < i-j <= k for adjacent elements in the subsequence? \n\n# Approach | zsq007 | NORMAL | 2024-05-01T04:19:39.848425+00:00 | 2024-11-12T17:36:01.792936+00:00 | 391 | false | # Intuition\nWould it be easier if we change the constraint from `0 < nums[i]-nums[j] <= k` to `0 < i-j <= k` for adjacent elements in the subsequence? \n\n# Approach\n\nTo convert the condition, we invert the array from `nums[ind]` to `inds[num]`, sort the indices by the numbers, and search for the LIS on it. Imagine reflecting the function $num(ind)$ on $y=x$ to its inverse $num^{-1}(ind)$, the increasing subsequences will remain the same.\n\nThe **Monotonic Queue** method can then be adapted here. We use a sorted list to simulate the mono-queue. Iterating through the sorted `inds[num]` with a **sliding window**, we remove stale elements from the queue and find the LIS among the current valid elements.\n\nNote that the complexity is $O(n \\log n)$, making it work for even larger $k$ and `nums[i]`.\n\n- **Edit**: Thanks to @*Vinson Liu* for pointing out a flaw in the code. Elements in mono queue/stack can be replaced only when its `lens` is one larger than the previous one. Otherwise, the new element should be inserted.\n\n# Complexity\n- Time complexity: $O(n \\log n)$\n- Space complexity: $O(n)$\n\n# Code\n```python\nfrom sortedcontainers import SortedList\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n ptr, n, monoQ = 0, len(nums), SortedList([-1])\n lens, inv = [0]*(n+1), sorted(range(n), key=lambda i: (nums[i],-i))\n\n for ind in inv:\n # Remove stale indices\n while nums[inv[ptr]] < nums[ind]-k:\n monoQ.discard(inv[ptr])\n ptr += 1\n\n # Original LIS MonoQueue operations\n j = monoQ.bisect(ind)\n if j < len(monoQ) and lens[monoQ[j]] == lens[monoQ[j-1]] + 1:\n monoQ.pop(j)\n monoQ.add(ind)\n lens[ind] = lens[monoQ[j-1]]+1\n\n return max(lens)\n```\nIt turns out that list `pop/insert` achieves even better runtime ~160 ms (quadratic complexity though).\n```python\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n ptr, n, stack = 0, len(nums), [-1]\n lens, inv = [0]*(n+1), sorted(range(n), key=lambda i: (nums[i],-i))\n\n for ind in inv:\n while nums[inv[ptr]] < nums[ind]-k:\n j = bisect_left(stack,inv[ptr])\n if j < len(stack) and stack[j] == inv[ptr]:\n stack.pop(j)\n ptr += 1\n\n j = bisect_left(stack,ind)\n if j < len(stack) and lens[stack[j]] == lens[stack[j-1]] + 1:\n stack[j] = ind\n else:\n stack.insert(j, ind)\n lens[ind] = lens[stack[j-1]]+1\n return max(lens)\n``` | 3 | 0 | ['Sliding Window', 'Monotonic Queue', 'Python', 'Python3'] | 1 |
longest-increasing-subsequence-ii | Segment Tree Approach - Classical Segment Tree Implementation | segment-tree-approach-classical-segment-zrj93 | Intuition\n Describe your first thoughts on how to solve this problem. \nNotice that the subsequence is strickly increasing and the difference between adjacent | jimkirk | NORMAL | 2024-04-13T20:41:18.551996+00:00 | 2024-04-15T04:02:27.739444+00:00 | 499 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNotice that the subsequence is **strickly increasing** and the difference between adjacent elements in the subsequence is **at most k**.\n\nSo that given the current number is $num$, I need to find the longest-increasing-subsequence of [$left$, $right$], where $left = max(1, num - k)$ and $right = num - 1$.\n\nGiven that this is a problem that needs to find maximum within a certain range effectively, I consider using **segment tree**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAt each value, I just need to find out the maximum length of the longest-increasing-subsequence, then update the existing segment tree.\n\nUse the classical implementation of segment tree.\n\n# Complexity\nAssume the maximum value of nums is $maxValue$. Assume length of nums is $n$.\n\n- Time complexity: Each query O($n$log$maxValue$).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O($maxValue$).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private int size;\n private int[] segment;\n public int lengthOfLIS(int[] nums, int k) {\n size = 0;\n for (int num : nums) {\n size = Math.max(size, num);\n }\n size++;\n segment = new int[2 * size];\n int longest = 0;\n for (int i = 0; i < nums.length; i++) {\n int left = Math.max(1, nums[i] - k);\n int right = nums[i] - 1;\n int curr = query(left, right) + 1;\n longest = Math.max(longest, curr);\n update(nums[i], curr);\n }\n return longest;\n }\n private int query(int left, int right) {\n // edge cases\n if (left > right) {\n return 0;\n }\n // normal cases\n left += size;\n right += size;\n int result = 0;\n while (left <= right) {\n if ((left & 1) == 1) {\n result = Math.max(result, segment[left++]);\n }\n if ((right & 1) == 0) {\n result = Math.max(result, segment[right--]); \n }\n left /= 2;\n right /= 2;\n }\n return result;\n }\n private void update(int index, int value) {\n index += size;\n segment[index] = value;\n for (index /= 2; index >= 1; index /= 2) {\n segment[index] = Math.max(segment[2 * index], segment[2 * index + 1]);\n }\n }\n}\n\n\n``` | 3 | 0 | ['Segment Tree', 'Java'] | 0 |
longest-increasing-subsequence-ii | [Python] A Solution without SegmentTree | python-a-solution-without-segmenttree-by-eu8o | Intuition\n Describe your first thoughts on how to solve this problem. \nSince the constraint is n \leq 10^5, we can\'t use the normal n^2 approach. In the norm | duyvt6663 | NORMAL | 2024-04-09T14:41:48.742035+00:00 | 2024-04-11T02:27:58.857394+00:00 | 335 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the constraint is $$n \\leq 10^5$$, we can\'t use the normal $$n^2$$ approach. In the normal LIS problem, there is the $$O(n\\log n)$$ solution where you update the longest lowest increasing sequences within a single list. My intuition is to expand on that solution here.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy idea is to also do binary search like the normal approach. But to make sure the elements are within $k$ from each other, I won\'t discard larger elements, but keep them all inside a SortedList at each index and retrieve the closest element to the query $$nums[i]$$. If that element falls within range $k$ of $nums[i]$, we can expand the sequence by 1, otherwise we just add it into the SortedList at current index.\n\n# Complexity\n- Time complexity: $$O(n\\log^2 n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe binary search takes $$\\log n$$, coupled with a $$\\log n$$ access from SortedList. We can reduce this to $$O(n\\log n)$$ by storing the min element along with the SortedList, making the access during binary search $$O(1)$$.\n- Space complexity: $O(n\\log n)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n ds = [SortedList([nums[0]])] # list of SortedList\n for i in range(1, len(nums)):\n if nums[i] > ds[-1][-1] + k or nums[i] < ds[0][0]: \n # out of range-k of top or less than bottom\n pos = 0 # reset to 0\n else: # perform binary search on the min of each pos\n s, e = 0, len(ds)-1\n while s < e:\n m = (s + e)//2\n if nums[i] >= ds[m][0]:\n s = m + 1\n else:\n e = m - 1\n pos = s - 1 if nums[i] < ds[s][0] else s\n \n # find the nearest element within k from nums[i] at pos\n j = ds[pos].bisect_left(nums[i]) - 1\n if j != -1 and ds[pos][j] >= nums[i] - k: \n # within range-k -> push to pos + 1\n if pos + 1 >= len(ds):\n ds.append(SortedList([nums[i]]))\n else: \n ds[pos + 1].add(nums[i])\n else: # out of range-k -> pos\n ds[pos].add(nums[i])\n \n # the complexity of this algo is Nlog^2(N)\n return len(ds)\n\n \n \n\n\n\n\n \n\n\n``` | 3 | 0 | ['Binary Search', 'Python3'] | 0 |
longest-increasing-subsequence-ii | DP to Segment Tree (Python) | dp-to-segment-tree-python-by-ewackerbart-3wa3 | Intuition\n Describe your first thoughts on how to solve this problem. \nTo make sense of the accepted segment tree approach, we first need to briefly discuss t | ewackerbarth | NORMAL | 2023-06-22T03:39:21.776782+00:00 | 2023-06-22T03:39:21.776814+00:00 | 424 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo make sense of the accepted segment tree approach, we first need to briefly discuss the relevant dynamic programming approach with $$O(nk)$$ time complexity and $$O(n)$$ space complexity.\n\nWe\'re going to traverse our array nums. For each element $x$ of $nums$, we\'re going to check for the longest increasing subsequence (LIS) that terminated at a value in the following set/interval: {$x - k, x - k + 1, ..., x - 1$}. We will track the prior LIS\'s that terminate at each value $x$ in an array of length equal to max($nums$).\n\nThis looks like:\n```python []\ndef lengthOfLIS(self, nums: List[int], k: int) -> int:\n lis = [0] * max(nums)\n for x in nums:\n intervalStart = max(0, x-1-k)\n for idx in range(intervalStart, x-1):\n lis[x-1] = max(lis[x-1], lis[idx]+1)\n \n return max(lis)\n```\n\nThis approach is TLE, so we need to use some extra space (still maintaining linear complexity) in order to improve our time complexity. This leads us to the segment tree.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe build a binary tree where each node of our tree contains the length of LIS that terminates at a value in some interval $[l, r)$. Naturally, the root node of our tree corresponds to the interval $[1, \\max(nums)+1)$. \n\nConsider a node corresponding to the interval $[l, r)$. Let the midpoint of this interval, $c$, equal the floor of $(l + r) / 2$. Then the left child of this node corresponds to the interval $[l, c)$ and the right child corresponds to the interval $[c, r)$.\n\nWe will represent our tree implicitly by using the Eytzinger layout to map values to an array. Given a node whose value is at array index $m$, its left child is at index $2m$ and its right child is at index $2m + 1$. The root of our tree is at array index 1. \n\nI chose recursive implementations for the update and query methods because those made the most sense to me (I could justify to myself that the node to array index mapping was working and I could easily see how we traversed the tree to find our desired intervals). But I\'m definitely not an expert on segment trees and there are much faster implementations!\n\nPlease consult the following resources:\n- [Segment Trees (Recursive, Iterative, Best Optimizations)](https://en.algorithmica.org/hpc/data-structures/segment-trees/)\n- [Iterative Segment Tree](https://codeforces.com/blog/entry/18051)\n- [Iterative Segment Tree (python implementation)](https://leetcode.com/problems/longest-increasing-subsequence-ii/solutions/2560085/python-explanation-with-pictures-segment-tree/)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n \\log(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```python []\nclass SegmentTree:\n def __init__(self, n):\n self.tree = [0] * 4 * n\n self.n = n\n \n def update(self, l, r, x, val, treeIdx):\n if l == r - 1:\n self.tree[treeIdx] = max(self.tree[treeIdx], val)\n return \n \n c = (l + r) // 2\n if x < c:\n self.update(l, c, x, val, 2 * treeIdx)\n else:\n self.update(c, r, x, val, 2 * treeIdx + 1)\n\n self.tree[treeIdx] = max(self.tree[2 * treeIdx], self.tree[2 * treeIdx + 1])\n \n def query(self, lDesired, rDesired, l, r, treeIdx):\n if lDesired <= l and rDesired >= r:\n return self.tree[treeIdx]\n \n c = (l + r) // 2\n leftMax, rightMax = 0, 0\n if lDesired < c:\n leftMax = self.query(lDesired, rDesired, l, c, 2 * treeIdx)\n if rDesired > c:\n rightMax = self.query(lDesired, rDesired, c, r, 2 * treeIdx + 1)\n \n return max(leftMax, rightMax) \n \nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = max(nums)\n seg = SegmentTree(n)\n for num in nums:\n lis = seg.query(max(1, num - k), num, 1, n+1, 1)\n seg.update(1, n+1, num, lis+1, 1)\n\n #print(f\'seg.tree = {seg.tree}\')\n return seg.tree[1] \n \n``` | 3 | 0 | ['Dynamic Programming', 'Segment Tree', 'Python3'] | 1 |
longest-increasing-subsequence-ii | C++| Segment Tree | O(NlogN) | c-segment-tree-onlogn-by-kumarabhi98-m5x2 | For any nums[i], its last element in the increasing seq will range from nums[i]-k to nums[i]-1. Find the max length of elements in this Range.\n\nclass Solution | kumarabhi98 | NORMAL | 2022-09-11T06:16:59.533167+00:00 | 2022-09-11T06:16:59.533210+00:00 | 462 | false | For any `nums[i]`, its last element in the increasing seq will range from `nums[i]-k` to `nums[i]-1`. Find the max length of elements in this Range.\n```\nclass Solution {\npublic:\n const int n = 100001;\n int nums[4*100001] = {0};\n void update(int n,int id,int val,int l,int h){\n if(l<=h){\n if(l==h){\n if(id==l) nums[n] = max(nums[n],val);\n return;\n }\n else{\n int mid = (l+h)/2;\n if(id>=l && id<=mid) update(2*n+1,id,val,l,mid);\n else update(2*n+2,id,val,mid+1,h);\n nums[n] = max(nums[2*n+1],nums[2*n+2]);\n }\n }\n }\n int find(int i,int j,int n,int l,int h){\n if(l<=h){\n if(i<=l && j>=h) return nums[n];\n if((j<l || h<i) || l==h) return 0;\n int mid = (l+h)/2;\n int a = find(i,j,2*n+1,l,mid);\n int b = find(i,j,2*n+2,mid+1,h);\n return max(a,b);\n }\n else return 0;\n }\n int lengthOfLIS(vector<int>& arr, int k) {\n int re = 0;\n for(int i = 0; i<arr.size();++i){\n int x = max(1,arr[i]-k);\n int k = find(x,arr[i]-1,0,0,n);\n re = max(re,k+1);\n update(0,arr[i],k+1,0,n);\n }\n return re;\n }\n};\n``` | 3 | 0 | ['Tree', 'C'] | 0 |
longest-increasing-subsequence-ii | Segment Tree + 1D DP || C++ || Intutive Approach | segment-tree-1d-dp-c-intutive-approach-b-pc04 | USED IN THIS QUESTION\nSegment Tree -> To find the maximum value from the previous K numbers i.e. in range [a[i]-k,a[i]-1] . \nDP -> To store the LIS ending at | ayush_a1111 | NORMAL | 2022-09-11T04:10:35.325689+00:00 | 2022-09-11T04:46:23.390101+00:00 | 550 | false | **USED IN THIS QUESTION**\nSegment Tree -> To find the maximum value from the previous K numbers i.e. in range [a[i]-k,a[i]-1] . \nDP -> To store the LIS ending at that number ( dp[i] represents the LIS ending at that element ) \n\n```\nclass Solution {\n\n//CODE FOR SEGMENT TREE\n private:\n // BUILD FUNCTION (SEGMENT TREE)\nvoid build(int i,int l,int r,vector<int>& a,vector<int>& seg)\n{\n\tif(l==r)\n\t{\n\t\tseg[i]=a[l];\n\t\treturn ;\n\t}\n \n\tint m=(l+r)/2;\n \n\tbuild(2*i+1,l,m,a,seg);\n\tbuild(2*i+2,m+1,r,a,seg);\n \n\tseg[i]=max(seg[2*i+1],seg[2*i+2]);\n}\n // QUERY THE MAXIMUM ELEMENT IN RANGE [x,y] (SEGMENT TREE) \nint query(int i,int l,int r,vector<int>& a,int x,int y,vector<int>& seg)\n{\n\tif(l>=x && r<=y)\n\t{\n\t\treturn seg[i];\n\t}\n\tif(l>y || r<x)\n\t{\n\t\treturn INT_MIN;\n\t}\n \n\tint m=(l+r)/2;\n \n\tint c=query(2*i+1,l,m,a,x,y,seg);\n\tint d=query(2*i+2,m+1,r,a,x,y,seg);\n \n\treturn max(c,d);\n}\n \n // CHANGE THE VALUE OF a[j] to x (SEGMENT TREE)\nvoid update(int i,int l,int r,vector<int>& a,int j,int x,vector<int>& seg)\n{\n\tif(l==r)\n\t{\n\t\tseg[i]=x;\n\t\treturn;\n\t}\n \n\tint m=(l+r)/2;\n\tif(j<=m)\n\t{\n\t\tupdate(2*i+1,l,m,a,j,x,seg);\n\t}\n\telse\n\t{\n\t\tupdate(2*i+2,m+1,r,a,j,x,seg);\n\t}\n \n\tseg[i]=max(seg[2*i+1],seg[2*i+2]);\n}\npublic:\n \n int lengthOfLIS(vector<int>& a, int k) \n {\n int n=a.size();\n \n int m=100005;\n\t\t\n vector<int> dp(m,0); \n\t\t// dp [LIS ending at this index]\n \n vector<int> seg;\n seg.assign(4*m+1,0);\n \n build(0,0,m-1,dp,seg);\n \n for(int i=0;i<n;i++)\n {\n if(a[i]-k>=0)\n {\n\t\t\t // query( [a[i]-k , a[i]-1] )\n int t=query(0,0,m-1,dp,a[i]-k,a[i]-1,seg);\n dp[a[i]]=t+1; // changing dp[ a[i] ]=max element in range + 1\n\t\t\t\t// update( seg[a[i]] to dp[a[i]] )\n update(0,0,m-1,dp,a[i],dp[a[i]],seg);\n }\n else\n {\n\t\t\t // query( 0, a[i]-1] )\n int t=query(0,0,m-1,dp,0,a[i]-1,seg);\n dp[a[i]]=t+1; // changing dp[ a[i] ]=max element in range + 1\n\t\t\t\t// update( seg[a[i]] to dp[a[i]] )\n update(0,0,m-1,dp,a[i],dp[a[i]],seg);\n }\n }\n \n\t\t//FINDING THE MAXIMUM AMONG ALL THE ELEMENTS\n int ans=0;\n for(int i=0;i<m;i++)\n {\n ans=max(ans,dp[i]);\n }\n \n return ans;\n \n }\n};\n```\n\n**PLEASE UPVOTE IF UNDERSTOOD** | 3 | 1 | ['Dynamic Programming', 'Tree'] | 0 |
longest-increasing-subsequence-ii | Standard SegmentTree + DP || JAVA | standard-segmenttree-dp-java-by-priyank-idc5l | DP Defination\ndp[i] = length of LIS such that last element is i\nUsing this idea, if we are at arr[j], then previous element of this LIS ending at arr[j] can | priyank-doshi | NORMAL | 2022-09-11T04:08:28.826914+00:00 | 2022-09-11T04:11:43.088827+00:00 | 1,598 | false | **DP Defination**\ndp[i] = length of LIS such that last element is i\nUsing this idea, if we are at ```arr[j]```, then previous element of this LIS ending at ```arr[j]``` can be in the range of ```[arr[j] - k, arr[j] - 1]```. So we need to find max value of dp in the range of this.\nThis can be done faster using Segment tree.\n\n**Segment tree Operations:**\n1. point update\n2. range max\n\n**Key Idea:**\nUse values of ```arr[i]``` as the indexes in segment tree. Then when we want to find max of dp value in range ```[arr[j] - k, arr[j] - 1]```, we can treat them as indexes and query rangeMax.\n\nFinal ans is max of entire range i.e. ```segTree.max(1, 100000 + 1)```;\n\n```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n //int[] dp = new int[100000 + 5];\n SegmentTree st = new SegmentTree(100000 + 5);\n st.set(nums[0], 1);\n //dp[nums[0]] = 1;\n for(int i = 1; i < nums.length; i++) {\n int minN = Math.max(0, nums[i] - k); // 10 - 5 = 5\n st.set(nums[i], Math.max(st.get(nums[i], nums[i]), 1 + st.get(minN, nums[i])));\n st.set(nums[i], Math.max(st.get(nums[i], nums[i] + 1) , 1));\n }\n return (int)st.get(1, 100000 + 2);\n }\n}\n\n class SegmentTree {\n\n int size;\n long[] arr;\n\n int inputSize;\n\n private long neutralElement = Long.MIN_VALUE / 2;\n\n public SegmentTree(int n) {\n size = 1;\n inputSize = n;\n while (size < n) size *= 2;\n arr = new long[2 * size - 1];\n Arrays.fill(arr, neutralElement);\n }\n\n public void print() {\n //Arrays.stream(arr).forEachOrdered(x -> System.out.print(x + " "));\n }\n\n private void build(long[] input, int x, int lx, int rx) {\n if (rx - lx == 1) {\n if (lx < inputSize)\n arr[x] = input[lx];\n return;\n }\n int mid = (lx + rx) / 2;\n build(input, 2 * x + 1, lx, mid);\n build(input, 2 * x + 2, mid, rx);\n arr[x] = op(arr[2 * x + 1], arr[2 * x + 2]);\n }\n\n public void build(long[] arr) {\n build(arr, 0, 0, size);\n }\n\n private void set(int index, long val, int x, int lx, int rx) {\n if (rx - lx == 1) {\n arr[x] = val;\n return;\n }\n int mid = (lx + rx) / 2;\n if (index < mid) {\n set(index, val, 2 * x + 1, lx, mid);\n } else {\n set(index, val, 2 * x + 2, mid, rx);\n }\n arr[x] = op(arr[2 * x + 1], arr[2 * x + 2]);\n }\n\n public void set(int index, long val) {\n set(index, val, 0, 0, size);\n }\n\n public long get(int l, int r) { //inclusive l - exclusive r || [l, r)\n return get(l, r, 0, 0, size);\n }\n\n public long get(int l, int r, int x, int lx, int rx) {\n if (lx >= r || l >= rx)\n return neutralElement;\n if (lx >= l && rx <= r)\n return arr[x];\n int mid = (lx + rx) / 2;\n long max1 = get(l, r, 2 * x + 1, lx, mid);\n long max2 = get(l, r, 2 * x + 2, mid, rx);\n return op(max1, max2);\n }\n\n private long op(long a, long b) {\n return Math.max(a, b);\n }\n }\n ``` | 3 | 0 | ['Dynamic Programming', 'Tree', 'Java'] | 2 |
longest-increasing-subsequence-ii | [Python 3] Max Segment Tree | python-3-max-segment-tree-by-huangshan01-hqjk | Use a segment tree to track and query max length LIS. For leaf nodes in the 2nd half of the tree, tree index - len(nums) represents values appearing in nums. Fo | huangshan01 | NORMAL | 2022-09-11T04:07:33.421041+00:00 | 2022-09-11T13:31:38.259642+00:00 | 747 | false | Use a segment tree to track and query max length LIS. For leaf nodes in the 2nd half of the tree, `tree index - len(nums)` represents values appearing in nums. For a given val in nums, left query boundary = max(0, val - k), right query boundary = max(0, val - 1). val can be connected to all elements within the query range to form a 1-longer LIS.\n\n```\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n def update(i, x):\n i += n\n while i:\n tree[i] = max(tree[i], x)\n i //= 2\n \n def query(i, j):\n i += n\n j += n\n ans = -inf\n while i <= j:\n if i & 1:\n ans = max(ans, tree[i])\n i += 1\n if not j & 1:\n ans = max(ans, tree[j])\n j -= 1\n i //= 2\n j //= 2\n return ans\n \n ma = max(nums)\n n = ma + 1\n tree = [0] * (2 * n)\n ans = 0\n \n for i, v in enumerate(nums):\n # right query boundary\n rq = max(0, v - 1)\n # left query boundary\n lq = max(0, v - k)\n # query\n res = query(lq, rq) + 1\n # update LIS length for current value\n ans = max(ans, res)\n if res > tree[v + n]:\n update(v, res)\n\n return ans\n``` | 3 | 1 | ['Tree'] | 2 |
longest-increasing-subsequence-ii | [Javascript] Segment Tree | javascript-segment-tree-by-anna-hcj-qbzx | Solution: Segment Tree\n\nUse a segment tree to keep track of the longest subsequence ending with each number.\nFor each nums[i], take the maximum subsequence l | anna-hcj | NORMAL | 2022-09-11T04:00:37.494768+00:00 | 2022-09-11T04:00:37.494809+00:00 | 430 | false | **Solution: Segment Tree**\n\nUse a segment tree to keep track of the longest subsequence ending with each number.\nFor each `nums[i]`, take the maximum subsequence length ending within range `(nums[i] - k, nums[i] - 1)`.\n\n`n = length of nums`, `m = max(nums[i])`\nTime Complexity: `O(n log(m)) `\nSpace Complexity: `O(m)`\n```\nvar lengthOfLIS = function(nums, k) {\n let max = Math.max(...nums), segTree = new SegmentTree(max + 1), ans = 0;\n for (let num of nums) {\n let maxLength = segTree.maxInRange(Math.max(num - k, 0), num - 1);\n segTree.update(num, maxLength + 1);\n ans = Math.max(ans, maxLength + 1);\n }\n return ans;\n};\n\nclass SegmentTree {\n constructor(n) {\n this.size = n;\n this.segTree = Array(n * 2).fill(0);\n }\n update(index, val) {\n let n = this.size, idx = index + n;\n this.segTree[idx] = Math.max(this.segTree[idx], val);\n idx = Math.floor(idx / 2);\n\n while (idx > 0) {\n this.segTree[idx] = Math.max(this.segTree[idx * 2], this.segTree[idx * 2 + 1]);\n idx = Math.floor(idx / 2);\n }\n }\n maxInRange(left, right) {\n let n = this.size, max = 0;\n let left_idx = left + n, right_idx = right + n;\n // left must be even, right must be odd\n // when left is odd or right is even, this indicates partial coverage. \n // in other words, the parent node will be covering a range outside of the range we are looking for.\n // so, we need to take the partial sum and move the pointers so that it has full coverage.\n while (left_idx <= right_idx) {\n if (left_idx % 2 === 1) {\n max = Math.max(max, this.segTree[left_idx]);\n left_idx++;\n }\n if (right_idx % 2 === 0) {\n max = Math.max(max, this.segTree[right_idx]);\n right_idx--;\n }\n left_idx = Math.floor(left_idx / 2);\n right_idx = Math.floor(right_idx / 2);\n }\n return max;\n }\n}\n``` | 3 | 0 | ['Tree', 'JavaScript'] | 2 |
longest-increasing-subsequence-ii | C++ | Segment Tree Solution | c-segment-tree-solution-by-avadhut7969-hh9k | \n\n# Complexity\n- Time complexity:\nO(nlog(n))\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution {\npublic:\n vector<int>tree;\n void update(int | avadhut7969 | NORMAL | 2024-05-24T04:48:15.749179+00:00 | 2024-05-24T04:48:15.749211+00:00 | 558 | false | \n\n# Complexity\n- Time complexity:\nO(nlog(n))\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int>tree;\n void update(int node,int st,int end,int i,int val){\n if(st==end){\n tree[node]=max(tree[node],val);\n return;\n }\n int mid=(st+end)/2;\n if(i<=mid){\n update(node*2,st,mid,i,val);\n }else{\n update(node*2+1,mid+1,end,i,val);\n }\n tree[node]=max(tree[node*2],tree[node*2+1]);\n }\n int query(int node,int st,int end,int x,int y){\n if(x>end || y<st) return -1e9;\n if(st>=x && end<=y){\n return tree[node];\n }\n int mid=(st+end)/2;\n int left=query(2*node,st,mid,x,y);\n int right=query(2*node+1,mid+1,end,x,y);\n return max(left,right);\n }\n int lengthOfLIS(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1) return 1;\n int m=*max_element(nums.begin(),nums.end());\n tree.clear();\n tree.resize(4*m+10);\n for(int i=n-1;i>=0;i--){\n int l=nums[i]+1,r=min(nums[i]+k,m);\n int x=query(1,0,m,l,r);\n if(x==-1e9) x=0;\n update(1,0,m,nums[i],x+1);\n }\n return tree[1];\n }\n};\n``` | 2 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | Java modified LIS | Intuitive but TLE | java-modified-lis-intuitive-but-tle-by-s-stsu | Approach:\n- Posting just for intuition, LC doesn\'t accept this solution as it\'s getting TLE\n\n\nclass Solution {\n public int lengthOfLIS(int[] nums, int | sbd5_941 | NORMAL | 2024-02-08T15:10:18.703806+00:00 | 2024-02-08T15:10:18.703871+00:00 | 302 | false | # Approach:\n- Posting just for intuition, LC doesn\'t accept this solution as it\'s getting TLE\n\n```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n int n = nums.length;\n int[] dp = new int[n];\n Arrays.fill(dp, 1);\n \n int max = 1;\n for(int i = n-1; i >= 0; i--) {\n for(int j = i+1; j < n; j++) {\n if(nums[i] + k < nums[j] || nums[i] >= nums[j])\n continue;\n dp[i] = Math.max(dp[i], 1+dp[j]); \n max = Math.max(max, dp[i]);\n }\n }\n return max;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
longest-increasing-subsequence-ii | Beats 81% || Segment Tree || DP || C++ | beats-81-segment-tree-dp-c-by-krishiiitp-zlmc | Code\n\n#define ll int\nclass Solution {\npublic:\n void build(vector<ll>& seg,vector<ll>& a,ll low,ll high,ll ind){\n if(low==high){\n seg | krishiiitp | NORMAL | 2024-01-24T14:07:50.251902+00:00 | 2024-01-24T14:07:50.251936+00:00 | 1,001 | false | # Code\n```\n#define ll int\nclass Solution {\npublic:\n void build(vector<ll>& seg,vector<ll>& a,ll low,ll high,ll ind){\n if(low==high){\n seg[ind]=a[low];\n return;\n } \n ll mid=(low + high)/2;\n build(seg,a,low,mid,2*ind + 1);\n build(seg,a,mid+1,high,2*ind + 2);\n seg[ind]=max(seg[2*ind + 1],seg[2*ind + 2]);\n }\n ll query(vector<ll>& seg,ll low,ll high,ll x,ll y,ll ind){\n if(x>high || y<low){\n return INT_MIN;\n }\n if(low>=x && high<=y){\n return seg[ind];\n }\n ll mid=(low + high)/2;\n ll left=query(seg,low,mid,x,y,2*ind + 1);\n ll right=query(seg,mid+1,high,x,y,2*ind + 2);\n return max(left,right);\n }\n void update(vector<ll>& seg,ll low,ll high,ll i,ll val,ll ind){\n if(low==high){\n seg[ind]=max(seg[ind],val);\n return;\n }\n int mid=(low+high)/2;\n if(i<=mid){\n update(seg,low,mid,i,val,2*ind + 1);\n }else{\n update(seg,mid+1,high,i,val,2*ind+2);\n }\n seg[ind]=max(seg[2*ind + 1],seg[2*ind + 2]);\n }\n int lengthOfLIS(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1){\n return 1;\n }\n int mx=0,ans=0;\n for(int i=0;i<n;i++){\n mx=max(mx,nums[i]);\n }\n int sz=mx+1;\n vector<int> a(sz,0);\n vector<ll> seg(4*mx + 10);\n build(seg,a,0,mx,0);\n update(seg,0,sz-1,nums[n-1],1,0);\n for(int i=n-2;i>=0;i--){\n if(nums[i]==mx){\n update(seg,0,sz-1,nums[i],1,0);\n continue;\n }\n int l=nums[i]+1,r=min(mx,nums[i]+k);\n int some=query(seg,0,sz-1,l,r,0);\n if(some==INT_MIN){\n some=0;\n }\n update(seg,0,sz-1,nums[i],some+1,0);\n }\n ans=query(seg,0,sz-1,1,mx,0);\n //ans--;\n return ans;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | C++ solution using segment tree | c-solution-using-segment-tree-by-ankit_6-f5yx | \n// // Template reference: https://github.com/ankit6776/CPP_LIBRARIES/blob/master/src/segTree.hpp\ntemplate<typename T> inline T Max(T a, T b){return a>b?a:b;} | ankit_6776 | NORMAL | 2022-10-10T07:15:48.383122+00:00 | 2022-10-10T07:15:48.383160+00:00 | 468 | false | ```\n// // Template reference: https://github.com/ankit6776/CPP_LIBRARIES/blob/master/src/segTree.hpp\ntemplate<typename T> inline T Max(T a, T b){return a>b?a:b;}\ntemplate<typename T> inline T Min(T a, T b){return a<b?a:b;}\ntemplate<typename T> inline T __Gcd(T a, T b){ return b==0 ? a : __Gcd(b,a%b);}\ntemplate<typename T> struct SegTree {\n long long int N;\n vector<T> v;\n vector<T> seg;\n vector<T> lazy;\n void init(int st, int end, int ind){\n if(st==end){\n seg[ind]=v[st];\n return;\n }\n int mid = (st+end)/2;\n init(st,mid,2*ind+1);\n init(mid+1,end, 2*ind+2);\n seg[ind]=f(seg[2*ind+1],seg[2*ind+2]);\n }\n T f(T a, T b){\n return max(a, b); \n \n }\n void pre() {\n seg.resize(4*N);\n lazy.resize(4*N);\n init(0,N-1,0);\n }\n \n void point_update(int p, T x) {\n point_update_query(0,0,N-1,p,x);\n }\n \n T update_function(T x, T y){\n return f(x,y);\n }\n \n void point_update_query(int node, int st, int en, int ind, T x) {\n if(ind<st||ind>en)return;\n if(st==en) {\n seg[node] = update_function(seg[node], x);\n return;\n }\n int mid = (st+en)/2;\n ind<=mid ? point_update_query(2*node+1, st, mid, ind, x) : point_update_query(2*node+2, mid+1, en, ind, x);\n seg[node]=f(seg[2*node+1],seg[2*node+2]);\n }\n \n void update_range_query(int l, int r, T x) {\n update_range(0, 0, N-1, l, r, x);\n }\n\n void update_range(int node, int st, int en, int l, int r, T x) {\n if(st>en || st>r || l>en)return;\n if(st == en) {\n seg[node] = f(seg[node], x);\n return;\n }\n \n int mid = (st+en)/2;\n if(st>=l&&en<=r) {\n if(seg[node]<=x) { // lazy return condition\n seg[node]=x;\n lazy[node]=x;\n return;\n }\n if(lazy[node]>=x) {\n return;\n }\n seg[2*node+1]=f(seg[2*node+1], lazy[node]);\n seg[2*node+2]=f(seg[2*node+2], lazy[node]);\n lazy[2*node+1]=f(lazy[node], lazy[2*node+1]);\n lazy[2*node+2]=f(lazy[node], lazy[2*node+2]);\n update_range(2*node+1, st, mid, l,r,x);\n update_range(2*node+2, mid+1, en, l, r,x);\n seg[node]=f(seg[2*node+1], seg[2*node+2]);\n return;\n }\n seg[2*node+1]=f(seg[2*node+1], lazy[node]);\n seg[2*node+2]=f(seg[2*node+2], lazy[node]);\n lazy[2*node+1]=f(lazy[node], lazy[2*node+1]);\n lazy[2*node+2]=f(lazy[node], lazy[2*node+2]);\n update_range(2*node+1, st, mid, l, r, x);\n update_range(2*node+2, mid+1, en, l, r, x);\n seg[node]=f(seg[2*node+1], seg[2*node+2]);\n }\n \n T query(int l,int r){\n return _query(0,l,r,0,N-1);\n }\n \n T _query(int node, int l,int r, int st,int en){\n if(l>en||r<st)return 0; // replace INF with zero for sum query\n if(st>=l&&en<=r)return seg[node];\n int mid = (st+en)/2;\n return f(_query(2*node+1,l,r,st,mid),_query(2*node+2,l,r,mid+1,en));\n }\n\n T lazy_query(T x) {\n return _range_query(0,x, 0, N-1);\n }\n\n T _range_query(int node, T x, int st, int en) {\n if(st==en && st==x) return seg[node];\n int mid = (st+en)/2;\n seg[2*node+1]=f(seg[2*node+1], lazy[node]);\n seg[2*node+2]=f(seg[2*node+2], lazy[node]);\n lazy[2*node+1]=f(lazy[node], lazy[2*node+1]);\n lazy[2*node+2]=f(lazy[node], lazy[2*node+2]);\n if(mid>=x)return _range_query(2*node+1, x, st, mid);\n else return _range_query(2*node+2, x, mid+1, en);\n }\n \n //TODO(ankit6776): Add query implementation for range query in lazy propagation.\n \n};\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n SegTree<int> seg;\n int n = 100002;\n vector<int> v(n);\n seg.N = n;\n seg.v = v;\n seg.pre();\n int ans = 0;\n for(int i=0;i<nums.size();++i){\n int pp = seg.query(nums[i], nums[i]);\n int qq = seg.query(nums[i]-k, nums[i]-1);\n ans = max(ans, pp);\n if(pp>=qq+1){\n continue;\n }\n seg.point_update(nums[i], qq+1);\n ans = max(ans, qq+1);\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
longest-increasing-subsequence-ii | Python, runtime O(n logn), memory O(n) | python-runtime-on-logn-memory-on-by-tsai-qtm6 | \n\nclass Solution:\n def getmax(self, st, start, end):\n maxi = 0\n \n while start < end:\n if start%2:#odd\n | tsai00150 | NORMAL | 2022-09-18T05:57:37.899557+00:00 | 2022-09-18T05:57:45.524175+00:00 | 640 | false | \n```\nclass Solution:\n def getmax(self, st, start, end):\n maxi = 0\n \n while start < end:\n if start%2:#odd\n maxi = max(maxi, st[start])\n start += 1\n if end%2:#odd\n end -= 1\n maxi = max(maxi, st[end])\n start //= 2\n end //= 2\n return maxi\n \n def update(self, st, maxi, n):\n st[n] = maxi\n while n > 1:\n n //= 2\n st[n] = max(st[2*n], st[2*n+1])\n \n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n ans = 1\n length = max(nums)\n st = [0]*length*2\n for n in nums:\n n -= 1\n maxi = self.getmax(st, max(0, n-k)+length, n+length) + 1\n self.update(st, maxi, n+length)\n ans = max(maxi, ans)\n return ans\n \n\n```\nReference:\nhttps://www.youtube.com/watch?v=xztU7lmDLv8&ab_channel=StableSort\nhttps://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2560085/Python-Explanation-with-pictures-Segment-Tree | 2 | 0 | ['Tree', 'Python', 'Python3'] | 0 |
longest-increasing-subsequence-ii | Segment Tree || C++ | segment-tree-c-by-vvd4-6317 | \n\nvoid update(vector<int> &seg,int si,int sl,int sr,int i,int val){\n if(sl==sr){\n seg[si]=max(seg[si],val);\n return;\n }\n int mid=( | vvd4 | NORMAL | 2022-09-17T08:21:20.110582+00:00 | 2022-09-17T08:21:20.110619+00:00 | 388 | false | ```\n\nvoid update(vector<int> &seg,int si,int sl,int sr,int i,int val){\n if(sl==sr){\n seg[si]=max(seg[si],val);\n return;\n }\n int mid=(sl+sr)/2;\n if(i<=mid)update(seg,si*2,sl,mid,i,val);\n else update(seg,si*2+1,mid+1,sr,i,val);\n seg[si]=max(seg[si*2],seg[si*2+1]);\n}\n\nint Q(vector<int> &seg,int si,int sl,int sr,int l,int r){\n if(l>r)return 0;\n if(sl==l and sr==r)return seg[si];\n int mid=(sl+sr)/2;\n return max(\n Q(seg,si*2,sl,mid,l,min(r,mid)),\n Q(seg,si*2+1,mid+1,sr,max(mid+1,l),r)\n );\n}\n\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n vector<int> seg(400005);\n int ans=0;\n for(int i=0;i<nums.size();i++){\n int maxi=Q(seg,1,1,100000,max(1,nums[i]-k),nums[i]-1);\n ans=max(ans,maxi+1);\n update(seg,1,1,100000,nums[i],maxi+1);\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
longest-increasing-subsequence-ii | [JAVA] DP + Segment Tree, Time: NLogN, Space: (max - min), Commented | java-dp-segment-tree-time-nlogn-space-ma-id8d | Use the segment tree to store DP results and query them\n\n\nclass Solution {\n\tpublic int lengthOfLIS(int[] nums, int k) {\n\t\t// find the boundaries of the | yurokusa | NORMAL | 2022-09-13T14:11:21.429798+00:00 | 2022-09-16T17:21:35.313710+00:00 | 661 | false | Use the segment tree to store DP results and query them\n\n```\nclass Solution {\n\tpublic int lengthOfLIS(int[] nums, int k) {\n\t\t// find the boundaries of the segment tree\n\t\tvar minVal = Integer.MAX_VALUE;\n\t\tvar maxVal = Integer.MIN_VALUE;\n\t\tfor (int n : nums) {\n\t\t\tminVal = Math.min(minVal, n);\n\t\t\tmaxVal = Math.max(maxVal, n);\n\t\t}\n\n\t\t// build the segment tree\n\t\tvar dp = new SegmentTree(minVal, maxVal);\n\t\tfor (int num : nums) {\n\t\t\t// find longest chain in range\n\t\t\tvar preMax = 1 + dp.rangeMaxQuery(num - k, num - 1);\n\t\t\t// store the results\n\t\t\tdp.update(num, preMax);\n\t\t}\n\t\treturn dp.val;\n\t}\n\n\tstatic final class SegmentTree {\n\t\tSegmentTree left;\n\t\tSegmentTree right;\n\t\tfinal int lo;\n\t\tfinal int hi;\n\t\tint val;\n\n\t\tSegmentTree(int lo, int hi) {\n\t\t\tthis.lo = lo;\n\t\t\tthis.hi = hi;\n\t\t\tif (lo != hi) {\n\t\t\t\tvar mid = lo + (hi - lo) / 2;\n\t\t\t\tthis.left = new SegmentTree(lo, mid);\n\t\t\t\tthis.right = new SegmentTree(mid + 1, hi);\n\t\t\t}\n\t\t}\n\n\t\tvoid update(int index, int val) {\n\t\t\tif (index < this.lo || this.hi < index) // out of range\n\t\t\t\treturn;\n\t\t\tif (lo == hi) { // found node\n\t\t\t\tthis.val = val;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.left.update(index, val);\n\t\t\tthis.right.update(index, val);\n\t\t\tthis.val = Math.max(this.left.val, this.right.val);\n\t\t}\n\n\t\tint rangeMaxQuery(int lo, int hi) {\n\t\t\tif (hi < this.lo || this.hi < lo) // not overlap\n\t\t\t\treturn 0;\n\t\t\tif (lo <= this.lo && this.hi <= hi) // in range\n\t\t\t\treturn this.val;\n\t\t\treturn Math.max(this.left.rangeMaxQuery(lo, hi), this.right.rangeMaxQuery(lo, hi));\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn "[" + lo + "," + hi + "]->" + val;\n\t\t}\n\t}\n}\n``` | 2 | 0 | ['Tree', 'Java'] | 1 |
longest-increasing-subsequence-ii | C# Solution | Time: O(n*log(n)), Memory: O(n) | Segment tree, Max range query | c-solution-time-onlogn-memory-on-segment-mayp | C#\npublic class Solution {\n public int LengthOfLIS(int[] nums, int k) {\n var max = nums.Max();\n var segmentTree = new SegmentTree(max + 1, | tonytroeff | NORMAL | 2022-09-12T20:50:27.163633+00:00 | 2022-09-12T20:50:27.163674+00:00 | 298 | false | ```C#\npublic class Solution {\n public int LengthOfLIS(int[] nums, int k) {\n var max = nums.Max();\n var segmentTree = new SegmentTree(max + 1, new MaxSegmentTreeNodeMerger());\n \n for (int i = 0; i < nums.Length; i++) {\n int left = Math.Max(0, nums[i] - k), right = nums[i] - 1;\n var queryResult = segmentTree.QueryRange(left, right);\n \n segmentTree.Update(nums[i], queryResult + 1);\n }\n \n return segmentTree.QueryRange(0, max);\n }\n}\n\npublic class SegmentTree\n{\n private readonly int _originalLength;\n private readonly int[] _items;\n private readonly ISegmentTreeNodeMerger _merger;\n\n public SegmentTree(int[] nums, ISegmentTreeNodeMerger merger) \n : this(nums?.Length ?? throw new ArgumentNullException(nameof(nums)), merger)\n {\n for (var i = 0; i < this._originalLength; i++) this._items[i + this._originalLength] = nums[i];\n for (var i = this._originalLength - 1; i > 0; i--) this._items[i] = this._merger.Merge(this._items[i * 2], this._items[i * 2 + 1]);\n }\n \n public SegmentTree(int length, ISegmentTreeNodeMerger merger)\n {\n this._originalLength = length;\n this._items = new int[this._originalLength * 2];\n this._merger = merger ?? throw new ArgumentNullException(nameof(merger));\n }\n\n public void Update(int index, int value)\n {\n index += this._originalLength;\n this._items[index] = value;\n\n while (index > 1)\n {\n int left = index, right = index;\n if (index % 2 == 0) right += 1;\n else left -= 1;\n\n this._items[index / 2] = this._merger.Merge(this._items[left], this._items[right]);\n index /= 2;\n }\n }\n\n public int QueryRange(int left, int right)\n {\n left += this._originalLength;\n right += this._originalLength;\n\n var res = this._merger.InitialQueryValue;\n while (left <= right)\n {\n // If `left` is right child, then the parent contains sum of range of `left` and another child which is outside the sum range and we don\'t need the parent sum. Add `left` to sum without its parent and set `left` to point to the right of its parent on the upper level.\n if (left % 2 != 0)\n {\n res = this._merger.Merge(res, this._items[left]);\n left += 1;\n }\n\n // If `right` is left child, then the parent contains sum of range of `right` and another child which is outside the sum range and we don\'t need the parent sum. Add `right` to sum without its parent and set `right` to point to the left of its parent on the upper level.\n if (right % 2 == 0)\n {\n res = this._merger.Merge(res, this._items[right]);\n right -= 1;\n }\n\n left /= 2;\n right /= 2;\n }\n\n return res;\n }\n}\n\npublic interface ISegmentTreeNodeMerger\n{\n int Merge(int leftValue, int rightValue);\n int InitialQueryValue { get; }\n}\n\npublic class MaxSegmentTreeNodeMerger : ISegmentTreeNodeMerger\n{\n public int Merge(int leftValue, int rightValue) => Math.Max(leftValue, rightValue);\n\n public int InitialQueryValue => int.MinValue;\n}\n``` | 2 | 0 | ['Tree'] | 0 |
longest-increasing-subsequence-ii | Simple Java Solution using TreeSet | simple-java-solution-using-treeset-by-pi-fmle | \nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n ArrayList<TreeSet> arr=new ArrayList<>();\n arr.add(new TreeSet());\n | piyushkumar2000 | NORMAL | 2022-09-11T06:35:47.265900+00:00 | 2022-09-11T06:35:47.265946+00:00 | 846 | false | ```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n ArrayList<TreeSet> arr=new ArrayList<>();\n arr.add(new TreeSet());\n for(int i=0;i<nums.length;i++){\n int val=nums[i];\n int n=arr.size();\n if(arr.get(0).lower(val)==null ){\n arr.get(0).add(val);\n }\n else if(arr.get(n-1).lower(val)!=null && (val-(int)arr.get(n-1).lower(val))<=k){\n arr.add(new TreeSet());\n arr.get(n).add(val);\n }\n else{\n int idx=binSearch(arr,val,k);\n arr.get(idx).add(val);\n }\n }\n return arr.size();\n }\n public int binSearch(ArrayList<TreeSet> arr,int val,int k){\n int i=0;\n int j=arr.size()-1;\n int idx=-1;\n while(i<=j){\n int mid=i+(j-i)/2;\n if(arr.get(mid).lower(val)!=null && (val-(int)arr.get(mid).lower(val))<=k){\n idx=mid;\n i=mid+1;\n }\n else if(arr.get(mid).lower(val)!=null && (val-(int)arr.get(mid).lower(val))>k){\n i=mid+1;\n }\n else{\n j=mid-1;\n }\n }\n return idx+1;\n }\n}\n``` | 2 | 0 | ['Tree', 'Binary Tree', 'Ordered Set', 'Java'] | 2 |
longest-increasing-subsequence-ii | zkw segment tree | zkw-segment-tree-by-yachiyo-l3xp | \ndef lengthOfLIS(self, nums: List[int], k: int) -> int:\n N = 1+max(nums)\n tree = [0] * (2*N+1)\n def update(x, l):\n i = x+N\ | yachiyo | NORMAL | 2022-09-11T04:13:29.379301+00:00 | 2022-09-11T04:13:29.379337+00:00 | 297 | false | ```\ndef lengthOfLIS(self, nums: List[int], k: int) -> int:\n N = 1+max(nums)\n tree = [0] * (2*N+1)\n def update(x, l):\n i = x+N\n while i:\n tree[i] = max(tree[i],l)\n i>>=1\n def query(l,r):\n ans =0 \n l += N-1\n r += N+1\n while l^r^1:\n if ~l & 1: ans= max(ans, tree[l^1])\n if r & 1 : ans = max(ans, tree[r^1])\n l>>=1\n r>>=1\n return ans\n for x in nums:\n l = query(max(1,x-k), x-1)\n update(x, l+1)\n return max(tree)\n``` | 2 | 0 | ['Tree', 'Python'] | 0 |
longest-increasing-subsequence-ii | Memoization-Tabulation-Space Optimization Explained || DP | memoization-tabulation-space-optimizatio-q0yv | 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 | blackhorse_ | NORMAL | 2024-06-18T18:19:39.073060+00:00 | 2024-06-18T18:19:39.073105+00:00 | 173 | false | # 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```Memoization []\nclass Solution {\npublic:\n int f(vector<int> &nums, int idx, int last, vector<vector<int>> &dp, int k){\n int n = nums.size();\n if(dp[idx][last] != -1) return dp[idx][last];\n if(idx>=n+1){\n return dp[idx][last] = 0;\n }\n int cnt = 0;\n if(last >= 1 && nums[idx-1] > nums[last-1] && nums[idx-1] - nums[last-1] <= k){\n cnt = max(1 + f(nums, idx + 1, idx, dp, k), f(nums, idx + 1, last, dp, k));\n }\n else if(last >= 1 && (nums[idx-1] - nums[last-1] > k || nums[idx-1] <= nums[last-1])){\n cnt = f(nums, idx + 1, last, dp, k);\n }\n else if(last == 0){\n cnt = max(1 + f(nums, idx + 1, idx, dp, k), f(nums, idx + 1, last, dp, k));\n }\n return dp[idx][last] = cnt;\n }\n int lengthOfLIS(vector<int>& nums, int k) {\n vector<vector<int>> dp(nums.size() + 2, vector<int> (nums.size() + 2, -1));\n return f(nums, 1, 0, dp, k);\n }\n};\n```\n```Tabulation []\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<int>> dp(n + 2, vector<int> (n + 2, 0));\n for(int idx = n; idx >= 0; idx--){\n for(int last = n; last >= 0; last--){\n if(idx > 0 && last > 0 && nums[idx-1] > nums[last-1] && nums[idx-1] - nums[last-1] <= k){\n dp[idx][last] = max(1 + dp[idx+1][idx], dp[idx+1][last]);\n }\n else if(last > 0 && idx > 0 && (nums[idx-1] - nums[last-1] > k || nums[idx-1] <= nums[last-1])){\n dp[idx][last] = dp[idx+1][last];\n }\n else if(last == 0){\n dp[idx][last] = max(1 + dp[idx+1][idx], dp[idx+1][last]);\n }\n }\n }\n return dp[1][0];\n }\n};\n```\n```Space-Optimization []\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> cur(n + 2, 0), next(n + 2, 0);\n \n for(int idx = n; idx >= 0; idx--){\n for(int last = n; last >= 0; last--){\n if(idx > 0 && last > 0 && nums[idx-1] > nums[last-1] && nums[idx-1] - nums[last-1] <= k){\n cur[last] = max(1 + next[idx], next[last]);\n }\n else if(last > 0 && idx > 0 && (nums[idx-1] - nums[last-1] > k || nums[idx-1] <= nums[last-1])){\n cur[last] = next[last];\n }\n else if(last == 0){\n cur[last] = max(1 + next[idx], next[last]);\n }\n }\n swap(cur, next); // Move to the next row\n }\n \n return next[0]-1;\n }\n};\n\n```\n```SegmentTree []\nclass Solution {\npublic:\n int n;\n vector<int> segtree;\n \n int BestRange(int start, int end) {\n int res = 0;\n start += 1e5 - 1;\n end += 1e5 - 1;\n \n while (start < end) {\n res = max({segtree[start], segtree[end], res});\n if (start % 2 == 0) start++;\n if (end % 2 == 1) end--;\n start = (start - 1) / 2;\n end = (end - 1) / 2;\n }\n \n if (start == end) res = max(segtree[start], res);\n \n return res;\n }\n \n void Update(int idx, int newlen) {\n idx += 1e5 - 1;\n while (idx >= 0) {\n segtree[idx] = max(newlen, segtree[idx]);\n if (idx == 0) idx = -1;\n else idx = (idx - 1) / 2;\n }\n return;\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int ans = 0;\n n = nums.size();\n segtree.resize(2e5);\n \n for (int i = 0; i < n; i++) nums[i]--;\n \n for (int i : nums) {\n int longest = 1;\n if (i > 0) longest = BestRange(max(i - k, 0), i - 1) + 1;\n ans = max(longest, ans);\n Update(i, longest);\n }\n \n return ans;\n }\n};\n```\n | 1 | 0 | ['Dynamic Programming', 'Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | Stretch that Sequence: Long and Increasing! | stretch-that-sequence-long-and-increasin-7kkx | Intuition\nMy first thought was to use dynamic programming to solve this problem. Given that we need to find the longest strictly increasing subsequence where t | pavan_riser | NORMAL | 2024-06-10T16:56:59.566203+00:00 | 2024-06-10T16:56:59.566239+00:00 | 220 | false | # Intuition\nMy first thought was to use dynamic programming to solve this problem. Given that we need to find the longest strictly increasing subsequence where the difference between adjacent elements is at most k, the challenge is to efficiently find and update the lengths of such subsequences.\n\n# Approach\n**Dynamic Programming Array:** Use a dp array where dp[i] represents the length of the longest subsequence ending at index i in the nums array.\n\n**Segment Tree:** To efficiently get the maximum length of subsequences ending with values within a certain range, utilize a segment tree. \nThis data structure allows us to perform range maximum queries and point updates in logarithmic time.\n\nU**pdating the DP Array and Segment Tree:** For each element in nums:\n- Query the segment tree to find the maximum length of subsequences that end with values in the range [nums[i] - k, nums[i] - 1].\n- Update dp[i] to this maximum length plus one (since nums[i] can be added to extend these subsequences).\n- Update the segment tree with the new value of dp[i].\n\n# Complexity\n- Time complexity:\nO(nlogn) due to the logarithmic time complexity for updates and queries in the segment tree, and linear time complexity for iterating through the array.\n\n- Space complexity:\nO(n) for the segment tree and the dp array.\n\n# Code\n```\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nclass SegmentTree {\nprivate:\n vector<int> tree;\n int n;\n\npublic:\n SegmentTree(int size) : n(size) {\n tree.resize(4 * n, 0);\n }\n\n void update(int index, int value, int node, int nodeLeft, int nodeRight) {\n if (nodeLeft == nodeRight) {\n tree[node] = value;\n } else {\n int mid = (nodeLeft + nodeRight) / 2;\n if (index <= mid) {\n update(index, value, 2 * node + 1, nodeLeft, mid);\n } else {\n update(index, value, 2 * node + 2, mid + 1, nodeRight);\n }\n tree[node] = max(tree[2 * node + 1], tree[2 * node + 2]);\n }\n }\n\n void update(int index, int value) {\n update(index, value, 0, 0, n - 1);\n }\n\n int query(int left, int right, int node, int nodeLeft, int nodeRight) {\n if (left > nodeRight || right < nodeLeft) {\n return 0;\n }\n if (left <= nodeLeft && right >= nodeRight) {\n return tree[node];\n }\n int mid = (nodeLeft + nodeRight) / 2;\n return max(query(left, right, 2 * node + 1, nodeLeft, mid),\n query(left, right, 2 * node + 2, mid + 1, nodeRight));\n }\n\n int query(int left, int right) {\n if (left > right) return 0;\n return query(left, right, 0, 0, n - 1);\n }\n};\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> dp(n, 0);\n int maxVal = *max_element(nums.begin(), nums.end());\n SegmentTree segTree(maxVal + 1);\n\n for (int i = 0; i < n; ++i) {\n int maxLength = segTree.query(max(0, nums[i] - k), nums[i] - 1);\n dp[i] = maxLength + 1;\n segTree.update(nums[i], dp[i]);\n }\n\n return *max_element(dp.begin(), dp.end());\n }\n};\n\n``` | 1 | 0 | ['Dynamic Programming', 'Segment Tree', 'C++'] | 1 |
longest-increasing-subsequence-ii | C++ concise solution with helpful video | c-concise-solution-with-helpful-video-by-aiic | Video not made by me. Still a very difficult algorithm to understand even with such a helpful video.\nhttps://www.youtube.com/watch?v=xztU7lmDLv8\n\nclass Solut | user5976fh | NORMAL | 2024-04-19T20:11:19.027351+00:00 | 2024-04-19T20:16:25.070886+00:00 | 4 | false | Video not made by me. Still a very difficult algorithm to understand even with such a helpful video.\nhttps://www.youtube.com/watch?v=xztU7lmDLv8\n```\nclass Solution {\npublic:\n int s = 100001;\n int a[200002] = {};\n int findMax(int l, int r){\n int m = 0;\n l += s, r += s;\n while (l < r){\n if (l % 2) m = max(m, a[l++]);\n if (r % 2) m = max(m, a[--r]);\n l /= 2, r /= 2;\n }\n return m;\n }\n \n void insert(int i, int v){\n for (i = i + s; i > 0; a[i] = max(a[i], v), i /= 2);\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int ans = 0;\n for (auto& n : nums){\n int m = findMax(max(1, n - k), n);\n insert(n, ++m);\n ans = max(ans, m);\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
longest-increasing-subsequence-ii | Node Based Recursive Implementation Segment Tree Example Run | node-based-recursive-implementation-segm-5mpf | Intuition\nInspired by shiv-code\'s solution and explanation. Replaced the Iterative Segment Tree with Node based recursive segment tree which is inspired by ne | rajsinghsudhanshu930 | NORMAL | 2024-01-15T08:12:22.907545+00:00 | 2024-01-15T08:15:32.198702+00:00 | 22 | false | # Intuition\nInspired by shiv-code\'s solution and explanation. Replaced the Iterative Segment Tree with Node based recursive segment tree which is inspired by neetcode.\n \n# Approach\nWe store the longest increasing sequence ending at every number in nums in a segment tree.\n\nThe array which this segment tree represents will reprent values from 0 to max(nums). For example array[5] represents what is the longest subsequence that ends at element 5 in the array. As we traverse the nums, it will keep getting updated. If you see another 5, you update this value.\n\nFor a particular element num, we only want to find longest subsequence in range (nums-k) to (nums-1) since we already know for the values lower than nums-k so far in the array as we are traversing from left to right. Important to keep in mind that this is a subsequence.\n\nWe add 1 to the result as num will become part of this subsequence and update the segment tree entry for num with this value.\n\n**Example**\n\nnums = [4,2,1,4,3,4,5,8,15], k=3\n\ni=0, num=4\nmm=tree.rangeQuery(max(0, 4 - 3), 4-1)=tree.rangeQuery(1, 3)=0\nupdate tree to store mm+1=1 at position 4\nres=1\n\ni=1, num=2\nmm=tree.rangeQuery(max(0, 2 - 3), 2-1)=tree.rangeQuery(0, 1)=0\nupdate tree to store mm+1=1 at position 2\nres=1\n\ni=2, num=1\nmm=tree.rangeQuery(max(0, 1 - 3), 1-1)=tree.rangeQuery(0, 0)=0\nupdate tree to store mm+1=1 at position 1\nres=1\n\ni=3, num=4\nmm=tree.rangeQuery(max(0, 4 - 3), 4-1)=tree.rangeQuery(1, 3)=1\nupdate tree to store mm+1=2 at position 4\nres=2\n\ni=4, num=3\nmm=tree.rangeQuery(max(0, 3 - 3), 3-1)=tree.rangeQuery(0, 2)=1\nupdate tree to store mm+1=2 at position 3\nres=2\n\ni=5, num=4\nmm=tree.rangeQuery(max(0, 4 - 3), 4-1)=tree.rangeQuery(1, 3)=2\nupdate tree to store mm+1=3 at position 4\nres=3\n\ni=6, num=5\nmm=tree.rangeQuery(max(0, 5 - 3), 5-1)=tree.rangeQuery(2, 4)=3\nupdate tree to store mm+1=4 at position 5\nres=4\n\ni=7, num=8\nmm=tree.rangeQuery(max(0, 8 - 3), 8-1)=tree.rangeQuery(5, 7)=4\nupdate tree to store mm+1=5 at position 8\nres=5\n\ni=5, num=15\nmm=tree.rangeQuery(max(0, 15 - 3), 15-1)=tree.rangeQuery(12, 14)=0\nupdate tree to store mm+1=1 at position 15\nres=5\n\n\n\n# Complexity\n- Time complexity:\nO(nlog(max(nums)))\n- Space complexity:\nO(max(nums))\n# Code\n```\nclass SegmentTree:\n def __init__(self,L,R):\n self.longest=0\n self.L=L\n self.R=R\n if L==R:\n self.left=None\n self.right=None\n else:\n M=(L+R)//2\n self.left=SegmentTree(L,M)\n self.right=SegmentTree(M+1,R)\n \n def update(self,index,val):\n if self.L==self.R:\n self.longest=val\n return\n M=(self.L+self.R)//2\n\n if index>M:\n self.right.update(index,val)\n else:\n self.left.update(index,val)\n \n self.longest=max(self.left.longest,self.right.longest)\n \n def rangeQuery(self,L,R):\n if L==self.L and R==self.R:\n return self.longest\n \n M=(self.L+self.R)//2\n if L>M:\n return self.right.rangeQuery(L,R)\n elif R<=M:\n return self.left.rangeQuery(L,R)\n else:\n return max(self.left.rangeQuery(L,M),self.right.rangeQuery(M+1,R))\n\nclass Solution:\n \n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = max(nums)\n res = 1\n tree = SegmentTree(0, n)\n for num in nums:\n mm = tree.rangeQuery(max(0, num - k), num-1)\n tree.update(num, mm + 1)\n res = max(res, mm + 1)\n return res\n``` | 1 | 0 | ['Python3'] | 0 |
longest-increasing-subsequence-ii | C++ simple and short, no segment tree. | c-simple-and-short-no-segment-tree-by-ir-dk2o | Intuition\n\n1. When an element is added to an existing sequence, this breaks the sequence into two sequences: with and without the added element, unless the ne | irisonia | NORMAL | 2023-09-02T08:04:08.203499+00:00 | 2023-11-09T13:22:52.522199+00:00 | 489 | false | # Intuition\n\n1. When an element is added to an existing sequence, this breaks the sequence into two sequences: with and without the added element, unless the newly added value is exactly following the last element of the sequence, in which case we only keep the sequence with the new element.\nExample:\nInput: 1, 2, 10, 3, 4, 5, 6, 7, 20, 30, 40, 50, 60, 70, 80\nk: 10.\nWhen adding the 10 to the sequence [1, 2], we are blocking the option to add [3, 4, 5, 6, 7] to [1, 2], which is much better than just adding 10. So when adding 10, we do not override the sequence [1, 2], but leave it as it is, and just add another sequence: [1, 2, 10]. So we need to keep track of multiple sequences.\n2. When adding a new element to multiple existing sequences, we only need to remember one of them, the longest one, as they will all now grow in the same way, as they now all end with the same element.\n3. For every element from the input, try not to check all existing sequences for whether the new element can be added to them. Instead, try to immediately identify the sequences that surely match the addition, i.e. that their last element is up to k smaller than the new value.\n\n# Approach\nHold a map, where the key is the last element of a sequence, and the value is the maximum length so far, of a sequence that ends with this element.\nFor each element \'num\' from the input, point to its location in the map. if it does not exist, add it, with the value 1, representing the fact that even if this new element can\'t be added to any existing sequence, it makes a new sequence of its own, of length 1.\nThen binary search the map for the first element that is equal/bigger than \'num - k\'. that is the first sequence to which we can add \'num\'. iterate the elements between there until \'num\' itself, add 1 to each, representing the addition of the new element \'num\', and choose the longest resulting length, to be the value near the key \'num\' in the map. if one of these sequences ends with \'num - 1\', then this sequence can be removed, as it is now \'absorbed\' in the sequence that ends with \'num\'. Also, sequences that are shorter than the longest sequence that ends with \'num\' by more than the difference of their last element from \'num\', can also be removed, as they will never beat the length. \n\n# Complexity\n- Time complexity:\n - N for iterating the input, and then for each input element:\n - Twice log N for finding in the map.\n - N for iterating the sequences that we found in the map.\n - For the return: N for finding the biggest sequence in the map.\nConclusion: N^2\n\n- Space complexity:\nN for the map\n\nNote: Runtime beats only up to 78% of solutions, usually less, which is not ideal. However I like the simplicity of my solution.\n\n# Code\n```\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n map<int, int> sequences;\n \n for (auto num: nums) {\n auto it_num = sequences.emplace(num, 1).first;\n for (auto it_seq = sequences.lower_bound(num - k); it_seq != it_num; ) {\n it_num->second = max(it_num->second, it_seq->second + 1);\n if ((it_seq->first + 1 == num) || \n ((it_num->first - it_seq->first) <= (it_num->second - it_seq->second))) {\n it_seq = sequences.erase(it_seq);\n }\n else {\n ++it_seq;\n }\n }\n }\n \n return max_element(sequences.begin(), sequences.end(), [](auto s1, auto s2) { return s1.second < s2.second; })->second;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
longest-increasing-subsequence-ii | C++ Bottom-up Segment Tree (beats 100%) | c-bottom-up-segment-tree-beats-100-by-su-ohqo | Intuition\nImplement a naive DP, namely if we have state dp[i][value] be the best we can do with the first i elements and such that the last element is value. T | suhdavid11 | NORMAL | 2023-08-14T06:50:48.947474+00:00 | 2023-08-14T17:36:39.866198+00:00 | 237 | false | # Intuition\nImplement a naive DP, namely if we have state `dp[i][value]` be the best we can do with the first `i` elements and such that the last element is `value`. Then it is not hard to see that \n\n$$\n\\tt dp[i][nums[i]] = 1 + max_{v\\in [nums[i]-k, nums[i])} dp[i][v].\n$$\n\nBut this naive approach is only $O(n^2)$ so is not fast enough. We want at least $O(n \\log n)$. But thankfully, we can note that:\n\n* In the transition from `dp[i-1]` to `dp[i]` the only value that can change is `dp[i][nums[i]]`. So we dont need to maintain a whole dimension of DP.\n* We need to process find max of range (RMQ) quickly -- for this we can use Segment Tree.\n\nIn fact, we do not need a `dp` array at all, we need only maintain a segment tree and update it for each iteration over `nums`. \n# Approach\nMaintain a segment tree of size such that it can handle queries up to `1e5+1`. Here we use a segment tree that handles queries for segments $[l,r)$. Then iterate over nums, updating the segment tree as per the following sudo code:\n\n```\nfor num in nums:\n best = 1 + RMQ(num - k, num)\n Update(num, best)\n\nreturn RMQ(0, 1e5+1)\n```\nWe can look at the Naive DP to see why this works. The segment tree is a so-called "bottom up" segment tree where the nodes are stored in heap-like format where child of `tree[i]` is `tree[2*i], tree[2*i+1]`. This form of segment tree is known to be much faster than the normal recursive implementation (sometimes even faster than Fenwick Tree).\n# Complexity\n- Time complexity:\n$O(n \\log N)$, where $n$ is the lengths of `nums` and $N$ is max value of `nums` (but in implementation, we just use `1e5+1`). Both update and query operations on a segment tree are $O(\\log N)$. \n\n- Space complexity:\n$O(N)$, where $N$ is max of `nums`. \n\n# Code\n```\nconst int N = 1e5+1;\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n int t[2*N + 2]; memset(t, 0, sizeof(t));\n\n auto upd = [&](int p, int v) {\n p += N;\n t[p] = v;\n for(; p > 1; p >>= 1) t[p>>1] = max(t[p], t[p^1]);\n };\n\n auto qry = [&](int l, int r) {\n l+=N, r+=N;\n int ret = 0;\n for(; l<r; l>>=1, r>>=1) {\n if (l&1) ret = max(ret, t[l++]);\n if (r&1) ret = max(ret, t[--r]);\n }\n return ret;\n };\n\n //upd(nums[0], 1);\n\n for (int i=0; i<n; ++i) {\n int curr = nums[i];\n int best = 1 + qry(max(0, curr - k), curr);\n upd(curr, best);\n }\n int ans = qry(0, N+1);\n\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
longest-increasing-subsequence-ii | [Python] Segment Tree Template (3 mins) with thought process when being asked during interviews | python-segment-tree-template-3-mins-with-t3f7 | Segment Tree\nYour first intuition might be using binary search on the longest sequence maintained as iterating each num similarly to the quite popluar problem | jandk | NORMAL | 2023-07-23T21:20:14.970125+00:00 | 2023-07-23T21:20:14.970144+00:00 | 11 | false | ### Segment Tree\nYour first intuition might be using binary search on the longest sequence maintained as iterating each `num` similarly to the quite popluar problem `longest increasing subsequence`. However, it doesn\'t work with the requirement of having difference between adjacent elements of at most `k`. An anti-example could be `[4,1,2,5,4,7,6,9]` with `k` of 2. The original solution maintains the longest subsequence `[1,2,4,6]`, but the answer is `[1,2,5,7,9]`.\n\nIt indicates that we have to check each possible`num[j]` that `j < i and nums[j] + k >= nums[i]` for each `i` to get longest result, which results in dynamic programming. We can define `dp[nums[i]]` as the `the length of the longest subsequence ending with value of nums[i]`. And then we have to compare each `dp[nums[j]]` and find the longest one. \nIt looks feasible, but it runs too slow with the complexity is *O(NK)*. Any ways to improve it?\n\nThe invariance that we always pick the longest one from all of choices among range `nums[i] - k <= val< nums[i]` indicates we should think about a data strucure or algorithm that can quickly get the largest number/longest given a range.\nSegment Tree falls into this case perfectly, and it allows *O(lgN)* update and query so that it makes our algorithm *O(NlgN)*. \nNote, in this use case, segement tree is used for single update and range query. For each cell in the segment tree, it stores the `the length of the longest subsequence ending with values range from [left] and [right]` \nSo the algorithm looks like\n1. itearate each `num` \n2. query the longest length `length` for the range `num - k ~ num - 1` on the segment tree `st`.\n3. update the `length + 1` to the `st` at value of `num`\n4. query the entire `st` for the final result.\n\n*bonus* : some one might think that writing segment tree is quite hard, but the template below makes it easy for you to write the ST in 3 mins.\n\n```python\ndef lengthOfLIS(self, nums: List[int], k: int) -> int:\n\tn = max(nums) + 1 # 0 based\n\tst = [0] * (2 * n) # segment tree always uses twice as much space as orignal nums\n \n\tdef update(i, val): # single update template for max\n\t\ti += n\n\t\tst[i] = max(val, st[i])\n\t\twhile (i >> 1) > 0:\n\t\t\ti >>= 1\n\t\t\tst[i] = max(st[i << 1], st[i << 1 | 1])\n \n\tdef query(i, j): # template range query\n\t\ti, j = i + n, j + n\n\t\tans = 0\n\t\twhile i <= j:\n\t\t\tif i % 2:\n\t\t\t\tans = max(ans, st[i])\n\t\t\t\ti += 1\n\t\t\tif not j % 2:\n\t\t\t\tans = max(ans, st[j])\n\t\t\t\tj -= 1\n\t\t\ti >>= 1\n\t\t\tj >>= 1\n\t\treturn ans \n \n\tfor num in nums:\n\t\tleft, right = max(0, num - k), num - 1\n\t\tupdate(num, query(left, right) + 1)\n\treturn query(1, n - 1)\n```\n\n*Time Complexity* = **O(NlgN)**\n*Space Complexity* = **O(N)**\n | 1 | 0 | ['Tree', 'Python'] | 0 |
longest-increasing-subsequence-ii | Segment Tree Solution | Java | Explained | segment-tree-solution-java-explained-by-hcudn | Intuition\n Describe your first thoughts on how to solve this problem. \nThis questions is somehow similar to 315. Count of Smaller Numbers after Self which is | utkrsh003 | NORMAL | 2023-06-18T10:41:32.455505+00:00 | 2023-06-18T10:41:32.455526+00:00 | 98 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis questions is somehow similar to [315. Count of Smaller Numbers after Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) which is similar to [307. Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/). It is advisable to solve these before coming to this problem.\n\n[Reference video for 315](https://www.youtube.com/watch?v=tcsPJFKoNNY)\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The function initializes a new `SegmentTree` object named `st` with an array of size 100001. This segment tree will be used to store the maximum LIS length for each index in the `nums` array.\n\n2. The variable `ans` is initialized to 0, which will store the maximum LIS length found so far.\n\n3. The function iterates over each element `i` in the `nums` array:\n\n a. It performs a query on the segment tree `st` to find the maximum LIS length for the range from `i - k` to `i - 1`. This range represents the previous elements in the LIS where the difference between the current element and the previous element is at most `k`.\n\n b. It updates the segment tree at index `i` with the value `val + 1`, where `val` is the maximum LIS length for the range `i - k` to `i - 1`. This update represents adding the current element `i` to the LIS.\n\n c. It updates the `ans` variable with the maximum value between the current LIS length (`val + 1`) and the previous maximum length (`ans`).\n\n4. After processing all the elements in the `nums` array, the function returns the final maximum LIS length stored in the `ans` variable.\n\nNow, let\'s understand how the `SegmentTree` class is implemented:\n\n1. The `SegmentTree` class represents a segment tree data structure and has two member variables: `tree` and `arr`.\n\n - `tree` is an array that stores the maximum LIS length for each segment of the input array `arr`. It has a length of `4 * arr.length` to ensure enough space for the tree nodes.\n - `arr` is the input array for which the segment tree is built.\n\n2. The constructor of the `SegmentTree` class takes the input array `ar` as a parameter. It initializes the `arr` variable and calls the `build` function to construct the segment tree.\n\n3. The `query` function performs a range query on the segment tree to find the maximum LIS length within the given range `[l, r]`. It calls the private `query` function with the initial parameters `1`, `0`, `arr.length - 1`, `l`, and `r`.\n\n - If the current segment `[start, end]` is completely outside the query range `[l, r]`, it returns `Integer.MIN_VALUE` to indicate that there is no valid LIS length in this segment.\n - If the current segment `[start, end]` is completely inside the query range `[l, r]`, it returns the LIS length stored in the current node of the segment tree.\n - Otherwise, it recursively calls the `query` function on the left and right child segments, merges the results by taking the maximum, and returns the maximum LIS length found in the range `[l, r]`.\n\n4. The `update` function updates the segment tree at a specific position `pos` with a new value `val`. It calls the private `update` function with the initial parameters `1`, `0`, `arr.length - 1`, `\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nBoth update and query functions of segment tree are implemented in O(logn).\nFor each element in nums we are having one update and one query. Therefore time complexity for the function becomes ```O(N * logN)```\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```O(N)```\n\nwhere N is the length of the array.\n\n# Code\n```Java []\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n SegmentTree st = new SegmentTree(new int[100001]);\n\n int ans = 0;\n\n for(int i : nums){\n int val = st.query(i - k, i-1);\n st.update(i, val+1);\n ans = Math.max(val+1, ans);\n }\n\n return ans;\n \n }\n}\n\nclass SegmentTree {\n\n int tree[];\n int arr[];\n\n SegmentTree(int ar[]) {\n arr = ar;\n tree = new int[4 * arr.length];\n build(1, 0, arr.length - 1);\n }\n \n int query(int l, int r) {\n return query(1, 0, arr.length - 1, l, r);\n }\n\n void update(int pos, int val) {\n update(1, 0, arr.length - 1, pos, val);\n }\n\n private void build(int node, int start, int end) {\n if (start == end) {\n tree[node] = arr[start];\n } else {\n int mid = (start + end) / 2;\n int left = node * 2;\n int right = node * 2 + 1;\n build(left, start, mid);\n build(right, mid + 1, end);\n tree[node] = Math.max(tree[left], tree[right]);\n }\n }\n\n\n private void update(int node, int start, int end, int pos, int val) {\n if (start == end) {\n arr[start] = val;\n tree[node] = val;\n } else {\n int mid = (start + end) / 2;\n if (start <= pos && pos <= mid) {\n update(node * 2, start, mid, pos, val);\n } else {\n update(node * 2 + 1, mid + 1, end, pos, val);\n }\n tree[node] = Math.max(tree[node * 2], tree[node * 2 + 1]);\n }\n }\n\n private int query(int node, int start, int end, int l, int r) {\n if (end < l || r < start)\n return Integer.MIN_VALUE;\n\n if (start == end) {\n return tree[node];\n } else if (l <= start && end <= r) {\n return tree[node];\n } else {\n int mid = (start + end) / 2;\n int left = query(node * 2, start, mid, l, r);\n int right = query(node * 2 + 1, mid + 1, end, l, r);\n\n return Math.max(left, right);\n }\n }\n\n\n\n}\n\n``` | 1 | 0 | ['Segment Tree', 'Java'] | 0 |
longest-increasing-subsequence-ii | thought process, 100%, nlog(k), segment tree, optimization | thought-process-100-nlogk-segment-tree-o-3yfz | Intuition\n1. based on already-well-explained segment tree solution\n - https://leetcode.com/problems/longest-increasing-subsequence-ii/solutions/2560085/pyt | jimhorng | NORMAL | 2023-01-13T13:15:37.678841+00:00 | 2023-01-15T01:57:11.205505+00:00 | 235 | false | # Intuition\n1. based on already-well-explained segment tree solution\n - https://leetcode.com/problems/longest-increasing-subsequence-ii/solutions/2560085/python-explanation-with-pictures-segment-tree/\n - https://codeforces.com/blog/entry/18051\n2. these common solutions set the segment tree\'s leaves as `0 ~ max(nums)`, when case like `nums=[1, 10^5]` it still require `10^5` leaves with query/update time of `log(2*10^5)` to deal with only 2 elements\n3. can we optimize this case?\n4. yes, we can condense the unit of leaves as elements of unqiue nums with accending order, so that each number of leaves becomes `|unique nums|`\ne.g. `nums=[1, 1, 10^5, 10^5]` : 2 leaves\n5. but how can we do query with given num? e.g. \n```text\nk = 3\nidx: 0 1 2 3 4 5 6 7 8\nnums:[4,2,1,4,3,4,5,8,15], \n ^ query:val:2 ~ 4\n```\n6. since the sorted unique nums has it\'s own idx, then we can pre-process to find each idx\'s query range (also idxs) by sliding window\ne.g.\n```text\nidx: 0 1 2 3 4 5 6 7 8\nnums:[4,2,1,4,3,4,5,8,15] \n\nsorted unique number as leaves ->\nidx: 0 1 2 3 4 5 6\nnums:[1,2,3,4,5,8,15]\n - - - ^ query idx:4 -> idx:2 ~ 3\n```\n7. apply back to segment tree, the leaves can be stored as idx of sorted unique number, and a mapping of `num to new idx`, each query of num convert to new idx and find query range from pre-processed queries\ne.g. \n```text\nsorted unique number as leaves:\nidx: 0 1 2 3 4 5 6\nnums:[1,2,3,4,5,8,15]\n ^ query:idx:2 ~ 3\n\noriginal nums:\nidx: 0 1 2 3 4 5 6 7 8\nnums:[4,2,1,4,3,4,5,8,15] \n ^ query -> new_idx[5]=4 -> query_idx[4]=2~3\n```\n8. put all together: (T: `O(n log(k))` = `n + klog(k)` + `n` + `k` + `n * log(k)`, n:|nums|, k:|unique nums|)\n 1. unique nums and sort ascending ( T:`n + klog(k)`)\n 2. creating num:idx of newly sorted list mapping ( T:`n`)\n 3. create query range of each new idx using sliding window ( T:`k` )\n 4. iterate all nums ( T:`n`)\n 1. find it\'s previous nums\' LIS via segment tree ( T:`log(k)` )\n 2. update new LIS value of this num to segment tree ( T:`log(k)` )\n9. submission record\n\n\n\n# Code\n```python\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n class SegmentTree:\n def __init__(self, leaves, val_init):\n self.nodes = 2 ** math.ceil(math.log2(leaves))\n self.seq_tree = [val_init for _ in range(self.nodes * 2)]\n\n def update(self, i_leaf, val):\n i_st = i_leaf + self.nodes\n while i_st >= 1:\n if val > self.seq_tree[i_st]:\n self.seq_tree[i_st] = val\n else:\n break\n i_st = math.floor(i_st/2)\n\n def query(self, i_leaf_left, i_leaf_right):\n i_left_st, i_right_st = i_leaf_left+self.nodes, i_leaf_right+self.nodes\n val_max = 0\n while i_left_st >= 1 and i_right_st >=1 and i_left_st <= i_right_st:\n # left\n if i_left_st % 2 == 1:\n val_max = max(val_max, self.seq_tree[i_left_st])\n i_left_st += 1\n # right\n if i_right_st % 2 == 0:\n val_max = max(val_max, self.seq_tree[i_right_st])\n i_right_st -= 1\n i_left_st = math.floor(i_left_st/2)\n i_right_st = math.floor(i_right_st/2)\n return val_max\n \n def process_query_range(nums_unique_st):\n """ ret: list[i]:(i_from,i_to) """\n query_range = []\n l = 0\n for r in range(len(nums_unique_st)):\n while nums_unique_st[l] < nums_unique_st[r]-k:\n l += 1\n if r == l:\n query_range.append(None)\n else:\n query_range.append([l,r-1])\n return query_range\n\n # main\n # 4. build sorted unique nums\n nums_unique_st = sorted(list(set(nums)))\n # 7. build mappings of num to idx of sorted unique nums\n num_to_i = {num:i for i, num in enumerate(nums_unique_st)}\n # 6. pre-proces query range for each num in idx manner\n query_range = process_query_range(nums_unique_st)\n # 7. build segment tree with number of idx in sorted unique nums\n seg_tree = SegmentTree(len(nums_unique_st), 0)\n\n # 7. iterate all num, query max lis for the nums before it\n for num in nums:\n i = num_to_i[num]\n lis = 1\n if query_range[i] is not None:\n i_from, i_to = query_range[i]\n lis += seg_tree.query(i_from, i_to)\n seg_tree.update(i, lis)\n lis_max = seg_tree.query(0, len(nums_unique_st)-1)\n return lis_max\n``` | 1 | 0 | ['Python'] | 0 |
longest-increasing-subsequence-ii | [C++] Segment Tree || Short Implementation + Fast | c-segment-tree-short-implementation-fast-ybuh | cpp\nclass Solution {\npublic:\n vector<int> seg;\n \n int getSize(int n){\n int size = 1;\n for(;size < n; size<<=1);\n return si | sandrikosxila | NORMAL | 2022-09-17T18:03:29.274157+00:00 | 2022-09-17T18:03:29.274190+00:00 | 244 | false | ```cpp\nclass Solution {\npublic:\n vector<int> seg;\n \n int getSize(int n){\n int size = 1;\n for(;size < n; size<<=1);\n return size;\n }\n \n void insert(int index, int value, int size){\n for(int i = index + size - 1; i > 0; seg[i]=max(seg[i], value), i>>=1);\n }\n \n int get(int start, int end, int index, int l, int r){\n if(r < start || l > end)\n return 0;\n if(start <= l && r <= end){\n return seg[index];\n }\n int mid = (l + r) >> 1;\n return max(\n get(start, end, index << 1, l, mid), \n get(start, end, (index << 1) + 1, mid + 1, r)\n );\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size();\n int size = getSize(1e5);\n seg = vector<int>(size * 2, 0);\n \n int ans{};\n \n for(int i = 1; i <= n; i++){\n int num = nums[i - 1];\n int mx = get(max(1, num - k), num - 1, 1, 1, size);\n insert(num, mx + 1, size);\n ans = max(ans, seg[num + size - 1]);\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Tree', 'C'] | 0 |
longest-increasing-subsequence-ii | [Java] Segment Tree beats 100% | java-segment-tree-beats-100-by-luoyunfen-67zm | \nclass Solution {\n private int[] segments;\n private int n;\n public int lengthOfLIS(int[] nums, int k) {\n int max = 0;\n for (int num | luoyunfeng1853 | NORMAL | 2022-09-12T09:24:18.153475+00:00 | 2022-09-12T09:24:18.153510+00:00 | 122 | false | ```\nclass Solution {\n private int[] segments;\n private int n;\n public int lengthOfLIS(int[] nums, int k) {\n int max = 0;\n for (int num : nums) {\n max = Math.max(max, num);\n }\n \n n = max;\n segments = new int[n*2];\n \n int res = 0;\n for (int num : nums) {\n int tmp = query(num-k-1 <= 0 ? 0 : num-k-1, num-2);\n update(num-1 + n, tmp + 1);\n res = Math.max(res, tmp+1);\n }\n return res;\n }\n \n private void update(int idx, int val) {\n segments[idx] = val;\n for (int i = idx; i > 1; i /= 2) {\n int p = i / 2;\n segments[p] = Math.max(segments[2*p], segments[2*p+1]);\n }\n }\n \n \n private int query(int left, int right) {\n left += n;\n right += n;\n \n int res = 0;\n \n while (left <= right) {\n if (left % 2 == 1) {\n res = Math.max(segments[left++], res);\n }\n \n if (right % 2 == 0) {\n res = Math.max(segments[right--], res);\n }\n \n left /= 2;\n right /= 2;\n }\n \n return res;\n }\n \n}\n``` | 1 | 0 | ['Tree', 'Java'] | 0 |
longest-increasing-subsequence-ii | Segment Tree C++ Clean Code | segment-tree-c-clean-code-by-jinyeli1996-855f | \nclass Solution {\npublic:\n vector<int> seg;\n int n=100001;\n \n int query(int left, int right){\n int ans=0;\n for(left+=n, right+ | jinyeli1996 | NORMAL | 2022-09-12T08:37:50.196096+00:00 | 2022-09-12T08:37:50.196135+00:00 | 158 | false | ```\nclass Solution {\npublic:\n vector<int> seg;\n int n=100001;\n \n int query(int left, int right){\n int ans=0;\n for(left+=n, right+=n; left<right; left>>=1, right>>=1){\n if(left&1){\n ans=max(ans, seg[left++]);\n }\n if(right&1){\n ans=max(ans, seg[--right]);\n }\n }\n \n return ans;\n }\n \n void update(int index, int val){\n for(seg[index+=n]=val; index>1; index>>=1){\n seg[index>>1]=max(seg[index],seg[index^1]);\n }\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n seg.resize(2*n+1, 0);\n int ans=0;\n \n for(auto& i:nums){\n int left=max(i-k, 1);\n int sum=query(left, i);\n ans=max(ans, sum+1);\n update(i, sum+1);\n }\n \n return ans;\n }\n};\n``` | 1 | 0 | [] | 1 |
longest-increasing-subsequence-ii | Does not work for sequential numbers from 1 to 10^5. - JAVA - dp - with memoization - TLE | does-not-work-for-sequential-numbers-fro-3zar | This one does not work for large test cases typically 1 to 100000 with unit increase. Looks like it should - any idea\n\n\nclass Solution {\n int res;\n p | venkim | NORMAL | 2022-09-12T02:10:03.328867+00:00 | 2022-09-12T02:10:09.668390+00:00 | 237 | false | This one does not work for large test cases typically 1 to 100000 with unit increase. Looks like it should - any idea\n\n```\nclass Solution {\n int res;\n public int lengthOfLIS(int[] nums, int k) {\n int n = nums.length;\n // keep track of state\n Integer[] dp = new Integer [n];\n dp[n-1] = 1;\n res = 1;\n helper(0, nums, k , dp);\n return res;\n }\n private int helper(int sta, int[] nums, int k, Integer[] dp){\n int n = nums.length;\n if (sta >= n){\n return 0;\n }\n if (dp[sta] != null){\n return dp[sta];\n }\n int rslt = 1;\n for(int i = sta+1; i < n; i++){\n if (nums[i] > nums[sta] && \n nums[i] - nums[sta] <= k){\n rslt = Math.max(rslt, 1 + helper(i, nums, k, dp));\n } else {\n // skip the sta point - but traverse for i\n helper(i, nums, k, dp);\n }\n }\n dp[sta] = rslt;\n res = Math.max(rslt, res);\n return rslt;\n }\n}\n``` | 1 | 0 | [] | 0 |
longest-increasing-subsequence-ii | Python Iterativr segment tree | python-iterativr-segment-tree-by-vignesh-vx7u | \nclass ST:\n def __init__(self,n):\n self.arr=[0 for i in range(4*n)]\n self.n=n\n\n def update(self,ind,val):\n def rec(i,l,r):\n | vigneshreddyjulakanti | NORMAL | 2022-09-11T16:44:38.175804+00:00 | 2022-09-11T16:44:38.175863+00:00 | 107 | false | ```\nclass ST:\n def __init__(self,n):\n self.arr=[0 for i in range(4*n)]\n self.n=n\n\n def update(self,ind,val):\n def rec(i,l,r):\n if l==r:\n self.arr[i]=val\n return\n m=(l+r)//2\n if m>=ind:\n rec(2*i+1,l,m)\n else:\n rec(2*i+2,m+1,r)\n self.arr[i]=max(self.arr[2*i+1],self.arr[2*i+2])\n rec(0,0,self.n-1)\n def rangemax(self,left,right):\n def rec(i,l,r,left,right):\n if l>=left and r<=right:\n return self.arr[i]\n elif l>right or r<left:\n return 0\n else:\n m=(l+r)//2\n return max(rec(2*i+1,l,m,left,right),rec(2*i+2,m+1,r,left,right))\n return rec(0,0,self.n-1,left,right)\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n m=max(nums)\n obj=ST(m+1)\n ans=0\n for i in nums:\n prev=obj.rangemax(max(0,i-k),i-1)\n ans=max(ans,prev+1)\n obj.update(i,prev+1)\n # print(i,obj.arr)\n return ans\n \n \n \n \n \nclass IST:\n def __init__(self,n):\n self.arr=[0 for i in range(2*n)]\n self.n=n\n def update(self,ind,val):\n ind+=self.n\n self.arr[ind]=val\n ind//=2\n while(ind>0):\n self.arr[ind]=max(self.arr[ind*2+1],self.arr[ind*2])\n ind//=2\n \n def rangemax(self,left,right):\n ans=0\n left+=self.n\n right+=self.n\n while(left<=right):\n if left&1:\n ans=max(ans,self.arr[left])\n left+=1\n if right&1==0:\n ans=max(ans,self.arr[right])\n right-=1\n left//=2\n right//=2\n return ans\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n m=max(nums)\n obj=IST(m+1)\n ans=0\n for i in nums:\n prev=obj.rangemax(max(0,i-k),i-1)\n ans=max(ans,prev+1)\n obj.update(i,prev+1)\n # print(i,obj.arr)\n return ans \n\n \n dici={}\n def rec(i,l):\n if i in dici:\n if l in dici[i]:\n return dici[i][l]\n if i>=len(nums):\n return 0\n if l==-1:\n return max(rec(i+1,nums[i])+1,rec(i+1,l))\n take=0\n \n if nums[i]<=l or l+k<nums[i] :\n take= 0\n else:\n take=rec(i+1,nums[i])+1\n ans= max(take,rec(i+1,l))\n if i not in dici:\n dici[i]={}\n dici[i][l]=ans\n return ans\n \n return rec(0,-1)\n \n \n \n``` | 1 | 0 | [] | 0 |
longest-increasing-subsequence-ii | [Kotlin] Segment Tree | kotlin-segment-tree-by-roka-ydrt | kotlin\nimport kotlin.math.max\nimport kotlin.math.min\n\nclass Solution {\n companion object {\n const val MAX_VALUE = 100010\n }\n\n fun lengt | roka | NORMAL | 2022-09-11T16:04:42.636868+00:00 | 2022-09-11T16:04:42.636910+00:00 | 42 | false | ```kotlin\nimport kotlin.math.max\nimport kotlin.math.min\n\nclass Solution {\n companion object {\n const val MAX_VALUE = 100010\n }\n\n fun lengthOfLIS(nums: IntArray, k: Int): Int {\n val tree = Tree(MAX_VALUE)\n var answer = 0\n\n nums.forEach { cur ->\n val prev = max(0, cur - k)\n val bestAnswer = tree.get(prev, cur - 1) + 1\n val prevAnswer = tree.get(cur, cur)\n val result = max(bestAnswer, prevAnswer)\n \n tree.set(cur, result)\n answer = max(answer, result)\n }\n\n return answer\n }\n}\n\nclass Tree(private val size: Int) {\n private val root: Node\n\n init {\n this.root = build(0, size)\n }\n\n fun get(from: Int, to: Int): Int {\n return get(this.root, 0, this.size, from, to)\n }\n\n private fun get(node: Node, left: Int, right: Int, from: Int, to: Int): Int {\n if (to < from) {\n return 0\n }\n\n if (from <= left && right <= to) {\n return node.value\n }\n\n val mid = (left + right) / 2\n return max(\n get(node.left!!, left, mid, from, min(mid, to)),\n get(node.right!!, mid + 1, right, max(mid + 1, from), to)\n )\n }\n\n fun set(idx: Int, value: Int) {\n set(this.root, 0, this.size, idx, value)\n }\n\n private fun set(node: Node, left: Int, right: Int, idx: Int, value: Int) {\n if (left > idx || right < idx) {\n return\n }\n\n if (left == right) {\n node.value = value\n } else {\n val mid = (left + right) / 2\n set(node.left!!, left, mid, idx, value)\n set(node.right!!, mid + 1, right, idx, value)\n\n node.value = max(node.left!!.value, node.right!!.value)\n }\n }\n\n private fun build(from: Int, to: Int): Node {\n return if (from == to) {\n Node(0)\n } else if (from > to) {\n throw IllegalArgumentException("Unexpected range $from..$to")\n } else {\n val mid = (from + to) / 2\n val left = build(from, mid)\n val right = build(mid + 1, to)\n\n Node(left, right)\n }\n }\n}\n\ndata class Node(var value: Int) {\n var left: Node? = null\n var right: Node? = null\n\n constructor(left: Node, right: Node) : this(max(left.value, right.value)) {\n this.left = left\n this.right = right\n }\n}\n``` | 1 | 0 | ['Tree', 'Kotlin'] | 0 |
longest-increasing-subsequence-ii | Rust Segment Tree | rust-segment-tree-by-xiaoping3418-zosb | ~~~\nimpl Solution {\n pub fn length_of_lis(nums: Vec, k: i32) -> i32 {\n let n = *nums.iter().max().unwrap() as usize + 1;\n let mut tree = ve | xiaoping3418 | NORMAL | 2022-09-11T10:50:21.081981+00:00 | 2022-09-11T10:51:35.569107+00:00 | 88 | false | ~~~\nimpl Solution {\n pub fn length_of_lis(nums: Vec<i32>, k: i32) -> i32 {\n let n = *nums.iter().max().unwrap() as usize + 1;\n let mut tree = vec![0; 4 * n];\n let mut ret = 1;\n \n for a in nums {\n let temp = Self::find(&tree, 1, 0, n - 1, i32::max(0, a - k) as usize, a as usize - 1);\n ret = ret.max(temp + 1);\n Self::update(&mut tree, 1, 0, n - 1, a as usize, temp + 1);\n }\n \n ret\n }\n \n fn find(tree: &Vec<i32>, u: usize, left: usize, right: usize, l: usize, r: usize) -> i32 {\n if l > right || r < left { return 0 }\n if left == right { return tree[u] }\n if left >= l && right <= r { return tree[u] }\n \n let mid = left + (right - left) / 2;\n \n let ret1 = Self::find(tree, 2 * u, left, mid, l, r);\n let ret2 = Self::find(tree, 2 * u + 1, mid + 1, right, l, r);\n \n ret1.max(ret2)\n }\n \n fn update(tree: &mut Vec<i32>, u: usize, left: usize, right: usize, i: usize, val: i32) {\n if left == right {\n tree[u] = val;\n return\n }\n \n let mid = left + (right - left) / 2;\n\t\t\n if i <= mid { Self::update(tree, 2 * u, left, mid, i, val); }\n else { Self::update(tree, 2 * u + 1, mid + 1, right, i, val); }\n \n tree[u] = i32::max(tree[2 * u], tree[2 * u + 1]);\n }\n}\n~~~ | 1 | 0 | ['Tree', 'Rust'] | 0 |
longest-increasing-subsequence-ii | Segment Tree | Java | segment-tree-java-by-pradhan222-b36f | For eg: 4,2,1,4,3,4,5,8,15\nat each index i,\nnums[i] -> find longest subsequence between in segment tree [max(1, nums[i] -k), nums[i] - 1)]\nand then update se | pradhan222 | NORMAL | 2022-09-11T06:01:09.773805+00:00 | 2022-09-11T06:08:36.239107+00:00 | 355 | false | For eg: 4,2,1,4,3,4,5,8,15\nat each index i,\nnums[i] -> find longest subsequence between in segment tree [max(1, nums[i] -k), nums[i] - 1)]\nand then update segment tree for nums[i] with (longest subsequence + 1).\n\nfor index 6, nums[6] = 5\nstart range = 5 - 3 = 2\nend range = 5 - 1 = 4\nlongest subsequece in range [2,4] is 3. i.e {1,3,4}\nand then update 5 in ST to (3 + 1).i.e 4\n\n```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n int n = nums.length;\n SegTree segTree = new SegTree(maxValue(nums) + 1);\n \n int ans = 1;\n for(int i = 0; i < n; i++) {\n int start = Math.max(1, nums[i] - k);\n int end = nums[i] - 1;\n int res = segTree.query(start, end);\n ans = Math.max(ans, 1 + res);\n segTree.update(nums[i], res + 1);\n }\n return ans;\n }\n \n private int maxValue(int[] nums) {\n int max = 0;\n for(int num : nums)\n max = Math.max(max, num);\n return max;\n }\n \n}\n\nclass SegTree {\n int[] tree;\n int n;\n \n SegTree(int n) {\n this.n = n;\n tree = new int[4 * n];\n }\n \n public void update(int i, int val) {\n update(0, n - 1, i, 0, val);\n }\n \n private void update(int l, int r, int i, int node, int val) {\n if(l == r) {\n tree[node] = val;\n return;\n }\n int mid = l + (r - l) / 2;\n if(i <= mid) update(l, mid, i, 2 * node + 1, val);\n else update(mid + 1, r, i, 2 * node + 2, val);\n tree[node] = Math.max(tree[node], Math.max(tree[2 * node + 1], tree[2 * node + 2]));\n }\n \n public int query(int st, int end) {\n return query(0, n - 1, st, end, 0);\n }\n \n private int query(int l, int r, int st, int end, int node) {\n if(l > end || r < st) return 0;\n if(l >= st && r <= end) {\n return tree[node];\n }\n int mid = l + (r - l) / 2;\n int res = query(l, mid, st, end, 2 * node + 1);\n res = Math.max(res, query(mid + 1, r, st, end, 2 * node + 2));\n return res;\n }\n}\n``` | 1 | 0 | ['Tree', 'Java'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.