title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Very Easy || 100% || Fully Explained || Java, C++, Python, JavaScript, Python3 || DFS || Recursion | flood-fill | 1 | 1 | **Problem Statement:**\n\nAn image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.\n\nYou are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].\n\nTo perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.\n\nReturn the modified image after performing the flood fill.\n \n \n\n# **Java Solution:**\n```\n// Runtime: 1 ms, faster than 90.98% of Java online submissions for Flood Fill.\n// Time Complexity : O(n*m)\n// Space Complexity : O(n*m)\nclass Solution {\n public int[][] floodFill(int[][] image, int sr, int sc, int color) {\n // Avoid infinite loop if the new and old colors are the same...\n if(image[sr][sc] == color) return image;\n // Run the fill function starting at the position given...\n fill(image, sr, sc, color, image[sr][sc]);\n return image;\n }\n public void fill(int[][] image, int sr, int sc, int color, int cur) {\n // If sr is less than 0 or greater equals to the length of image...\n // Or, If sc is less than 0 or greater equals to the length of image[0]...\n if(sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) return;\n // If image[sr][sc] is not equal to previous color...\n if(cur != image[sr][sc]) return;\n // Update the image[sr][sc] as a color...\n image[sr][sc] = color;\n // Make four recursive calls to the function with (sr-1, sc), (sr+1, sc), (sr, sc-1) and (sr, sc+1)...\n fill(image, sr-1, sc, color, cur);\n fill(image, sr+1, sc, color, cur);\n fill(image, sr, sc-1, color, cur);\n fill(image, sr, sc+1, color, cur);\n }\n}\n```\n\n# **C++ Solution:**\n```\n// Time Complexity : O(n*m)\n// Space Complexity : O(n*m)\nclass Solution {\npublic:\n void fill(vector<vector<int>>& image, int sr, int sc, int color, int cur) {\n // If sr is less than 0 or greater equals to the length of image...\n // Or, If sc is less than 0 or greater equals to the length of image[0]...\n if(sr < 0 || sr >= image.size() || sc < 0 || sc >= image[0].size()) return;\n // If image[sr][sc] is not equal to previous color...\n if(cur != image[sr][sc]) return;\n // Update the image[sr][sc] as a color...\n image[sr][sc] = color;\n // Make four recursive calls to the function with (sr-1, sc), (sr+1, sc), (sr, sc-1) and (sr, sc+1)...\n fill(image, sr-1, sc, color, cur);\n fill(image, sr+1, sc, color, cur);\n fill(image, sr, sc-1, color, cur);\n fill(image, sr, sc+1, color, cur);\n }\n vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {\n // Avoid infinite loop if the new and old colors are the same...\n if(image[sr][sc] == color) return image;\n // Run the fill function starting at the position given...\n fill(image, sr, sc, color, image[sr][sc]);\n return image;\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\n# Time Complexity : O(n*m)\n# Space Complexity : O(n*m)\nclass Solution(object):\n def fill(self, image, sr, sc, color, cur):\n # If sr is less than 0 or greater equals to the length of image...\n # Or, If sc is less than 0 or greater equals to the length of image[0]...\n if sr < 0 or sr >= len(image) or sc < 0 or sc >= len(image[0]): return;\n # If image[sr][sc] is not equal to previous color...\n if cur != image[sr][sc]: return;\n # Update the image[sr][sc] as a color...\n image[sr][sc] = color;\n # Make four recursive calls to the function with (sr-1, sc), (sr+1, sc), (sr, sc-1) and (sr, sc+1)...\n self.fill(image, sr-1, sc, color, cur);\n self.fill(image, sr+1, sc, color, cur);\n self.fill(image, sr, sc-1, color, cur);\n self.fill(image, sr, sc+1, color, cur);\n def floodFill(self, image, sr, sc, color):\n # Avoid infinite loop if the new and old colors are the same...\n if image[sr][sc] == color: return image;\n # Run the fill function starting at the position given...\n self.fill(image, sr, sc, color, image[sr][sc]);\n return image;\n```\n\n# **JavaScript Solution:**\n```\n// Time Complexity : O(n*m)\n// Space Complexity : O(n*m)\nvar floodFill = function(image, sr, sc, color) {\n // Avoid infinite loop if the new and old colors are the same...\n if(image[sr][sc] == color) return image;\n // Run the fill function starting at the position given...\n fill(image, sr, sc, color, image[sr][sc]);\n return image;\n}\nvar fill = function(image, sr, sc, color, cur) {\n // If sr is less than 0 or greater equals to the length of image...\n // Or, If sc is less than 0 or greater equals to the length of image[0]...\n if(sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) return;\n // If image[sr][sc] is not equal to previous color...\n if(cur != image[sr][sc]) return;\n // Update the image[sr][sc] as a color...\n image[sr][sc] = color;\n // Make four recursive calls to the function with (sr-1, sc), (sr+1, sc), (sr, sc-1) and (sr, sc+1)...\n fill(image, sr-1, sc, color, cur);\n fill(image, sr+1, sc, color, cur);\n fill(image, sr, sc-1, color, cur);\n fill(image, sr, sc+1, color, cur);\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 93 | An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n` | Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels. |
Solution | flood-fill | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<pair<int,int>> dirs = {{0,-1}, {0,1}, {1,0}, {-1,0}};\n void dfs(int i, int j, vector<vector<int>>& image, int oldColor, int newColor){\n int n = image.size();\n int m = image[0].size();\n if( i < 0 || i>=n || j < 0 || j >= m || image[i][j] != oldColor)\n return;\n \n image[i][j] = newColor;\n for(auto &dir : dirs) {\n dfs(i+dir.first, j+dir.second, image, oldColor, newColor);\n }\n }\n void bfs(int i, int j, vector<vector<int>> &img, int old, int newc) {\n int n = img.size();\n int m = img[0].size();\n queue<pair<int,int>> q;\n q.push({i,j});\n img[i][j] = newc;\n\n int dir[4][2] = {{-1,0} , {1,0}, {0,-1}, {0,1}};\n while(!q.empty()) {\n auto curr = q.front();\n q.pop();\n\n for(int i=0; i<4; i++){\n int newi = curr.first + dir[i][0];\n int newj = curr.second + dir[i][1];\n\n if(newi < 0 || newi>=n || newj < 0 || newj >= m || img[newi][newj] != old)\n continue;\n q.push({newi, newj});\n img[newi][newj] = newc;\n }\n }\n }\n vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {\n int color = image[sr][sc];\n if(color != newColor)\n bfs(sr, sc, image, image[sr][sc], newColor);\n return image;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n src_col = image[sr][sc]\n if src_col == color:\n return image\n \n flood = [(sr,sc)]\n width = len(image)\n height = len(image[0])\n while flood:\n curr = flood.pop(0)\n image[curr[0]][curr[1]] = color\n if (up:=curr[0]-1) >= 0 and src_col == image[up][curr[1]]:\n flood.append((up, curr[1]))\n\n if (down:=curr[0]+1) < width and src_col == image[down][curr[1]]:\n flood.append((down, curr[1]))\n\n if (left:=curr[1]-1) >= 0 and src_col == image[curr[0]][left]:\n flood.append((curr[0], left))\n \n if (right:=curr[1]+1) < height and src_col == image[curr[0]][right]:\n flood.append((curr[0], right))\n\n return image\n```\n\n```Java []\nclass Solution {\n public int[][] floodFill(int[][] image, int sr, int sc, int color) {\n if (image[sr][sc] == color) {\n return image;\n }\n fill(image, sr, sc, image[sr][sc], color);\n return image;\n }\n public void fill(int[][] image, int sr, int sc, int org, int color) {\n if (sr >= 0 && sc >= 0 && sr < image.length && sc < image[0].length && image[sr][sc] == org) {\n image[sr][sc] = color;\n fill(image, sr-1, sc, org, color);\n fill(image, sr+1, sc, org, color);\n fill(image, sr, sc-1, org, color);\n fill(image, sr, sc+1, org, color);\n }\n }\n}\n```\n | 2 | An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n` | Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels. |
Simple dfs python | flood-fill | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def floodFill(self, grid: List[List[int]], x: int, y: int, color: int) -> List[List[int]]:\n curr = grid[x][y]\n n = len(grid)\n m = len(grid[0])\n def dfs(i, j):\n if 0 <= i < n and 0 <= j < m and grid[i][j] == curr and grid[i][j] != color:\n grid[i][j] = color\n dfs(i+1, j)\n dfs(i-1, j)\n dfs(i, j+1)\n dfs(i, j-1)\n dfs(x, y)\n return grid\n``` | 3 | An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n` | Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels. |
✔️ Python Flood Fill Algorithm | 98% Faster 🔥 | flood-fill | 0 | 1 | **\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: https://www.python-techs.com/\n\n**Solution:**\n```\nclass Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n \n start_color = image[sr][sc]\n \n def flood_fill(x, y):\n if x < 0 or x >= len(image): return\n if y < 0 or y >= len(image[0]): return\n \n if image[x][y] == color: return\n if image[x][y] != start_color: return\n \n image[x][y] = color\n \n flood_fill(x-1, y)\n flood_fill(x+1, y)\n flood_fill(x, y+1)\n flood_fill(x, y-1)\n \n flood_fill(sr, sc)\n return image\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.** | 52 | An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image.
You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`.
To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`.
Return _the modified image after performing the flood fill_.
**Example 1:**
**Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2
**Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\]
**Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
**Example 2:**
**Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0
**Output:** \[\[0,0,0\],\[0,0,0\]\]
**Explanation:** The starting pixel is already colored 0, so no changes are made to the image.
**Constraints:**
* `m == image.length`
* `n == image[i].length`
* `1 <= m, n <= 50`
* `0 <= image[i][j], color < 216`
* `0 <= sr < m`
* `0 <= sc < n` | Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels. |
C++ stack vs vector/Python list | asteroid-collision | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThat is a stack problem. One approach is using C++ STL stack. In the second version, Python code uses list and C++ uses vector!\n\nThe programming becomes easier!\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$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n vector<int> asteroidCollision(vector<int>& asteroids) {\n stack<int> st;\n for(int x: asteroids){\n bool survive=1;\n if(x>0) st.push(x);\n else{ //x<0\n while(!st.empty()){\n int y=st.top();\n if (y<0) break;\n else if (x+y==0) {\n survive=0;\n st.pop();\n break;\n }\n else if (x+y<0){\n st.pop();\n }\n else{\n survive=0;\n break;\n } \n }\n if (survive) \n st.push(x);\n }\n }\n int n=st.size();\n vector<int> ans(n);\n for(int i=n-1; i>=0; i--){\n ans[i]=st.top();\n st.pop();\n }\n return ans;\n }\n};\n```\n# Code using C++ vector, in fact vector can used as a stack makes programming easier!\n```\nclass Solution {\npublic:\n vector<int> asteroidCollision(vector<int>& asteroids) {\n vector<int> st;\n for(int x: asteroids){\n bool survive=1;\n if(x>0) st.push_back(x);\n else{ //x<0\n while(!st.empty()){\n int y=st.back();\n if (y<0) break;\n else if (x+y==0) {\n survive=0;\n st.pop_back();\n break;\n }\n else if (x+y<0){\n st.pop_back();\n }\n else{\n survive=0;\n break;\n } \n }\n if (survive) \n st.push_back(x);\n }\n }\n return st;\n }\n};\n\n```\n# Python using just list\n```\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n st = []\n for x in asteroids:\n surv = True\n if x > 0:\n st.append(x)\n else:\n while len(st) > 0:\n y = st[-1]\n if y < 0:\n break\n elif x + y == 0:\n surv = False\n st.pop()\n break\n elif x + y < 0:\n st.pop()\n else:\n surv = False\n break\n if surv:\n st.append(x)\n return st\n```\n | 2 | We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0` | Say a row of asteroids is stable. What happens when a new asteroid is added on the right? |
🤩 Simple Iteration | No Stack needed | Beats 100% | Runtime 1ms | asteroid-collision | 1 | 1 | # Intuition\nThe intuition behind the optimized approach is to simulate the asteroid collisions while using an in-place modification of the original array. By iterating through the array and updating it in a way that ensures surviving asteroids are placed in the front of the array, we can avoid using an additional stack for storing the final state of the asteroids.\n\n# Approach\n1. Initialize a variable j to keep track of the position where the next surviving asteroid should be placed in the array.\n2. Iterate through the given asteroids array using a loop.\n3. For each asteroid, check if it will collide with the asteroids that are already placed in the array.\n4. If the current asteroid survives the collision, place it at index j and increment j by 1.\n5. If it explodes during the collision, discard it and continue checking the remaining asteroids in the array.\n6. The final state of the asteroids will be the elements from index 0 to j-1 in the modified array.\n\nThe above approach eliminates the need for an additional stack, reduces space complexity, and achieves the same result as the initial approach with improved performance.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public int[] asteroidCollision(int[] asteroids) {\n int n = asteroids.length;\n int j = 0;\n\n for (int i = 0; i < n; i++) {\n int asteroid = asteroids[i];\n while (j>0 && asteroids[j-1]>0 && asteroid<0 && asteroids[j-1] < Math.abs(asteroid)) \n {j--;}\n\n if (j==0 || asteroid>0 || asteroids[j-1]<0) \n asteroids[j++] = asteroid;\n else if(asteroids[j-1] == Math.abs(asteroid)) \n j--;\n }\n \n int[] result = new int[j];\n System.arraycopy(asteroids, 0, result, 0, j);\n\n return result;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> asteroidCollision(vector<int>& asteroids) {\n int n = asteroids.size();\n int j = 0;\n\n for (int i = 0; i < n; i++) {\n int asteroid = asteroids[i];\n\n while (j > 0 && asteroids[j - 1] > 0 && asteroid < 0 && asteroids[j - 1] < abs(asteroid)) {\n j--;\n }\n\n if (j == 0 || asteroid > 0 || asteroids[j - 1] < 0) {\n asteroids[j++] = asteroid;\n } else if (asteroids[j - 1] == abs(asteroid)) {\n j--;\n }\n }\n\n vector<int> result(asteroids.begin(), asteroids.begin() + j);\n\n return result;\n }\n};\n```\n```Python []\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n j = 0\n n = len(asteroids)\n\n for i in range(n):\n asteroid = asteroids[i]\n while j > 0 and asteroids[j - 1] > 0 and asteroid < 0 and asteroids[j - 1] < abs(asteroid):\n j -= 1\n\n if j == 0 or asteroid > 0 or asteroids[j - 1] < 0:\n asteroids[j] = asteroid\n j += 1\n elif asteroids[j - 1] == abs(asteroid):\n j -= 1\n return asteroids[:j]\n```\n```C []\nint* asteroidCollision(int* asteroids, int asteroidsSize, int* returnSize) {\n int j = 0;\n for (int i = 0; i < asteroidsSize; i++) {\n int asteroid = asteroids[i];\n\n while (j > 0 && asteroids[j - 1] > 0 && asteroid < 0 && asteroids[j - 1] < abs(asteroid)) \n {\n j--;\n }\n\n if (j == 0 || asteroid > 0 || asteroids[j - 1] < 0) {\n asteroids[j++] = asteroid;\n } else if (asteroids[j - 1] == abs(asteroid)) {\n j--;\n }\n }\n\n int* result = (int*)malloc(j * sizeof(int));\n for (int i = 0; i < j; i++) {\n result[i] = asteroids[i];\n }\n\n *returnSize = j;\n return result;\n}\n```\n> If you find my solution helpful, I would greatly appreciate your one upvote. | 46 | We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0` | Say a row of asteroids is stable. What happens when a new asteroid is added on the right? |
[Python 3] Simple stack solution | asteroid-collision | 0 | 1 | ```python3 []\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for a in asteroids:\n while stack and stack[-1] > 0 > a:\n if stack[-1] < abs(a):\n stack.pop()\n continue\n elif stack[-1] == abs(a):\n stack.pop()\n break # this means asteroid must be destroyed (not add to stack in else statement below)\n else:\n stack.append(a)\n \n return stack\n``` | 16 | We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0` | Say a row of asteroids is stable. What happens when a new asteroid is added on the right? |
Solution | parse-lisp-expression | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int evaluate(string expression) {\n unordered_map<string, int> map;\n int idx = 0;\n return eval(expression, idx, map);\n }\n int eval(const string& exp, int& idx, const unordered_map<string, int>& map){\n int result;\n idx++;\n int end = exp.find(\' \', idx);\n const string op = exp.substr(idx, end - idx);\n idx = end + 1;\n if(op == "add" || op == "mult"){\n const int v1 = parse_and_eval(exp, idx, map);\n const int v2 = parse_and_eval(exp, idx, map);\n result = op == "add" ? v1 + v2 : v1 * v2;\n }else{\n unordered_map<string, int> new_map = map;\n while(exp[idx] != \'(\'){\n end = idx;\n while(exp[end] != \' \' && exp[end] != \')\') ++end;\n if(exp[end] == \')\') break;\n const string var = exp.substr(idx, end - idx);\n idx = end + 1;\n const int val = parse_and_eval(exp, idx, new_map);\n new_map[var] = val;\n }\n result = parse_and_eval(exp, idx, new_map);\n }\n idx++;\n return result;\n }\n int parse_and_eval(const string& exp, int& idx, const unordered_map<string, int>& map){\n int result;\n if(exp[idx] == \'(\'){\n result = eval(exp, idx, map);\n if(exp[idx] == \' \') ++idx;\n }else{\n int end = idx;\n while(exp[end] != \' \' && exp[end] != \')\') ++end;\n if(exp[idx] == \'-\' || (exp[idx] >= \'0\' && exp[idx] <= \'9\'))\n result = stoi(exp.substr(idx, end - idx));\n else\n result = map.at(exp.substr(idx, end - idx));\n idx = exp[end] == \' \' ? end + 1 : end;\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def evaluate(self, expression: str) -> int:\n \n tokens = deque(expression.replace(\'(\',\'( \').replace(\')\',\' )\').split())\n \n def eva(tokens,env):\n \n if tokens[0] != \'(\':\n if tokens[0][0] in \'-1234567890\':\n return int(tokens.popleft())\n else:\n return env[tokens.popleft()]\n else:\n tokens.popleft()\n if tokens[0] in (\'add\', \'mult\'):\n op = tokens.popleft()\n a, b = eva(tokens, env), eva(tokens, env)\n val = a + b if op == \'add\' else a * b\n else:\n tokens.popleft()\n local = env.copy()\n while tokens[0] != \'(\' and tokens[1] != \')\':\n var = tokens.popleft()\n local[var] = eva(tokens, local)\n val = eva(tokens, local)\n tokens.popleft()\n return val\n \n return eva(tokens,{})\n```\n\n```Java []\nclass Solution {\n String expression;\n int index;\n HashMap<String,Deque<Integer>> scope; \n public int evaluate(String expression) {\n this.expression=expression;\n index=0;\n scope=new HashMap<>();\n return evaluate();\n }\n private int evaluate(){\n if(expression.charAt(index)==\'(\'){\n index++;\n char begin=expression.charAt(index);\n int ret;\n if(begin==\'l\'){\n index += 4;\n ArrayList<String> vars=new ArrayList<>();\n while(true){\n if(!Character.isLowerCase(expression.charAt(index))){\n ret=evaluate();\n break;\n }\n String var=parseVar();\n if(expression.charAt(index)==\')\'){\n ret=scope.get(var).peek();\n break;\n }\n vars.add(var);\n index++;\n int e=evaluate();\n scope.putIfAbsent(var, new LinkedList<>());\n scope.get(var).push(e);\n index++;\n }\n for (String var : vars) {\n scope.get(var).pop();\n }\n } else if(begin==\'a\') {\n index += 4;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1+v2;\n } else {\n index += 5;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1*v2;\n }\n index++;\n return ret;\n } else {\n if(Character.isLowerCase(expression.charAt(index))){\n String var=parseVar();\n return scope.get(var).peek();\n } else {\n return parseInt();\n }\n }\n }\n private int parseInt(){\n boolean negative=false;\n if(expression.charAt(index)==\'-\'){\n negative=true;\n index++;\n }\n int ret=0;\n while(Character.isDigit(expression.charAt(index))){\n ret*=10;\n ret+=expression.charAt(index)-\'0\';\n index++;\n }\n if(negative) return -ret;\n return ret;\n }\n private String parseVar(){\n StringBuilder sb=new StringBuilder();\n char c=expression.charAt(index);\n while(c!=\' \' && c!=\')\'){\n sb.append(c);\n c=expression.charAt(++index);\n }\n return sb.toString();\n }\n}\n```\n | 1 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Solution | parse-lisp-expression | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int evaluate(string expression) {\n unordered_map<string, int> map;\n int idx = 0;\n return eval(expression, idx, map);\n }\n int eval(const string& exp, int& idx, const unordered_map<string, int>& map){\n int result;\n idx++;\n int end = exp.find(\' \', idx);\n const string op = exp.substr(idx, end - idx);\n idx = end + 1;\n if(op == "add" || op == "mult"){\n const int v1 = parse_and_eval(exp, idx, map);\n const int v2 = parse_and_eval(exp, idx, map);\n result = op == "add" ? v1 + v2 : v1 * v2;\n }else{\n unordered_map<string, int> new_map = map;\n while(exp[idx] != \'(\'){\n end = idx;\n while(exp[end] != \' \' && exp[end] != \')\') ++end;\n if(exp[end] == \')\') break;\n const string var = exp.substr(idx, end - idx);\n idx = end + 1;\n const int val = parse_and_eval(exp, idx, new_map);\n new_map[var] = val;\n }\n result = parse_and_eval(exp, idx, new_map);\n }\n idx++;\n return result;\n }\n int parse_and_eval(const string& exp, int& idx, const unordered_map<string, int>& map){\n int result;\n if(exp[idx] == \'(\'){\n result = eval(exp, idx, map);\n if(exp[idx] == \' \') ++idx;\n }else{\n int end = idx;\n while(exp[end] != \' \' && exp[end] != \')\') ++end;\n if(exp[idx] == \'-\' || (exp[idx] >= \'0\' && exp[idx] <= \'9\'))\n result = stoi(exp.substr(idx, end - idx));\n else\n result = map.at(exp.substr(idx, end - idx));\n idx = exp[end] == \' \' ? end + 1 : end;\n }\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def evaluate(self, expression: str) -> int:\n \n tokens = deque(expression.replace(\'(\',\'( \').replace(\')\',\' )\').split())\n \n def eva(tokens,env):\n \n if tokens[0] != \'(\':\n if tokens[0][0] in \'-1234567890\':\n return int(tokens.popleft())\n else:\n return env[tokens.popleft()]\n else:\n tokens.popleft()\n if tokens[0] in (\'add\', \'mult\'):\n op = tokens.popleft()\n a, b = eva(tokens, env), eva(tokens, env)\n val = a + b if op == \'add\' else a * b\n else:\n tokens.popleft()\n local = env.copy()\n while tokens[0] != \'(\' and tokens[1] != \')\':\n var = tokens.popleft()\n local[var] = eva(tokens, local)\n val = eva(tokens, local)\n tokens.popleft()\n return val\n \n return eva(tokens,{})\n```\n\n```Java []\nclass Solution {\n String expression;\n int index;\n HashMap<String,Deque<Integer>> scope; \n public int evaluate(String expression) {\n this.expression=expression;\n index=0;\n scope=new HashMap<>();\n return evaluate();\n }\n private int evaluate(){\n if(expression.charAt(index)==\'(\'){\n index++;\n char begin=expression.charAt(index);\n int ret;\n if(begin==\'l\'){\n index += 4;\n ArrayList<String> vars=new ArrayList<>();\n while(true){\n if(!Character.isLowerCase(expression.charAt(index))){\n ret=evaluate();\n break;\n }\n String var=parseVar();\n if(expression.charAt(index)==\')\'){\n ret=scope.get(var).peek();\n break;\n }\n vars.add(var);\n index++;\n int e=evaluate();\n scope.putIfAbsent(var, new LinkedList<>());\n scope.get(var).push(e);\n index++;\n }\n for (String var : vars) {\n scope.get(var).pop();\n }\n } else if(begin==\'a\') {\n index += 4;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1+v2;\n } else {\n index += 5;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1*v2;\n }\n index++;\n return ret;\n } else {\n if(Character.isLowerCase(expression.charAt(index))){\n String var=parseVar();\n return scope.get(var).peek();\n } else {\n return parseInt();\n }\n }\n }\n private int parseInt(){\n boolean negative=false;\n if(expression.charAt(index)==\'-\'){\n negative=true;\n index++;\n }\n int ret=0;\n while(Character.isDigit(expression.charAt(index))){\n ret*=10;\n ret+=expression.charAt(index)-\'0\';\n index++;\n }\n if(negative) return -ret;\n return ret;\n }\n private String parseVar(){\n StringBuilder sb=new StringBuilder();\n char c=expression.charAt(index);\n while(c!=\' \' && c!=\')\'){\n sb.append(c);\n c=expression.charAt(++index);\n }\n return sb.toString();\n }\n}\n```\n | 1 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
736: Solution with step by step explanation | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution uses a recursive approach to evaluate the expression. Here\'s how it\'s structured:\n\nParsing the expression: Split the given expression into its constituent parts or tokens.\nEvaluating the expression: Recursively process the expression based on the type of operation (add, multiply, or let).\n\nObjective: Split the string e into individual tokens.\nHow: By checking the number of open and close parentheses. We only split on spaces that are outside of any nested expression.\n\n```\ndef parse(e: str) -> list[str]:\n tokens, s, parenthesis = [], \'\', 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n \n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if s: \n tokens.append(s)\n \n return tokens\n```\nObjective: Evaluate the string expression e given its current variable scope prevScope.\nHow:\nIf e is a number or a single variable, return its value.\nIf e is an "add" or "multiply" operation, recursively evaluate its operands.\nIf e is a "let" operation, update the current variable scope and evaluate the last expression in its body.\n\n```\ndef evaluate_expression(e: str, prevScope: dict) -> int:\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n if e in prevScope:\n return prevScope[e]\n\n scope = prevScope.copy()\n nextExpression = e[e.index(\' \') + 1:-1]\n tokens = parse(nextExpression)\n\n if e[1] == \'a\':\n return evaluate_expression(tokens[0], scope) + evaluate_expression(tokens[1], scope)\n if e[1] == \'m\':\n return evaluate_expression(tokens[0], scope) * evaluate_expression(tokens[1], scope)\n\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate_expression(tokens[i + 1], scope)\n\n return evaluate_expression(tokens[-1], scope)\n```\nKick off the recursive evaluation with an empty scope.\n```\nreturn evaluate_expression(expression, {})\n```\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n\n def parse(e: str) -> list[str]:\n tokens, s, parenthesis = [], \'\', 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n \n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if s: \n tokens.append(s)\n \n return tokens\n\n def evaluate_expression(e: str, prevScope: dict) -> int:\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n if e in prevScope:\n return prevScope[e]\n\n scope = prevScope.copy()\n nextExpression = e[e.index(\' \') + 1:-1]\n tokens = parse(nextExpression)\n\n if e[1] == \'a\':\n return evaluate_expression(tokens[0], scope) + evaluate_expression(tokens[1], scope)\n if e[1] == \'m\':\n return evaluate_expression(tokens[0], scope) * evaluate_expression(tokens[1], scope)\n\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate_expression(tokens[i + 1], scope)\n\n return evaluate_expression(tokens[-1], scope)\n\n return evaluate_expression(expression, {})\n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
736: Solution with step by step explanation | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution uses a recursive approach to evaluate the expression. Here\'s how it\'s structured:\n\nParsing the expression: Split the given expression into its constituent parts or tokens.\nEvaluating the expression: Recursively process the expression based on the type of operation (add, multiply, or let).\n\nObjective: Split the string e into individual tokens.\nHow: By checking the number of open and close parentheses. We only split on spaces that are outside of any nested expression.\n\n```\ndef parse(e: str) -> list[str]:\n tokens, s, parenthesis = [], \'\', 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n \n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if s: \n tokens.append(s)\n \n return tokens\n```\nObjective: Evaluate the string expression e given its current variable scope prevScope.\nHow:\nIf e is a number or a single variable, return its value.\nIf e is an "add" or "multiply" operation, recursively evaluate its operands.\nIf e is a "let" operation, update the current variable scope and evaluate the last expression in its body.\n\n```\ndef evaluate_expression(e: str, prevScope: dict) -> int:\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n if e in prevScope:\n return prevScope[e]\n\n scope = prevScope.copy()\n nextExpression = e[e.index(\' \') + 1:-1]\n tokens = parse(nextExpression)\n\n if e[1] == \'a\':\n return evaluate_expression(tokens[0], scope) + evaluate_expression(tokens[1], scope)\n if e[1] == \'m\':\n return evaluate_expression(tokens[0], scope) * evaluate_expression(tokens[1], scope)\n\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate_expression(tokens[i + 1], scope)\n\n return evaluate_expression(tokens[-1], scope)\n```\nKick off the recursive evaluation with an empty scope.\n```\nreturn evaluate_expression(expression, {})\n```\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n\n def parse(e: str) -> list[str]:\n tokens, s, parenthesis = [], \'\', 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n \n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if s: \n tokens.append(s)\n \n return tokens\n\n def evaluate_expression(e: str, prevScope: dict) -> int:\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n if e in prevScope:\n return prevScope[e]\n\n scope = prevScope.copy()\n nextExpression = e[e.index(\' \') + 1:-1]\n tokens = parse(nextExpression)\n\n if e[1] == \'a\':\n return evaluate_expression(tokens[0], scope) + evaluate_expression(tokens[1], scope)\n if e[1] == \'m\':\n return evaluate_expression(tokens[0], scope) * evaluate_expression(tokens[1], scope)\n\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate_expression(tokens[i + 1], scope)\n\n return evaluate_expression(tokens[-1], scope)\n\n return evaluate_expression(expression, {})\n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Python (Simple Stack) | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression):\n tokens, stack, dict1 = [""], [], defaultdict(int)\n\n def evaluate(tokens):\n if tokens[0] in ["add","mult"]:\n n1 = int(dict1[tokens[1]]) if tokens[1] in dict1 else int(tokens[1])\n n2 = int(dict1[tokens[2]]) if tokens[2] in dict1 else int(tokens[2])\n return str(n1+n2) if tokens[0] == "add" else str(n1*n2)\n else:\n for i in range(1,len(tokens)-2,2):\n dict1[tokens[i]] = dict1.get(tokens[i+1],tokens[i+1])\n return dict1[tokens[-1]] if tokens[-1] in dict1 else tokens[-1]\n\n for c in expression:\n if c == "(":\n if tokens[0] == "let": evaluate(tokens)\n stack.append((tokens,dict(dict1)))\n tokens = [""]\n elif c == ")":\n val = evaluate(tokens)\n tokens, dict1 = stack.pop()\n tokens[-1] += val\n elif c == " ":\n tokens.append("")\n else:\n tokens[-1] += c\n\n return int(tokens[0])\n\n\n\n\n \n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Python (Simple Stack) | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression):\n tokens, stack, dict1 = [""], [], defaultdict(int)\n\n def evaluate(tokens):\n if tokens[0] in ["add","mult"]:\n n1 = int(dict1[tokens[1]]) if tokens[1] in dict1 else int(tokens[1])\n n2 = int(dict1[tokens[2]]) if tokens[2] in dict1 else int(tokens[2])\n return str(n1+n2) if tokens[0] == "add" else str(n1*n2)\n else:\n for i in range(1,len(tokens)-2,2):\n dict1[tokens[i]] = dict1.get(tokens[i+1],tokens[i+1])\n return dict1[tokens[-1]] if tokens[-1] in dict1 else tokens[-1]\n\n for c in expression:\n if c == "(":\n if tokens[0] == "let": evaluate(tokens)\n stack.append((tokens,dict(dict1)))\n tokens = [""]\n elif c == ")":\n val = evaluate(tokens)\n tokens, dict1 = stack.pop()\n tokens[-1] += val\n elif c == " ":\n tokens.append("")\n else:\n tokens[-1] += c\n\n return int(tokens[0])\n\n\n\n\n \n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n \n \n \n \n \n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
solve it with python | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n def evaluate(e: str, prevScope: dict) -> int:\n # Base case: if the expression starts with a digit or a negative sign, it\'s a number\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n \n # Check if the expression has been evaluated previously and stored in the previous scope\n if e in prevScope:\n return prevScope[e]\n\n # Create a new scope based on the previous scope\n scope = prevScope.copy()\n \n # Extract the next expression by removing the outermost parentheses\n nextExpression = e[e.index(\' \') + 1:-1]\n \n # Split the expression into tokens\n tokens = parse(nextExpression)\n\n # Evaluate addition\n if e[1] == \'a\':\n return evaluate(tokens[0], scope) + evaluate(tokens[1], scope)\n \n # Evaluate multiplication\n if e[1] == \'m\':\n return evaluate(tokens[0], scope) * evaluate(tokens[1], scope)\n\n # Process assignments\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate(tokens[i + 1], scope)\n\n # Evaluate the last expression in the tokens using the updated scope\n return evaluate(tokens[-1], scope)\n\n def parse(e: str):\n tokens = []\n s = \'\'\n parenthesis = 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if len(s) > 0:\n tokens.append(s)\n return tokens\n\n # Start evaluating the expression with an empty scope\n return evaluate(expression, {})\n\n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
solve it with python | parse-lisp-expression | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n def evaluate(e: str, prevScope: dict) -> int:\n # Base case: if the expression starts with a digit or a negative sign, it\'s a number\n if e[0].isdigit() or e[0] == \'-\':\n return int(e)\n \n # Check if the expression has been evaluated previously and stored in the previous scope\n if e in prevScope:\n return prevScope[e]\n\n # Create a new scope based on the previous scope\n scope = prevScope.copy()\n \n # Extract the next expression by removing the outermost parentheses\n nextExpression = e[e.index(\' \') + 1:-1]\n \n # Split the expression into tokens\n tokens = parse(nextExpression)\n\n # Evaluate addition\n if e[1] == \'a\':\n return evaluate(tokens[0], scope) + evaluate(tokens[1], scope)\n \n # Evaluate multiplication\n if e[1] == \'m\':\n return evaluate(tokens[0], scope) * evaluate(tokens[1], scope)\n\n # Process assignments\n for i in range(0, len(tokens) - 2, 2):\n scope[tokens[i]] = evaluate(tokens[i + 1], scope)\n\n # Evaluate the last expression in the tokens using the updated scope\n return evaluate(tokens[-1], scope)\n\n def parse(e: str):\n tokens = []\n s = \'\'\n parenthesis = 0\n\n for c in e:\n if c == \'(\':\n parenthesis += 1\n elif c == \')\':\n parenthesis -= 1\n if parenthesis == 0 and c == \' \':\n tokens.append(s)\n s = \'\'\n else:\n s += c\n\n if len(s) > 0:\n tokens.append(s)\n return tokens\n\n # Start evaluating the expression with an empty scope\n return evaluate(expression, {})\n\n``` | 0 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Python3 Solution | parse-lisp-expression | 0 | 1 | ```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n stack = []\n parenEnd = {}\n \n # Get the end parenthesis location \n for idx, ch in enumerate(expression):\n if ch == \'(\':\n stack.append(idx)\n if ch == \')\':\n parenEnd[stack.pop()] = idx\n\n # Parses the expression into a list, each new sublist is a set of parenthesis\n # Example: \n # Input: "(let x 2 (mult x (let x 3 y 4 (add x y))))"\n # Output: [\'let\', \'x\', \'2\', [\'mult\', \'x\', [\'let\', \'x\', \'3\', \'y\', \'4\', [\'add\', \'x\', \'y\']]]]\n def parse(lo, hi):\n arr = []\n word = []\n\n i = lo\n while i < hi:\n if expression[i] == \'(\':\n arr.append(parse(i + 1, parenEnd[i]))\n i = parenEnd[i]\n elif expression[i] == \' \' or expression[i] == \')\' and word != []:\n if \'\'.join(word) != \'\':\n arr.append(\'\'.join(word))\n word = []\n i += 1\n elif expression[i] != \')\':\n word.append(expression[i])\n i += 1\n else:\n i += 1\n\n\n if word != []:\n arr.append(\'\'.join(word))\n\n return arr\n\n # Change string expression into the list expression\n expressionList = parse(1, len(expression) - 1)\n\n # Eval expression with starting scope (variables)\n return self.genEval(expressionList, {})\n \n def genEval(self, expression, scope):\n if type(expression) != list:\n # If expression is just a variable or int\n try:\n return int(expression)\n except:\n return scope[expression]\n else:\n if expression[0] == \'let\':\n # Remove "let" from expression list\n expression = expression[1:]\n \n # This loop updates the scope (variables)\n while len(expression) > 2:\n scope = self.letEval(expression, scope.copy())\n expression = expression[2:]\n \n # Return the last value\n return self.genEval(expression[0], scope.copy())\n \n if expression[0] == \'add\':\n return self.addEval(expression, scope.copy())\n \n if expression[0] == \'mult\':\n return self.multEval(expression, scope.copy())\n\n\n \n def letEval(self, expression, scope):\n scope[expression[0]] = self.genEval(expression[1], scope)\n return scope\n \n def addEval(self, expression, scope):\n return self.genEval(expression[1], scope) + self.genEval(expression[2], scope)\n \n def multEval(self, expression, scope):\n return self.genEval(expression[1], scope) * self.genEval(expression[2], scope)\n\n``` | 3 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Python3 Solution | parse-lisp-expression | 0 | 1 | ```\nclass Solution:\n def evaluate(self, expression: str) -> int:\n stack = []\n parenEnd = {}\n \n # Get the end parenthesis location \n for idx, ch in enumerate(expression):\n if ch == \'(\':\n stack.append(idx)\n if ch == \')\':\n parenEnd[stack.pop()] = idx\n\n # Parses the expression into a list, each new sublist is a set of parenthesis\n # Example: \n # Input: "(let x 2 (mult x (let x 3 y 4 (add x y))))"\n # Output: [\'let\', \'x\', \'2\', [\'mult\', \'x\', [\'let\', \'x\', \'3\', \'y\', \'4\', [\'add\', \'x\', \'y\']]]]\n def parse(lo, hi):\n arr = []\n word = []\n\n i = lo\n while i < hi:\n if expression[i] == \'(\':\n arr.append(parse(i + 1, parenEnd[i]))\n i = parenEnd[i]\n elif expression[i] == \' \' or expression[i] == \')\' and word != []:\n if \'\'.join(word) != \'\':\n arr.append(\'\'.join(word))\n word = []\n i += 1\n elif expression[i] != \')\':\n word.append(expression[i])\n i += 1\n else:\n i += 1\n\n\n if word != []:\n arr.append(\'\'.join(word))\n\n return arr\n\n # Change string expression into the list expression\n expressionList = parse(1, len(expression) - 1)\n\n # Eval expression with starting scope (variables)\n return self.genEval(expressionList, {})\n \n def genEval(self, expression, scope):\n if type(expression) != list:\n # If expression is just a variable or int\n try:\n return int(expression)\n except:\n return scope[expression]\n else:\n if expression[0] == \'let\':\n # Remove "let" from expression list\n expression = expression[1:]\n \n # This loop updates the scope (variables)\n while len(expression) > 2:\n scope = self.letEval(expression, scope.copy())\n expression = expression[2:]\n \n # Return the last value\n return self.genEval(expression[0], scope.copy())\n \n if expression[0] == \'add\':\n return self.addEval(expression, scope.copy())\n \n if expression[0] == \'mult\':\n return self.multEval(expression, scope.copy())\n\n\n \n def letEval(self, expression, scope):\n scope[expression[0]] = self.genEval(expression[1], scope)\n return scope\n \n def addEval(self, expression, scope):\n return self.genEval(expression[1], scope) + self.genEval(expression[2], scope)\n \n def multEval(self, expression, scope):\n return self.genEval(expression[1], scope) * self.genEval(expression[2], scope)\n\n``` | 3 | You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
* An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
* (An integer could be positive or negative.)
* A let expression takes the form `"(let v1 e1 v2 e2 ... vn en expr) "`, where let is always the string `"let "`, then there are one or more pairs of alternating variables and expressions, meaning that the first variable `v1` is assigned the value of the expression `e1`, the second variable `v2` is assigned the value of the expression `e2`, and so on sequentially; and then the value of this let expression is the value of the expression `expr`.
* An add expression takes the form `"(add e1 e2) "` where add is always the string `"add "`, there are always two expressions `e1`, `e2` and the result is the addition of the evaluation of `e1` and the evaluation of `e2`.
* A mult expression takes the form `"(mult e1 e2) "` where mult is always the string `"mult "`, there are always two expressions `e1`, `e2` and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
* For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names `"add "`, `"let "`, and `"mult "` are protected and will never be used as variable names.
* Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
**Example 1:**
**Input:** expression = "(let x 2 (mult x (let x 3 y 4 (add x y)))) "
**Output:** 14
**Explanation:** In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.
**Example 2:**
**Input:** expression = "(let x 3 x 2 x) "
**Output:** 2
**Explanation:** Assignment in let statements is processed sequentially.
**Example 3:**
**Input:** expression = "(let x 1 y 2 x (add x y) (add x y)) "
**Output:** 5
**Explanation:** The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.
**Constraints:**
* `1 <= expression.length <= 2000`
* There are no leading or trailing spaces in `expression`.
* All tokens are separated by a single space in `expression`.
* The answer and all intermediate calculations of that answer are guaranteed to fit in a **32-bit** integer.
* The expression is guaranteed to be legal and evaluate to an integer. | * If the expression starts with a digit or '-', it's an integer: return it.
* If the expression starts with a letter, it's a variable. Recall it by checking the current scope in reverse order.
* Otherwise, group the tokens (variables or expressions) within this expression by counting the "balance" `bal` of the occurrences of `'('` minus the number of occurrences of `')'`. When the balance is zero, we have ended a token. For example, `(add 1 (add 2 3))` should have tokens `'1'` and `'(add 2 3)'`.
* For add and mult expressions, evaluate each token and return the addition or multiplication of them.
* For let expressions, evaluate each expression sequentially and assign it to the variable in the current scope, then return the evaluation of the final expression. |
Solution | monotone-increasing-digits | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n string s = to_string(n);\n while(1){\n bool flag = false;\n for(int i = 1; i < s.length(); i++){\n if(s[i] >= s[i-1]) continue;\n else{\n s[i-1]--;\n while(i != s.length()){\n s[i] = \'9\';\n i++;\n }\n flag = true;\n }\n }\n if(!flag) break;\n }\n return stoi(s);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n strn = list(str(n))\n flag = len(strn)\n\n for i in range(flag-1,0,-1):\n if strn[i] < strn[i-1]:\n flag = i\n strn[i-1] = str(int(strn[i-1]) -1)\n \n for i in range(flag, len(strn)):\n strn[i] = \'9\'\n\n return int("".join(strn))\n```\n\n```Java []\nclass Solution {\n public int monotoneIncreasingDigits(int n) {\n int[] digits = new int[10];\n int num = n;\n int index = 0;\n\n while(n > 0){\n digits[index++] = n % 10;\n n /= 10;\n }\n int start = 0, len = index;\n int end = len - 1;\n while(start < end){\n int d = digits[start];\n digits[start++] = digits[end];\n digits[end--] = d;\n }\n int i = 1;\n for(;i < len;i++){\n if(digits[i - 1] > digits[i]) break;\n }\n if(i == len) return num;\n i--;\n while(i > 0 && digits[i - 1] == digits[i]){\n i--;\n }\n digits[i++]--;\n while(i < len) digits[i++] = 9;\n int ans = 0;\n for( i = 0;i < len;i++) ans = ans * 10 + digits[i];\n return ans;\n }\n}\n```\n | 1 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
Python Solution Using Backtracking || Easy to Understand | monotone-increasing-digits | 0 | 1 | ```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n\t\t# max size of string\n self.maxlen = len(str(n))\n\t\t# maximum ans store here\n self.maxans = 0\n self.find(str(n))\n return self.maxans\n \n def find(self,num,idx=0,curnum=\'\',pb=None):\n\t\t# idx is size counter of current number (curnum) pb represents previous bit/number at idx position\n\t\t\'\'\'\n\t\t\tThis Approach uses leading zeros in number that means\n\t\t\tif we are looking for ans for value 10 it will be 09 instead of 9\n\t\t\tbut int(\'09\') = 9 so we receive our output. hence length of final\n\t\t\toutput will always be equal to length of string i.e. self.maxlen\n\t\t\t\n\t\t\twe\'ll start creating number from backside for example if we are looking for\n\t\t\tn = 1234 first bit in first iteration will be 1 then we\'ll place second bit in the range\n\t\t\tof 1-9 and third bit in the range of 2-9.\n\t\t\t\n\t\t\tAs soon as we receive one ans that will be the largest one we stop the recursion and returns\n\t\t\tthe answer\n\t\t\'\'\'\n if idx == self.maxlen:\n self.maxans = max(self.maxans,int(curnum))\n\t\t# if we have received our ans we will stop backtracking immediatly\n if idx >= self.maxlen or self.maxans:\n return\n\t\t# if first time call\n if not pb:\n for i in range(int(num[idx]),-1,-1):\n self.find(num,idx+1,curnum+str(i),num[idx])\n\t\t# otherwise\n else:\n for i in range(9,int(pb)-1,-1):\n if int(curnum+str(i))<=int(num[:idx+1]):\n self.find(num,idx+1,curnum+str(i),num[idx])\n``` | 1 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
738: Solution with step by step explanation | monotone-increasing-digits | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ndigits = list(str(n))\n```\nWe first convert the integer n to its string representation and then create a list of its characters.\nThis step allows us to easily modify individual digits if needed.\n\n```\nn = len(digits)\nidx_to_modify = n\n```\n\nn now represents the length of the digits list.\nidx_to_modify will store the position where the first monotonicity violation occurs. Initially, it\'s set to the length of the digits list, assuming the number is already monotonic.\n\n```\nfor i in range(n - 1, 0, -1):\n if digits[i] < digits[i - 1]:\n idx_to_modify = i\n digits[i - 1] = str(int(digits[i - 1]) - 1)\n```\n\nStarting from the end of the list, we move towards the beginning.\nWe compare each digit with its preceding digit.\nThe first time we find a digit that\'s smaller than its predecessor (digits[i] < digits[i - 1]), we\'ve found a monotonicity violation.\nAt this point, we reduce the preceding digit by 1 (digits[i - 1] -= 1) to make it smaller and set the idx_to_modify to the current index i.\n\n```\nfor i in range(idx_to_modify, n):\n digits[i] = \'9\'\n```\n\nTo get the largest possible number after modifying a digit, we need to make all digits to its right as \'9\'.\nThis loop sets every digit after the idx_to_modify to \'9\'.\n\n```\nreturn int("".join(digits))\n```\n\nWe join the modified list of characters to form the string representation of the new number and then convert it back to an integer.\n\n# Complexity\n- Time complexity:\nO(log n)\n\n- Space complexity:\nO(log n)\n\n# Code\n```\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n digits = list(str(n))\n n = len(digits)\n idx_to_modify = n \n\n for i in range(n - 1, 0, -1):\n if digits[i] < digits[i - 1]:\n idx_to_modify = i\n digits[i - 1] = str(int(digits[i - 1]) - 1)\n \n for i in range(idx_to_modify, n):\n digits[i] = \'9\'\n \n return int("".join(digits))\n\n``` | 1 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
Log(n) Time Complexity? | Beats 99% ! | Intuitive Solution ?! | monotone-increasing-digits | 0 | 1 | ## First, the Intuition ...\nFor any arbitrary integer *n*, if its digits are in non-decreasing order from left to right, then it satisfies the monotonic increasing condition. \n\nHowever, if we encounter a digit that\'s smaller than the preceding one, we can decrement the previous digit by one and **replace all digits to its right with \'9\'** to ensure we obtain the **largest** possible monotonic increasing number. \n\nFor example, using the number $$322$$:\n\nOn our first iteration, we can see that it violates the monotonic increasing condition. We reduce the first $$3$$ to $$2$$ and replace the digits to its right with $$9$$, we get $$299$$, which satisifes the monotonic increasing condition.\n\nFor another example, apply this intuition with $$8612$$\n\n## The Approach\n1. Convert the number into a list of string digits.\n2. Traverse the digits from the rightmost to the left.\n3. If a digit is discovered to be smaller than the one before it, decrease the previous digit by one and change all the digits to its right to \'9\'.\n4. Continue this process until the beginning of the list is reached or until the entire list is in a non-decreasing order.\n5. Convert the list of digits back into an integer and return the result.\n\n## The Complexity\n**Time complexity**: $$\\Theta\n(\\log ^ 2(n))$$\nGiven a number with $$d$$ digits, where $$( d \\approx \\log_{10} n )$$, our algorithm inspects digits from right to left, potentially updating all digits to its right. This results in:\n\n$$[ 1 + 2 + 3 + \\dots + d ]$$\n\nUsing the formula for the sum of the first $$n$$ positive integers:\n\n$$[ 1 + 2 + 3 + \\dots + d ] = \\frac{1}{2}(d^2\\;+\\;d) $$\n\nGiven $$ d \\approx \\log n $$, the time complexity becomes:\n\n$$ \\Theta(\\log^2 (n)) $$\n\n> For the average case, the time complexity remains $$O\n(\\log ^ 2(n))$$. \nHowever, for the best case, the time complexity reduces to $$\\Omega\n(\\log (n))$$.\n\n \n**Space complexity**: $$\\Theta\n(\\log (n))$$\n We represent the number as a list of its digits, which will have a length proportional to $$ \\log_{10} n $$. \n\n## Lastly, the Code.\n```\nclass Solution:\n def monotoneIncreasingDigits(self, num: int) -> int:\n nums = list(str(num)); i = len(nums) - 1\n while i > 0:\n if nums[i] < nums[i - 1]:\n nums[i - 1] = str(int(nums[i - 1]) - 1)\n nums[i:] = [\'9\'] * (len(nums) - i)\n i = len(nums) - 1\n else: \n i = i - 1\n\n return int(\'\'.join(nums))\n``` | 0 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
[Python3] Good enough | monotone-increasing-digits | 0 | 1 | ``` Python3 []\nclass Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n digits = []\n final = []\n\n while n:\n digits.append(n%10)\n n //= 10\n \n for i in range(len(digits)):\n if digits[i]<=0 or (i!=len(digits)-1 and digits[i]<digits[i+1]):\n if i!=len(digits)-1:\n final = [9]*(len(final)+1)\n digits[i+1] -= 1\n else:\n final.append(digits[i])\n \n final = final[::-1]\n\n return int(\'\'.join([str(x) for x in final])) if final else 0 \n``` | 0 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
easy||digit dp||intutive aproach | monotone-increasing-digits | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def digitdp(self,idx,s,prevdigit,val,tight,iszero):\n if idx>=len(s):\n return val\n limit=int(s[idx])\n if not tight:\n limit=9\n take=0\n\n for currentdigit in range(limit+1):\n nexttight=tight and currentdigit==limit\n nextzero=iszero and currentdigit==0\n if nextzero or currentdigit>=prevdigit:\n take=max(take,self.digitdp(idx+1,s,currentdigit,val*10+currentdigit,nexttight,nextzero))\n return take\n def monotoneIncreasingDigits(self, n: int) -> int:\n return self.digitdp(0,str(n),0,0,True,True)\n\n \n``` | 0 | An integer has **monotone increasing digits** if and only if each pair of adjacent digits `x` and `y` satisfy `x <= y`.
Given an integer `n`, return _the largest number that is less than or equal to_ `n` _with **monotone increasing digits**_.
**Example 1:**
**Input:** n = 10
**Output:** 9
**Example 2:**
**Input:** n = 1234
**Output:** 1234
**Example 3:**
**Input:** n = 332
**Output:** 299
**Constraints:**
* `0 <= n <= 109` | Build the answer digit by digit, adding the largest possible one that would make the number still less than or equal to N. |
Python Code (Stack approach) | O(n) | daily-temperatures | 0 | 1 | # Intuition\nThe problem requires finding the number of days you would have to wait until a warmer temperature. This suggests using a stack to keep track of temperatures and their indices.\n\n# Approach\n1. Initialize an empty stack to store temperatures and their corresponding indices.\n\n2. Initialize a list ans of the same length as the input temperatures to store the number of days to wait for each temperature. Initialize all values in ans to 0.\n\n3. Iterate through the temperatures list using enumerate. For each temperature t at index i:\n - While the stack is not empty and the current temperature t is greater than the temperature on top of the stack, pop temperatures from the stack and update the corresponding ans values with the number of days to wait.\n - Push the current temperature t and its index i onto the stack.\n \n4. After processing all temperatures, the ans list contains the number of days to wait for each temperature.\n\n5. Return the ans list as the result.\n\n# Complexity\n- Time complexity: O(N), where N is the number of temperatures. Each temperature is pushed onto the stack and popped from the stack at most once.\n\n- Space complexity: O(N) for the stack and the ans list, as they can both have a maximum of N elements.\n\n# Code\n```\nclass Solution:\n def dailyTemperatures(self, temperatures: List[int]) -> List[int]:\n ans=[0]*len(temperatures)\n stack=[]\n\n for i , t in enumerate(temperatures):\n while stack and t > stack[-1][0]:\n tempt ,tempi= stack.pop()\n ans[tempi] = i - tempi\n stack.append([t,i])\n return ans \n\n \n```\n\n# Please upvote the solution if you understood it.\n\n | 6 | Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100` | If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next. |
740: Beats 97.58%, Solution with step by step explanation | delete-and-earn | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nfrom collections import defaultdict\n\nclass Solution:\n def deleteAndEarn(self, nums: list[int]) -> int:\n # Step 1: Convert nums to a dictionary of points\n points = defaultdict(int)\n for num in nums:\n points[num] += num\n # At the end of this loop, \'points\' dictionary will contain each unique number \n # from \'nums\' as the key and the total sum of that number as the value.\n\n # Step 2: Sort the keys of the dictionary\n sorted_keys = sorted(points.keys())\n # This ensures that we process the numbers in ascending order.\n\n # Step 3: Dynamic Programming to decide whether to take or skip a number\n prev_key = None\n take, skip = 0, 0\n for key in sorted_keys:\n # If the current key is adjacent to the previous key (difference is 1)\n if prev_key is not None and key - prev_key == 1:\n # Decide between taking the current number or skipping it.\n take, skip = skip + points[key], max(take, skip)\n else:\n # If the current key is NOT adjacent to the previous key,\n # we can safely add the points of the current key to either \'take\' or \'skip\'.\n take, skip = max(take, skip) + points[key], max(take, skip)\n\n prev_key = key\n # The maximum of \'take\' and \'skip\' will give the maximum points we can earn.\n\n return max(take, skip)\n```\n\n# Complexity\n- Time complexity:\nO(n * log(n))\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def deleteAndEarn(self, nums: list[int]) -> int:\n points = defaultdict(int)\n for num in nums:\n points[num] += num\n \n sorted_keys = sorted(points.keys())\n \n prev_key = None\n take, skip = 0, 0\n for key in sorted_keys:\n if prev_key is not None and key - prev_key == 1:\n take, skip = skip + points[key], max(take, skip)\n else:\n take, skip = max(take, skip) + points[key], max(take, skip)\n prev_key = key\n\n return max(take, skip)\n\n``` | 1 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
Dynamic Programming : Just Duplicates Together -- House Robber Question | delete-and-earn | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n list1=[0]*10001\n for i in nums:\n list1[i]+=i\n rob1,rob2=0,0\n for n in list1:\n rob1,rob2,=rob2,max(rob1+n,rob2)\n return rob2\n #please upvote me it would encourage me alot\n\n``` | 23 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
Python Solution O(n) similar to House Robber Faster than 89.94% solutions | delete-and-earn | 0 | 1 | # Please upvote if you liked or it helped. feel free to comments suggestions or any other change and update in code. **\n\n# EXPLAINDED SOLUTION \n\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n# createed a dic to store value of a number i.e the dic[n] = n*(number of times it occurs)\n dic = defaultdict(int)\n for n in nums:\n dic[n] += n\n# made a list of unique num in nums, OR -> made a list so we can use it as House Robber \n newList = list(set(nums))\n newList.sort()\n \n# point list contains all the indexes in newList where the difference between any two consicutive num is greater than 1.\n# newList = [2,3,4,6,7,8,11,12] then -> point = [3,6] + ( also append len(newList)) to process the last 11,12 as we did in House Robber.\n# points = [3,6,8]\n point = []\n N = len(newList)\n for i in range(1,N):\n if newList[i] - newList[i-1] > 1:\n point.append(i)\n if len(point)==0 or point[-1] != N:\n point.append(N)\n\n# similar to House Robber. We try to get maximum for each sub array.\n# [2,3,4] , [6,7,8] , [11,12] ( prev = 0 )\n\n earning,prev = 0,0 # earning = 0, prev = 0 ( index starting)\n for indx in point: # points = # points = [3,6,8].. for each index we want to calculate max contiribution of it subarray... [0,3], [3,6], [6,8]\n dp = [-10**20,-10**20]\n for i,n in enumerate(newList[prev:indx]): # lists -> [2,3,4] , [6,7,8] , [11,12] \n if i == 0: # BASE CONDITION \n dp[0] = max(dp[0], dic[n]) \n continue\n if i == 1: # BASE CONDITION \n dp[1] = max(dp[1], dic[n])\n continue\n # UPDATING VALUES\n temp = dp[1]\n dp[1] = max(dic[n], dp[0]+dic[n],dp[1])\n dp[0] = max(temp,dp[0]) \n earning += max(dp) # updating earings\n prev = indx #prev updated to 3,6,8 after subarrays\n \n return earning # FINAL ANSWER\n \n```\n\n# CLEAN CODE - SOLUTION \n\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n\t# c\n dic = defaultdict(int)\n for n in nums:\n dic[n] += n\n \n newList = list(set(nums))\n newList.sort()\n \n point = []\n N = len(newList)\n for i in range(1,N):\n if newList[i] - newList[i-1] > 1:\n point.append(i)\n if len(point)==0 or point[-1] != N:\n point.append(N)\n \n earning,prev = 0,0\n for indx in point:\n dp = [-10**20,-10**20]\n for i,n in enumerate(newList[prev:indx]):\n if i == 0:\n dp[0] = max(dp[0], dic[n])\n continue\n if i == 1:\n dp[1] = max(dp[1], dic[n])\n continue\n temp = dp[1]\n dp[1] = max(dic[n], dp[0]+dic[n],dp[1])\n dp[0] = max(temp,dp[0])\n earning += max(dp)\n prev = indx\n \n return earning\n \n```\n\t\n# **Please upvote if you liked or it helped. feel free to comments suggestions or any other change and update in code.** | 4 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
Solution | delete-and-earn | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int deleteAndEarn(vector<int>& nums) {\n int n=nums.size();\n int maxi=0;\n for(int i=0;i<n;i++){\n maxi=max(maxi,nums[i]);\n }\n vector<int> hash(maxi+1,0);\n vector<int> dp(maxi+2);\n for(int i=0;i<n;i++){\n hash[nums[i]]++;\n }\n dp[0]=0;\n dp[1]=hash[1];\n for(int i=2;i<maxi+1;i++){\n dp[i]=max((dp[i-2]+i*hash[i]),dp[i-1]);\n }\n return dp[maxi];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n count = Counter(nums)\n nums = sorted(list(set(nums)))\n\n earn1, earn2 = 0, 0\n for i in range(len(nums)):\n curEarn = nums[i] * count[nums[i]]\n\n if i > 0 and nums[i] == nums[i - 1] + 1:\n temp = earn2\n earn2 = max(curEarn + earn1, earn2)\n earn1 = temp\n else:\n temp = earn2\n earn2 = curEarn + earn2\n earn1 = temp\n\n return earn2\n```\n\n```Java []\nclass Solution {\n public int deleteAndEarn(int[] nums) {\n if(nums.length==0)\n return 0;\n if(nums.length==1)\n return nums[0];\n if(nums.length==2){\n if(nums[0]+1==nums[1]||nums[0]==nums[1]+1){\n return Math.max(nums[0],nums[1]);\n } else{\n return nums[0]+nums[1];\n }\n }\n int n=nums.length;\n int max = nums[0];\n for(int i=0;i<n;i++){\n if(nums[i]>max)\n max = nums[i];\n }\n int[] count = new int[max+1];\n for(int i=0;i<n;i++){\n count[nums[i]]++;\n }\n int[] dp = new int[max+1];\n dp[1]=count[1]*1;\n for(int i=2;i<max+1;i++){\n dp[i]=Math.max(dp[i-1],count[i]*i+dp[i-2]);\n }\n return dp[max];\n }\n}\n```\n | 5 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
python DP : reduced to house robber | delete-and-earn | 0 | 1 | Once you store the frequency of each number, you can easily see that it is like the House Robber problem:\n\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n if not nums:\n return 0\n\n freq = [0] * (max(nums)+1)\n for n in nums:\n freq[n] += n\n\n dp = [0] * len(freq)\n dp[1] = freq[1]\n for i in range(2, len(freq)):\n dp[i] = max(freq[i] + dp[i-2], dp[i-1])\n\n return dp[len(freq)-1]\n``` | 71 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
Simplest Python dp solution | delete-and-earn | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n n = 10001\n sm = [0] * n\n dp = [0] * n\n \n for num in nums:\n sm[num] += num\n \n dp[0] = 0\n dp[1] = sm[1]\n\n for i in range(2, n):\n dp[i] = max(dp[i-2] + sm[i], dp[i-1])\n \n return dp[n-1]\n\n```\nWith just 2 variables instead of dp list:\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n n = 10001\n sums = [0] * n\n\n for num in nums:\n sums[num] += num\n\n prev, curr = 0, sums[1]\n\n for i in range(2, n):\n prev, curr = curr, max(prev + sums[i], curr)\n\n return curr\n``` | 2 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
easy solution python3 beats 90% in time and memory | delete-and-earn | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ninitialize the array going from 0 to max_value, loop through the input list and increment the count of each value. Then treat this like the robber problem and solve using dynamic programming\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the length of the input list. The code loops through the input list once to calculate the frequency of each value and once more to apply dynamic programming to calculate the maximum value. Both loops have a time complexity of O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m), where m is the maximum value in the input list. The code uses an array called value_counts with a length of max_value + 1 to store the frequency of each value in the input list. Therefore, the space complexity is O(m).\n\n# Code\n```\nclass Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n max_value = max(nums)\n\n # Initialize an array to track the counts of each value in the input list\n\n value_counts = [0] * (max_value + 1)\n for n in nums:\n value_counts[n] += n\n \n \n # Initialize two variables to track the maximum values\n max_value_1 = 0\n max_value_2 = 0\n \n # Iterate through the list of values, updating the maximum values as necessary\n for i in value_counts:\n max_value_1, max_value_2 = max_value_2, max(i + max_value_1, max_value_2)\n \n # Return the final maximum value\n return max_value_2\n\n``` | 6 | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. |
741: Solution with step by step explanation | cherry-pickup | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIn this problem, two people are simultaneously traveling on a grid from the top-left corner to the bottom-right corner. These two travelers pick cherries from the cells they visit. Since they both move towards the bottom-right corner, for every combined step they take, r2 + c2 will always be equal to r1 + c1. Therefore, we can uniquely identify the state by r1, c1, and r2\n\n1. Initialization:\nGet the length N of the grid.\nCreate a 3D memoization table memo to store the results of subproblems.\n\n2. Recursive function dp:\nThis function takes in the current row and column of the first person r1, c1, and the current row of the second person r2. The column of the second person c2 can be derived.\n\n3. Base Cases:\nIf any of the coordinates (r1, c1, r2, c2) are out of the grid or are thorns (-1), then return negative infinity.\nIf all the travelers reach the destination (bottom-right), then return the cherry count in that cell.\nIf the result for this state is already computed, return it.\n\n4. Compute Current Cherry Count:\nCalculate the cherries picked up by the two travelers. If both are in the same cell, add cherries once; otherwise, add for both.\n\n5. Recursive Calls:\nMake recursive calls for all possible next moves:\nBoth move down.\nFirst traveler moves down, second moves right.\nFirst traveler moves right, second moves down.\nBoth move right.\nAdd the maximum cherries from the next moves to the current cherries.\n\n6. Memoization:\nStore the result in the memoization table for reuse.\n\n7. Final Return:\nStart the recursive function from the top-left corner and return the maximum cherries collected.\n\n# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(n^3)\n\n# Code\n```\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n N = len(grid)\n memo = [[[None] * N for _1 in range(N)] for _2 in range(N)]\n\n def dp(r1, c1, r2):\n c2 = r1 + c1 - r2\n\n if not (0 <= r1 < N and 0 <= c1 < N and 0 <= r2 < N and 0 <= c2 < N) or \\\n grid[r1][c1] == -1 or grid[r2][c2] == -1:\n return float(\'-inf\')\n\n if r1 == c1 == r2 == N - 1:\n return grid[r1][c1]\n \n if memo[r1][c1][r2] is not None:\n return memo[r1][c1][r2]\n\n cherries = grid[r1][c1] + (r1 != r2) * grid[r2][c2]\n\n cherries += max(\n dp(r1 + 1, c1, r2 + 1),\n dp(r1 + 1, c1, r2),\n dp(r1, c1 + 1, r2 + 1),\n dp(r1, c1 + 1, r2)\n )\n\n memo[r1][c1][r2] = cherries\n return cherries\n\n return max(0, dp(0, 0, 0))\n\n``` | 1 | You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers.
* `0` means the cell is empty, so you can pass through,
* `1` means the cell contains a cherry that you can pick up and pass through, or
* `-1` means the cell contains a thorn that blocks your way.
Return _the maximum number of cherries you can collect by following the rules below_:
* Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`).
* After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells.
* When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`.
* If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected.
**Example 1:**
**Input:** grid = \[\[0,1,-1\],\[1,0,-1\],\[1,1,1\]\]
**Output:** 5
**Explanation:** The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes \[\[0,1,-1\],\[0,0,-1\],\[0,0,0\]\].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
**Example 2:**
**Input:** grid = \[\[1,1,-1\],\[1,-1,1\],\[-1,1,1\]\]
**Output:** 0
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `grid[i][j]` is `-1`, `0`, or `1`.
* `grid[0][0] != -1`
* `grid[n - 1][n - 1] != -1` | null |
DP and DFS Solutions, With a Different and Hopefully Simpler Explanations, FT 100%!! | cherry-pickup | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nI found this problem to be REALLY challenging. Even after reading some of the top solutions I was pretty confused. So to lead off, the solution is to use dynamic programming or DFS to solve for both paths at the same time.\n\nThe path we take on the way down changes the state of `grid` when we come back up, so when solving the problem we have to be careful to make sure the "up" path doesn\'t have any cherries we took on the way down. This is tricky.\n\nHere\'s what I tried and thought of:\n1. **brute force DFS + backtracking.** On the way down we make 2*N-2 moves to get from (0,0) to (N-1, N-1). N-1 of them are down moves, the others right. So there are O(2N-2 choose N-1) moves. This grows factorially in N (even worse than exponential!). 98 choose 49 is massive. So no.\n2. **dynamic programming: first down, then up** There\'s a classic DP problem for one direction, just going down. It\'s among the first 100 LC problems. If greedy solutions work, then (1) you can get the best path going down, and (2) record that path. Then modify the grid to remove cherries in the best path. Then (3) do the classic DP solution in reverse and return the sum of the two solutions. **But this doesn\'t work: the greedy solution is not always the best solution.**\n3. **dynamic programming: two paths.** Somehow do dynamic programming where we find both paths at the same time. This sounds hard, but it turns out to not be too bad.\n4. **dfs + caching**: the same as (3), but we use DFS and a cache instead of filling out a dynamic programming array.\n\nThis solution shows (3) and (4).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe answer to the solution doesn\'t change if we go down and up, versus if we just take two paths going down. This is because the number of cherries doesn\'t depend on the direction of the path - it just matters that the path goes over the cherry.\n\nSo we make make a DFS/DP solution with a recurrence relation. To get our two paths to (r1,c1) and (r2,c2), our options are\n* path 1 moved down, path 2 moved down\n* path 1 moved down, path 2 moved right\n* path 1 moved right, path 2 moved down\n* path 1 moved right, path 2 moved right\n\nSo `dfs(r1,c1,r2,c2)` depends on `dfs(r1-1,c1,r2-1,c2)`, etc. This is the `max(4 different options)` in the code.\n\nAs a kind of clever insight, we see that both paths move by exactly one square. So we know that each time we call `dfs` that the number of moves both paths have made is the same. This helps us in two ways\n* instead of having four DP/DFS variables, we can get away with 3: let `k` be the number of moves made. Then `k == r1+c2 == r2+c2`. So we just need `k, r1, c2` and can figure out `c1` and `c2`. Now we have $O(N^3)$ DP/DFS states.\n* since the paths have taken the same number of steps, we don\'t have to worry about path 1 visiting (r1, c1) after path 2 visited it. The reason is because (r1, c1) can only be visited on round r1+c1. So either (r1,c1) hasn\'t been visited yet, or both paths are at the same square for the first time.\n\nSo the solution uses these. There are some other checks we do as base cases:\n* if any row or col is out of bounds, return -Inf\n* if either grid cell has a thorn (-1), also return -Inf\n* if this is move `k==0` and we\'re in bounds, then both paths are at 0,0 so we return the grid value there\n* without loss of generality, if you look at two paths, one of them will be at least as far down as the other one. So we reduce the number of operations by only exploring cases where r1 >= r2, i.e. path 1 is farther down than the other. r1 + c1 == k so this is another way of saying that path 1 is at least as far left as the other\n\n**Final notes:**\n* it\'s generally easier to check for edge cases at the top of the `dfs` method. So when we recurse, we call all 4 options. Then the checks at the top of the recursive call figure out if there\'s a valid solution (result >= 0) or not (-Inf)\n* `-Inf` is used to flag bad/impossible situations. We could use anything, but `-Inf` + anything is `-Inf`, and `-Inf` is less than anything finite so it simplifies the code. You can just use `max(...)` and `result + ...`. So if any part of the solution involves an impossible state, then the result `-Inf` as well.\n\n# Is DFS+Caching or Dynamic Programming Faster?\n\nIf you will visit almost all states, then dynamic programming is faster. DFS+Caching involves a map-like structure which is slower than list/array lookups, and a lot of stack frames are created. So lots of overhead. In addition, the DP version only needs $O(N^2)$ memory because we only need the best results from the prior step $k-1$. So there\'s less time and memory needed.\n\nBut in this case, a lot of the test cases have thorns, and those thorns often result in large regions of the grid not being able to reach the bottom right. DFS natually avoids calculating any of those possibilities. So in practice large numbers of (k,r1,r2) combinations are completely irrelevant and don\'t need to be computed.\n\nIn principle you could add this as an optimization to the dynamic programming solution, but it\'s a lot easier to just let DFS organically and naturally just not explore those solutions.\n\nEmpirically it turns out that DFS+caching solution is a LOT faster than DP.\n\n# Complexity\n- Time complexity: $$O(N^3)$$\n\nIn general we explore many combinations of (k,r1,r2) and they\'re all $O(N)$.\n\nTo be more detailed, at $k$ we\'re exploring a shell of radius $k$ steps (L1 norm) away from the bottom right. There are $O(k)$ locations for the first path in that shell, and another $O(k)$ locations of the second path. In general $k$ is $O(N)$. So at each shell there are $O(N^2)$ possibilities. Exploring them for the $O(N)$ steps back to (0,0) therefore involves $O(N^3)$ work.\n\n- Space complexity: $$O(N^3)$$\n\nWe cache DFS solutions, so the memory is also $$O(N^3)$$.\n\n# Code\n```\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n\n # Some approaches:\n # (1) can do DFS + backtracking for both paths. Too many paths though. Could reduce with some followup DP, but the\n # paths "interact" so you have to be careful\n # (2) can try dynamic programming where you build the first half of the down path, then have some optimal subproblem\n # solution for the rest of down plus up. Not clear how you\'d do that though\n # (3) down and then up can be thought of as having two different down paths. can probably write it as C[r][c1][c2] where c1 <= c2\n # because we can go down and right, and once you go right you can\'t go back. so one path will be to the right of the other, and stay there\n # will paths ever cross? unlikely. maybe not really relevant. we\'ll see below\n\n # so we can have the best solution where the paths go from (0, 0) to (r,c1) and (r,c2)\n # from (r, c1) and (r,c2), each path can move R steps to the right, then down\n\n # maybe better to think about the case in reverse: to get to (r,c1) and (r, c2)\n # path 1 had to come from (r,c1-1) or (r-1,c1)\n # path 2 had to come from (r,c2-1) or (r-1,c2)\n #\n # Let B[r][c1][c2] be the best solution for two paths from (0,0) to (r,c1) and (r,c2)\n # Then the four alternatives (2 per path) work out to\n # B[r][c1][c2] = -1 if (r,c1) or (r,c2) are impassable terrain\n # = max(B[r][c1-1][c2-1], ???) # uh-oh... what about when r for left != r for right??\n\n # probably need a fourth variable: the paths are at r1,c1 and r2,c2 after n moves.\n # they move in lockstep though so I don\'t think there are actually four variables\n # but let\'s for ahead with four vars and see if we can reduce to 3 later\n\n # for four variables we have B[r1][c1][r2][c2]\n # at each step r1,c1 and r2,c2 we had to move down or left for both\n # so\n # -1 if either cell is -1 (thorn)\n # best of B[r1-1][c1][r2-1][c2] # so r1+c1 == k == r2+c2, so c1=k-r1 and c2=k-r2. So same info is in some B[k][r1][r2]\n # B[r1][c1-1][r2-1][c2]\n # B[r1-1][c1][r2][c2-1]\n # B[r1][c1-1][r2][c2-2]\n # PLUS grid[r1][c1] + grid[r2][c2] if they\'re different cells\n # PLUS grid[r1][c1] if they\'re the same cell\n # B[k][..] depends only on B[k-1][..] so we now have an O(N^2) space and O(N^3) time solution!\n\n # are there more considerations, e.g. do we need to worry about retracing paths for the +1/+2?\n # e.g. is it possible for r1,c1 that the other path travsed it in a previous step k\' < k?\n # for r1,c1, k = r1+c1. for path 2 to have already been there, it would have happened at k\'=r1+c2 = k.\n # So no, it\'s not possible.\n\n # I hypothesize further that wlog we\'ll never trace paths where path 1 is right of path 2 for a given row..\n # but this condition seems hard to enforce because we use a k,r1,r2-centric solution.\n\n # N = len(grid)\n # prev = [[0]*N for _ in range(N)]\n # curr = [[0]*N for _ in range(N)]\n # prev[0][0] = grid[0][0]\n\n # for k in range(1,2*N+1):\n # #\n # for r1 in range(max(k-N+1, 0), min(k+1,N)): # c1 >= 0 and c1 < N ====> k-r1 >= 0 and k-r1 < N ===> r1 <= k and r1 > k-N\n # c1 = k-r1\n # for r2 in range(max(k-N+1, 0), min(k+1,N)):\n # c2 = k-r2\n\n # # TODO: reorder checks for speed\n # if grid[r1][c1] < 0 or grid[r2][c2] < 0:\n # curr[r1][r2] = -1 # illegal state\n # else:\n # b = -1\n # # up to four source cells: UU, UL, LU, LL\n # if r1 > 0 and r2 > 0: # UU\n # b = prev[r1-1][r2-1]\n # if r1 > 0 and c2 > 0: # UL\n # b = max(b, prev[r1-1][r2])\n # if c1 > 0 and r2 > 0: # LU\n # b = max(b, prev[r1][r2-1])\n # if c1 > 0 and c2 > 0: # LL\n # b = max(b, prev[r1][r2])\n \n # if b == -1:\n # curr[r1][r2] = -1\n # else:\n # if r1 == r2:\n # curr[r1][r2] = b + grid[r1][c1]\n # else:\n # curr[r1][r2] = b + grid[r1][c1] + grid[r2][c2]\n\n # prev, curr = curr, prev\n\n # return max(prev[-1][-1], 0) # both paths at -1,-1. max with zero converts -1 to 0\n\n # FT about 40%\n # Fastest solutions use DFS + caching!!\n # In retrospect, there are some signs that this would be the case:\n # only part of the dp grid is filled out at a time\n # we fill out DP grid for all cells, even those where there is no path to the solution\n # So we could find all such cells not reachable from (-1,-1) and ignore them in the DP array\n # Or we can organically avoid them by the nature of DFS\n\n # brute force DP: be at r1,c1,r2,c2 and take best of four earlier solutions\n # some improvements: at each step we back up by 1 step, both paths have taken the same number of steps\n # so reformulate as k,r1,r2\n # Furthermore, wlog we can say one path is at least as low as the other\n bad = float(\'-inf\')\n\n @functools.cache\n def dfs(k: int, r1: int, r2: int):\n # print(r1, k-r1, r2, k-r2)\n\n if r1 < 0 or r2 < 0 or r1 > r2:\n return bad\n\n c1 = k-r1\n c2 = k-r2\n\n if c1 < 0 or c2 < 0:\n return bad\n\n if k == 0:\n return grid[0][0] # first step, r1 == .. == c2 == 0\n\n if grid[r1][c1] < 0 or grid[r2][c2] < 0:\n return bad\n\n prev = max(\n dfs(k-1, r1, r2),\n dfs(k-1, r1-1, r2),\n dfs(k-1, r1, r2-1),\n dfs(k-1, r1-1, r2-1)\n )\n\n if r1 == r2:\n return prev + grid[r1][c1]\n else:\n return prev + grid[r1][c1] + grid[r2][c2]\n\n N = len(grid)\n return max(dfs(2*N-2, N-1, N-1), 0)\n``` | 2 | You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers.
* `0` means the cell is empty, so you can pass through,
* `1` means the cell contains a cherry that you can pick up and pass through, or
* `-1` means the cell contains a thorn that blocks your way.
Return _the maximum number of cherries you can collect by following the rules below_:
* Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`).
* After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells.
* When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`.
* If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected.
**Example 1:**
**Input:** grid = \[\[0,1,-1\],\[1,0,-1\],\[1,1,1\]\]
**Output:** 5
**Explanation:** The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes \[\[0,1,-1\],\[0,0,-1\],\[0,0,0\]\].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
**Example 2:**
**Input:** grid = \[\[1,1,-1\],\[1,-1,1\],\[-1,1,1\]\]
**Output:** 0
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `grid[i][j]` is `-1`, `0`, or `1`.
* `grid[0][0] != -1`
* `grid[n - 1][n - 1] != -1` | null |
Solution | network-delay-time | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int networkDelayTime(vector<vector<int>>& times, int n, int k) {\n vector<pair<int,int>>adj[n+1];\n for(int i=0;i<times.size();i++){\n adj[times[i][0]].push_back({times[i][1],times[i][2]});\n }\n vector<int>time(n+1,1e9);\n set<pair<int,int>>s;\n s.insert({0,k});\n time[k]=0;\n while(!s.empty()){\n auto i=*(s.begin());\n int wt=i.first;\n int node=i.second;\n s.erase(s.begin());\n for(auto it:adj[node]){\n if(it.second+wt<time[it.first]){\n time[it.first]=it.second+wt;\n s.insert({time[it.first],it.first});\n }\n }\n }\n for(int i=1;i<n+1;i++){\n if(time[i]==1e9){\n return -1;\n }\n }\n return *max_element(time.begin()+1,time.end());\n }\n};\n```\n\n```Python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n graph = defaultdict(list)\n for u, v, w in times:\n graph[u].append((v, w))\n\n min_heap = [(0, k)]\n visited = set()\n distance = {i: float(\'inf\') for i in range(1, n+1)}\n distance[k] = 0\n\n while min_heap:\n cur_total_time, cur_node = heapq.heappop(min_heap)\n if cur_node not in visited:\n visited.add(cur_node)\n\n for adj_node, adj_time in graph[cur_node]:\n if cur_total_time + adj_time < distance[adj_node]:\n distance[adj_node] = cur_total_time + adj_time\n heapq.heappush(min_heap, (cur_total_time + adj_time, adj_node))\n return max(distance.values()) if len(visited) == n else -1\n```\n\n```Java []\nclass Solution {\n public int networkDelayTime(int[][] times, int n, int k) {\n int[][] graph = new int[n][n];\n for (int i = 0; i < n; i++) {\n Arrays.fill(graph[i], -1);\n }\n for (int[] time : times) {\n graph[time[0] - 1][time[1] - 1] = time[2];\n }\n int[] dist = new int[n];\n Arrays.fill(dist, Integer.MAX_VALUE);\n dist[k - 1] = 0;\n boolean[] visited = new boolean[n];\n for (int i = 0; i < n; i++) {\n int u = -1;\n for (int j = 0; j < n; j++) {\n if (!visited[j] && (u == -1 || dist[j] < dist[u])) {\n u = j;\n }\n }\n visited[u] = true;\n for (int v = 0; v < n; v++) {\n if (graph[u][v] != -1 && dist[u] + graph[u][v] < dist[v]) {\n dist[v] = dist[u] + graph[u][v];\n }\n }\n }\n int ans = 0;\n for (int i = 0; i < n; i++) {\n if (dist[i] == Integer.MAX_VALUE) {\n return -1;\n }\n ans = Math.max(ans, dist[i]);\n }\n return ans;\n }\n}\n```\n | 1 | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. |
Solution | network-delay-time | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int networkDelayTime(vector<vector<int>>& times, int n, int k) {\n vector<pair<int,int>>adj[n+1];\n for(int i=0;i<times.size();i++){\n adj[times[i][0]].push_back({times[i][1],times[i][2]});\n }\n vector<int>time(n+1,1e9);\n set<pair<int,int>>s;\n s.insert({0,k});\n time[k]=0;\n while(!s.empty()){\n auto i=*(s.begin());\n int wt=i.first;\n int node=i.second;\n s.erase(s.begin());\n for(auto it:adj[node]){\n if(it.second+wt<time[it.first]){\n time[it.first]=it.second+wt;\n s.insert({time[it.first],it.first});\n }\n }\n }\n for(int i=1;i<n+1;i++){\n if(time[i]==1e9){\n return -1;\n }\n }\n return *max_element(time.begin()+1,time.end());\n }\n};\n```\n\n```Python3 []\nfrom collections import defaultdict\n\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n graph = defaultdict(list)\n for u, v, w in times:\n graph[u].append((v, w))\n\n min_heap = [(0, k)]\n visited = set()\n distance = {i: float(\'inf\') for i in range(1, n+1)}\n distance[k] = 0\n\n while min_heap:\n cur_total_time, cur_node = heapq.heappop(min_heap)\n if cur_node not in visited:\n visited.add(cur_node)\n\n for adj_node, adj_time in graph[cur_node]:\n if cur_total_time + adj_time < distance[adj_node]:\n distance[adj_node] = cur_total_time + adj_time\n heapq.heappush(min_heap, (cur_total_time + adj_time, adj_node))\n return max(distance.values()) if len(visited) == n else -1\n```\n\n```Java []\nclass Solution {\n public int networkDelayTime(int[][] times, int n, int k) {\n int[][] graph = new int[n][n];\n for (int i = 0; i < n; i++) {\n Arrays.fill(graph[i], -1);\n }\n for (int[] time : times) {\n graph[time[0] - 1][time[1] - 1] = time[2];\n }\n int[] dist = new int[n];\n Arrays.fill(dist, Integer.MAX_VALUE);\n dist[k - 1] = 0;\n boolean[] visited = new boolean[n];\n for (int i = 0; i < n; i++) {\n int u = -1;\n for (int j = 0; j < n; j++) {\n if (!visited[j] && (u == -1 || dist[j] < dist[u])) {\n u = j;\n }\n }\n visited[u] = true;\n for (int v = 0; v < n; v++) {\n if (graph[u][v] != -1 && dist[u] + graph[u][v] < dist[v]) {\n dist[v] = dist[u] + graph[u][v];\n }\n }\n }\n int ans = 0;\n for (int i = 0; i < n; i++) {\n if (dist[i] == Integer.MAX_VALUE) {\n return -1;\n }\n ans = Math.max(ans, dist[i]);\n }\n return ans;\n }\n}\n```\n | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
FASTEST PYTHON SOLUTION | network-delay-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n adj=[[] for _ in range(n+1)]\n for i ,j,w in times:\n adj[i].append((j,w))\n dst=[float("infinity")]*(n+1)\n dst[0]=0\n dst[k]=0\n st=[]\n heapq.heapify(st)\n for i,w in adj[k]:\n dst[i]=w\n heapq.heappush(st,(w,i))\n while st:\n # print(st)\n wt,x=heapq.heappop(st)\n for i,w in adj[x]:\n if wt+w<dst[i]:\n dst[i]=wt+w\n heapq.heappush(st,(wt+w,i))\n # print(dst)\n if float("infinity") in dst:\n return -1\n return max(dst)\n\n\n\n\n \n``` | 1 | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. |
FASTEST PYTHON SOLUTION | network-delay-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n adj=[[] for _ in range(n+1)]\n for i ,j,w in times:\n adj[i].append((j,w))\n dst=[float("infinity")]*(n+1)\n dst[0]=0\n dst[k]=0\n st=[]\n heapq.heapify(st)\n for i,w in adj[k]:\n dst[i]=w\n heapq.heappush(st,(w,i))\n while st:\n # print(st)\n wt,x=heapq.heappop(st)\n for i,w in adj[x]:\n if wt+w<dst[i]:\n dst[i]=wt+w\n heapq.heappush(st,(wt+w,i))\n # print(dst)\n if float("infinity") in dst:\n return -1\n return max(dst)\n\n\n\n\n \n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python Simple Dijkstra Beats ~90% | network-delay-time | 0 | 1 | **Time - O(N + ELogN)** -Standard Time complexity of [Dijkstra\'s algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Running_time)\n\n**Space - O(N + E)** - for adjacency list and maintaining Heap.\n\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: \n adj_list = defaultdict(list)\n \n for x,y,w in times:\n adj_list[x].append((w, y))\n \n visited=set()\n heap = [(0, k)]\n while heap:\n travel_time, node = heapq.heappop(heap)\n visited.add(node)\n \n if len(visited)==n:\n return travel_time\n \n for time, adjacent_node in adj_list[node]:\n if adjacent_node not in visited:\n heapq.heappush(heap, (travel_time+time, adjacent_node))\n \n return -1\n```\n\n--- \n\n***Please upvote if you find it useful*** | 54 | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. |
Python Simple Dijkstra Beats ~90% | network-delay-time | 0 | 1 | **Time - O(N + ELogN)** -Standard Time complexity of [Dijkstra\'s algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Running_time)\n\n**Space - O(N + E)** - for adjacency list and maintaining Heap.\n\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: \n adj_list = defaultdict(list)\n \n for x,y,w in times:\n adj_list[x].append((w, y))\n \n visited=set()\n heap = [(0, k)]\n while heap:\n travel_time, node = heapq.heappop(heap)\n visited.add(node)\n \n if len(visited)==n:\n return travel_time\n \n for time, adjacent_node in adj_list[node]:\n if adjacent_node not in visited:\n heapq.heappush(heap, (travel_time+time, adjacent_node))\n \n return -1\n```\n\n--- \n\n***Please upvote if you find it useful*** | 54 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Dijkstra's Algorithms | network-delay-time | 0 | 1 | # Dijkstra\'s Algorithm\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n edges=defaultdict(list)\n for u, v, w in times:\n #graph[u-1].append((v-1, w))\n edges[u].append((v,w))\n minheap=[(0,k)]\n visit=set()\n t=0\n while minheap:\n w1,n1=heapq.heappop(minheap)\n if n1 in visit:\n continue\n visit.add(n1)\n t=max(t,w1)\n for n2,w2 in edges[n1]:\n if n2 not in visit:\n heapq.heappush(minheap,((w1+w2),n2))\n return t if len(visit)==n else -1\n```\n# please upvote me it would encourage me alot\n | 4 | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. |
Dijkstra's Algorithms | network-delay-time | 0 | 1 | # Dijkstra\'s Algorithm\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n edges=defaultdict(list)\n for u, v, w in times:\n #graph[u-1].append((v-1, w))\n edges[u].append((v,w))\n minheap=[(0,k)]\n visit=set()\n t=0\n while minheap:\n w1,n1=heapq.heappop(minheap)\n if n1 in visit:\n continue\n visit.add(n1)\n t=max(t,w1)\n for n2,w2 in edges[n1]:\n if n2 not in visit:\n heapq.heappush(minheap,((w1+w2),n2))\n return t if len(visit)==n else -1\n```\n# please upvote me it would encourage me alot\n | 4 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
743: Solution with step by step explanation | network-delay-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe input is given in the form of edge lists. We want to convert this representation into an adjacency list.\n\n```\ngraph = collections.defaultdict(list)\n\nfor u, v, w in times:\n if u != v:\n graph[u].append((v, w))\n```\nHere, we initialize a dictionary graph to represent our graph as an adjacency list. For each directed edge in times, we add a corresponding entry in our adjacency list. We\'re ensuring we don\'t add self-loops (u != v).\n\nWe will use a priority queue (heap) to keep track of nodes ordered by their distances. We start with the initial node K and a distance of 0.\n\n```\npq = [(0, K)]\ndist_map = {}\n```\n\npq will hold pairs of distances and node numbers. dist_map will store the shortest distance from K to every other node once that node is processed.\n\n\nWhile there are nodes in the priority queue:\n```\nwhile pq:\n time_taken, node = heapq.heappop(pq)\n \n if node in dist_map:\n continue\n \n dist_map[node] = time_taken\n```\nWe pop nodes from the queue in increasing order of their distance. If the node was already visited (i.e., exists in dist_map), we skip it.\n\nNext, for every neighbor of the current node:\n\n```\n for neighbor, time_to_neighbor in graph[node]:\n if neighbor not in dist_map:\n new_time = time_taken + time_to_neighbor\n heapq.heappush(pq, (new_time, neighbor))\n```\n\nWe calculate the new potential shortest distance to the neighbor. If we haven\'t already found a shortest distance to this neighbor, we push it onto the priority queue with its new distance.\n\nFinally, once we\'ve processed all reachable nodes, we check if the number of nodes we\'ve visited (len(dist_map)) is equal to N. If not, some nodes are unreachable, and we return -1.\n\n```\nif len(dist_map) != N:\n return -1\nreturn max(dist_map.values())\n```\n\nOtherwise, we return the maximum distance found, which will be the time taken for the signal to reach the furthest node.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:\n graph = collections.defaultdict(list)\n \n for u, v, w in times:\n if u != v:\n graph[u].append((v, w))\n\n pq = [(0, K)]\n dist_map = {}\n\n while pq:\n time_taken, node = heapq.heappop(pq)\n\n if node in dist_map:\n continue\n \n dist_map[node] = time_taken\n\n for neighbor, time_to_neighbor in graph[node]:\n if neighbor not in dist_map:\n new_time = time_taken + time_to_neighbor\n heapq.heappush(pq, (new_time, neighbor))\n\n if len(dist_map) != N:\n return -1\n\n return max(dist_map.values())\n\n``` | 1 | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. |
743: Solution with step by step explanation | network-delay-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe input is given in the form of edge lists. We want to convert this representation into an adjacency list.\n\n```\ngraph = collections.defaultdict(list)\n\nfor u, v, w in times:\n if u != v:\n graph[u].append((v, w))\n```\nHere, we initialize a dictionary graph to represent our graph as an adjacency list. For each directed edge in times, we add a corresponding entry in our adjacency list. We\'re ensuring we don\'t add self-loops (u != v).\n\nWe will use a priority queue (heap) to keep track of nodes ordered by their distances. We start with the initial node K and a distance of 0.\n\n```\npq = [(0, K)]\ndist_map = {}\n```\n\npq will hold pairs of distances and node numbers. dist_map will store the shortest distance from K to every other node once that node is processed.\n\n\nWhile there are nodes in the priority queue:\n```\nwhile pq:\n time_taken, node = heapq.heappop(pq)\n \n if node in dist_map:\n continue\n \n dist_map[node] = time_taken\n```\nWe pop nodes from the queue in increasing order of their distance. If the node was already visited (i.e., exists in dist_map), we skip it.\n\nNext, for every neighbor of the current node:\n\n```\n for neighbor, time_to_neighbor in graph[node]:\n if neighbor not in dist_map:\n new_time = time_taken + time_to_neighbor\n heapq.heappush(pq, (new_time, neighbor))\n```\n\nWe calculate the new potential shortest distance to the neighbor. If we haven\'t already found a shortest distance to this neighbor, we push it onto the priority queue with its new distance.\n\nFinally, once we\'ve processed all reachable nodes, we check if the number of nodes we\'ve visited (len(dist_map)) is equal to N. If not, some nodes are unreachable, and we return -1.\n\n```\nif len(dist_map) != N:\n return -1\nreturn max(dist_map.values())\n```\n\nOtherwise, we return the maximum distance found, which will be the time taken for the signal to reach the furthest node.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:\n graph = collections.defaultdict(list)\n \n for u, v, w in times:\n if u != v:\n graph[u].append((v, w))\n\n pq = [(0, K)]\n dist_map = {}\n\n while pq:\n time_taken, node = heapq.heappop(pq)\n\n if node in dist_map:\n continue\n \n dist_map[node] = time_taken\n\n for neighbor, time_to_neighbor in graph[node]:\n if neighbor not in dist_map:\n new_time = time_taken + time_to_neighbor\n heapq.heappush(pq, (new_time, neighbor))\n\n if len(dist_map) != N:\n return -1\n\n return max(dist_map.values())\n\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python Elegant & Short | O(log(n)) | Bisect | find-smallest-letter-greater-than-target | 0 | 1 | # Complexity\n- Time complexity: $$O(\\log_2 {n})$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return letters[bisect(letters, target) % len(letters)]\n``` | 2 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python Elegant & Short | O(log(n)) | Bisect | find-smallest-letter-greater-than-target | 0 | 1 | # Complexity\n- Time complexity: $$O(\\log_2 {n})$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return letters[bisect(letters, target) % len(letters)]\n``` | 2 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
SImple Python one-liner using bisect_right (Binary search) | find-smallest-letter-greater-than-target | 0 | 1 | \n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n idx = bisect_right(letters, target)\n return letters[idx] if idx < len(letters) else letters[0]\n```\njust converted it into 1 line for fun heh\n```\nclass Solution:\n def nextGreatestLetter(self, L: List[str], T: str) -> str:\n return L[bisect_right(L, T)] if bisect_right(L, T) < len(L) else L[0]\n``` | 2 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
SImple Python one-liner using bisect_right (Binary search) | find-smallest-letter-greater-than-target | 0 | 1 | \n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n idx = bisect_right(letters, target)\n return letters[idx] if idx < len(letters) else letters[0]\n```\njust converted it into 1 line for fun heh\n```\nclass Solution:\n def nextGreatestLetter(self, L: List[str], T: str) -> str:\n return L[bisect_right(L, T)] if bisect_right(L, T) < len(L) else L[0]\n``` | 2 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
python python python job job job job need solution | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n\n\n \n for i in letters:\n if target != i and sorted([target, i])[1] == i:\n return i \n \n return letters[0]\n\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
python python python job job job job need solution | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n\n\n \n for i in letters:\n if target != i and sorted([target, i])[1] == i:\n return i \n \n return letters[0]\n\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Find Smallest Letter Greater Than Target solution | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n left, right, i = 0, len(letters), -1\n\n while left < right:\n mid = (left + right) // 2\n \n if mid + 1 < len(letters) and letters[mid] <= target and letters[mid + 1] > target:\n i = mid + 1\n break;\n elif letters[mid] > target:\n right = mid\n else:\n left = mid + 1\n\n return letters[0] if i == -1 else letters[i]\n\n\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Find Smallest Letter Greater Than Target solution | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n left, right, i = 0, len(letters), -1\n\n while left < right:\n mid = (left + right) // 2\n \n if mid + 1 < len(letters) and letters[mid] <= target and letters[mid + 1] > target:\n i = mid + 1\n break;\n elif letters[mid] > target:\n right = mid\n else:\n left = mid + 1\n\n return letters[0] if i == -1 else letters[i]\n\n\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
python sorted+index solution, no loop | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\nCharacters in python are equal to numeric values so sort by them and looking for the indexes should find the next one\n\n# Approach\nfirst we create a set with the target added, this will garantee that its in order and no repetition in found, then we get the index for the target and add one more to get the next\n\n# Complexity\n- Time complexity:\n$$O(n*log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n sorted_with_letter = sorted(set(letters+[target]))\n index_target = sorted_with_letter.index(target)\n if index_target == len(sorted_with_letter)-1:\n return sorted_with_letter[0]\n return sorted_with_letter[index_target+1]\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
python sorted+index solution, no loop | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\nCharacters in python are equal to numeric values so sort by them and looking for the indexes should find the next one\n\n# Approach\nfirst we create a set with the target added, this will garantee that its in order and no repetition in found, then we get the index for the target and add one more to get the next\n\n# Complexity\n- Time complexity:\n$$O(n*log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n sorted_with_letter = sorted(set(letters+[target]))\n index_target = sorted_with_letter.index(target)\n if index_target == len(sorted_with_letter)-1:\n return sorted_with_letter[0]\n return sorted_with_letter[index_target+1]\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Intuitive, Easy Python3 Solution 🔥 | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe needed to find the next greater element than the one given as target. If we find such an element in the list letters then return it, else return the first element in letters list.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA linear search approach comparing each letter of letters with target and since it is already given that letters is sorted, we can say that the next largest is the first greater element that we encounter.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ where n is the length of letters\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ since we do not use any extra space \n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n for i in letters:\n if i>target:\n return i\n return letters[0]\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Intuitive, Easy Python3 Solution 🔥 | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe needed to find the next greater element than the one given as target. If we find such an element in the list letters then return it, else return the first element in letters list.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA linear search approach comparing each letter of letters with target and since it is already given that letters is sorted, we can say that the next largest is the first greater element that we encounter.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ where n is the length of letters\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ since we do not use any extra space \n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n for i in letters:\n if i>target:\n return i\n return letters[0]\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Binary Search Variation | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo optimize brute force, binary search is an straightforward approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is a variation of binary search. Since you have to get the smallest character which is larger than target, the final position of `left` index can give required answer.\n\nRefer to following to get more idea: \nhttps://leetcode.com/discuss/interview-question/1322500/5-variations-of-Binary-search-(A-Self-Note)\n\n# Complexity\n- Time complexity: $$O(log(N))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n l, r = 0, len(letters) - 1\n while l < r:\n mid = (l + r) // 2\n if letters[mid] > target:\n r -= 1\n else:\n l += 1\n if letters[l] > target:\n return letters[l]\n else:\n return letters[0]\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Binary Search Variation | find-smallest-letter-greater-than-target | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo optimize brute force, binary search is an straightforward approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is a variation of binary search. Since you have to get the smallest character which is larger than target, the final position of `left` index can give required answer.\n\nRefer to following to get more idea: \nhttps://leetcode.com/discuss/interview-question/1322500/5-variations-of-Binary-search-(A-Self-Note)\n\n# Complexity\n- Time complexity: $$O(log(N))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n l, r = 0, len(letters) - 1\n while l < r:\n mid = (l + r) // 2\n if letters[mid] > target:\n r -= 1\n else:\n l += 1\n if letters[l] > target:\n return letters[l]\n else:\n return letters[0]\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python | One liner | find-smallest-letter-greater-than-target | 0 | 1 | 1. Linear solution `O(N)`\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return min(a) if len(a := list(filter(lambda x: x>target, letters))) > 0 else letters[0]\n```\n2. Binary search solution `O(log N)`\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return letters[a] if (a := bisect.bisect(letters, target)) < len(letters) else letters[0]\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python | One liner | find-smallest-letter-greater-than-target | 0 | 1 | 1. Linear solution `O(N)`\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return min(a) if len(a := list(filter(lambda x: x>target, letters))) > 0 else letters[0]\n```\n2. Binary search solution `O(log N)`\n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n return letters[a] if (a := bisect.bisect(letters, target)) < len(letters) else letters[0]\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python3 Solution | find-smallest-letter-greater-than-target | 0 | 1 | \n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n ans=[]\n c=0\n n=len(letters)\n for i in range(0,n):\n if letters[i]>target:\n ans.append(letters[i])\n\n break\n\n else:\n c+=1\n continue\n\n\n if c==n:\n return letters[0]\n\n else:\n return ans[0] \n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python3 Solution | find-smallest-letter-greater-than-target | 0 | 1 | \n```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n ans=[]\n c=0\n n=len(letters)\n for i in range(0,n):\n if letters[i]>target:\n ans.append(letters[i])\n\n break\n\n else:\n c+=1\n continue\n\n\n if c==n:\n return letters[0]\n\n else:\n return ans[0] \n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Solution | find-smallest-letter-greater-than-target | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n char nextGreatestLetter(vector<char>& letters, char target) {\n auto it = upper_bound(letters.begin(), letters.end(), target);\n return it == letters.end() ? letters[0] : *it;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n index = bisect.bisect(letters, target, 0, len(letters))\n if index < len(letters) and letters[index] == target:\n return letters[index]\n else:\n return letters[index%len(letters)]\n```\n\n```Java []\nclass Solution {\n public char nextGreatestLetter(char[] letters, char target) {\n int start = 0, end = letters.length-1; \n \n while(start<=end){\n int mid = start + (end - start)/2;\n if(letters[mid]>target){\n end = mid - 1;\n }\n else{\n start = mid + 1;\n }\n }\n return letters[start % letters.length];\n }\n}\n```\n | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Solution | find-smallest-letter-greater-than-target | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n char nextGreatestLetter(vector<char>& letters, char target) {\n auto it = upper_bound(letters.begin(), letters.end(), target);\n return it == letters.end() ? letters[0] : *it;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n index = bisect.bisect(letters, target, 0, len(letters))\n if index < len(letters) and letters[index] == target:\n return letters[index]\n else:\n return letters[index%len(letters)]\n```\n\n```Java []\nclass Solution {\n public char nextGreatestLetter(char[] letters, char target) {\n int start = 0, end = letters.length-1; \n \n while(start<=end){\n int mid = start + (end - start)/2;\n if(letters[mid]>target){\n end = mid - 1;\n }\n else{\n start = mid + 1;\n }\n }\n return letters[start % letters.length];\n }\n}\n```\n | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python Linear Scan Easy Solution | find-smallest-letter-greater-than-target | 0 | 1 | ```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n for i in letters:\n if i>target:\n return i\n return letters[0]\n``` | 1 | You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter. | We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm. |
Python Linear Scan Easy Solution | find-smallest-letter-greater-than-target | 0 | 1 | ```\nclass Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n for i in letters:\n if i>target:\n return i\n return letters[0]\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python Easy Trie Solution | prefix-and-suffix-search | 0 | 1 | The Data structure more suitable in such cases is a [Trie](https://en.wikipedia.org/wiki/Trie). Please read and understand Trie before you move onto the solution.\n\nIn this approach, I will be storing all the following combinations of a word in the trie.\n>eg: word = **\'leet\'**\n**>leet#leet\n>eet#leet\n>et#leet\n>t#leet\n>#leet**\n>\nAll the above combinations will be added to the **Trie**.\n\n<img src=\'https://assets.leetcode.com/users/images/292c1ce5-185b-428e-ae2e-701e739a12c0_1655519535.6480691.jpeg\' height="500"/>\n\nNow let\'s say you want to lookup\n> prefix=\'**le**\', suffix=\'**et**\'\n\nYou would search for \'**et#le**\' ie `suffix + \'#\' + prefix` in the **Trie**. So this would match with the **\'et#leet\'** path.\n\nTaking above thoughts into consideration, below is my implementation:\n```\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.trie={}\n self.weight_marker=\'$\'\n w=self.weight_marker\n for idx, word in enumerate(words):\n word=word + \'#\'\n length=len(word)\n word+=word\n \n for i in range(length):\n curr=self.trie\n curr[w]=idx \n for c in word[i:]:\n if c not in curr:\n curr[c]={}\n curr=curr[c] \n curr[w]=idx # update the weight of substring \n \n\n def f(self, prefix: str, suffix: str) -> int:\n curr=self.trie\n for c in suffix + \'#\' + prefix:\n if c not in curr:\n return -1\n curr=curr[c]\n \n return curr[self.weight_marker] \n```\n\nIf `N` is the number of words, `L` is the max length of the word and `M` is the length of the query `suffix + \'#\' + prefix`.\n\n**Time** :\n`Constructor` - `O(N * L^2)` (Compute all the combinations of all the words), `Search` - `O(M)`\n**Space** - `O(N * L^2)`(Store all the combinations of all the words)\n\n\n---\n\n***Please upvote if you find it useful*** | 32 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python Easy Trie Solution | prefix-and-suffix-search | 0 | 1 | The Data structure more suitable in such cases is a [Trie](https://en.wikipedia.org/wiki/Trie). Please read and understand Trie before you move onto the solution.\n\nIn this approach, I will be storing all the following combinations of a word in the trie.\n>eg: word = **\'leet\'**\n**>leet#leet\n>eet#leet\n>et#leet\n>t#leet\n>#leet**\n>\nAll the above combinations will be added to the **Trie**.\n\n<img src=\'https://assets.leetcode.com/users/images/292c1ce5-185b-428e-ae2e-701e739a12c0_1655519535.6480691.jpeg\' height="500"/>\n\nNow let\'s say you want to lookup\n> prefix=\'**le**\', suffix=\'**et**\'\n\nYou would search for \'**et#le**\' ie `suffix + \'#\' + prefix` in the **Trie**. So this would match with the **\'et#leet\'** path.\n\nTaking above thoughts into consideration, below is my implementation:\n```\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.trie={}\n self.weight_marker=\'$\'\n w=self.weight_marker\n for idx, word in enumerate(words):\n word=word + \'#\'\n length=len(word)\n word+=word\n \n for i in range(length):\n curr=self.trie\n curr[w]=idx \n for c in word[i:]:\n if c not in curr:\n curr[c]={}\n curr=curr[c] \n curr[w]=idx # update the weight of substring \n \n\n def f(self, prefix: str, suffix: str) -> int:\n curr=self.trie\n for c in suffix + \'#\' + prefix:\n if c not in curr:\n return -1\n curr=curr[c]\n \n return curr[self.weight_marker] \n```\n\nIf `N` is the number of words, `L` is the max length of the word and `M` is the length of the query `suffix + \'#\' + prefix`.\n\n**Time** :\n`Constructor` - `O(N * L^2)` (Compute all the combinations of all the words), `Search` - `O(M)`\n**Space** - `O(N * L^2)`(Store all the combinations of all the words)\n\n\n---\n\n***Please upvote if you find it useful*** | 32 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Python Sets + Optimization beats 99% | prefix-and-suffix-search | 0 | 1 | \n# Code\n```\nfrom collections import defaultdict\n\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.prefixes = defaultdict(set)\n self.suffixes = defaultdict(set)\n seen = set()\n for idx in range(len(words) - 1, -1, -1):\n word = words[idx]\n if word in seen:\n continue\n seen.add(word)\n for i in range(0, len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n self.prefixes[prefix].add(idx)\n self.suffixes[suffix].add(idx)\n\n def f(self, pref: str, suff: str) -> int:\n if pref in self.prefixes and suff in self.suffixes:\n sharedWords = self.prefixes[pref] & self.suffixes[suff]\n return max(sharedWords) if sharedWords else -1\n return -1\n\n\n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(pref,suff)\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python Sets + Optimization beats 99% | prefix-and-suffix-search | 0 | 1 | \n# Code\n```\nfrom collections import defaultdict\n\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.prefixes = defaultdict(set)\n self.suffixes = defaultdict(set)\n seen = set()\n for idx in range(len(words) - 1, -1, -1):\n word = words[idx]\n if word in seen:\n continue\n seen.add(word)\n for i in range(0, len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n self.prefixes[prefix].add(idx)\n self.suffixes[suffix].add(idx)\n\n def f(self, pref: str, suff: str) -> int:\n if pref in self.prefixes and suff in self.suffixes:\n sharedWords = self.prefixes[pref] & self.suffixes[suff]\n return max(sharedWords) if sharedWords else -1\n return -1\n\n\n# Your WordFilter object will be instantiated and called as such:\n# obj = WordFilter(words)\n# param_1 = obj.f(pref,suff)\n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
745: Solution with step by step explanation | prefix-and-suffix-search | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__ method\nThis method initializes the WordFilter object and pre-processes the given list of words.\n\n```\ndef __init__(self, words):\n self.prefixes = defaultdict(list)\n self.suffixes = defaultdict(list)\n```\nWe use two dictionaries: prefixes and suffixes to store the indices of words that have the corresponding prefix or suffix.\ndefaultdict(list) ensures that if a prefix/suffix is not already in the dictionary, it gets assigned an empty list by default.\n\n```\nfor idx, word in enumerate(words):\n for i in range(len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n\n```\n\nFor each word in the list, we generate all possible prefixes and suffixes.\nFor example, for the word "apple", prefixes are: ["", "a", "ap", "app", "appl", "apple"] and suffixes are the same but in the reverse order.\n\n```\n if not self.prefixes[prefix] or self.prefixes[prefix][0] != idx:\n self.prefixes[prefix].insert(0, idx)\n if not self.suffixes[suffix] or self.suffixes[suffix][0] != idx:\n self.suffixes[suffix].insert(0, idx)\n```\n\nFor each prefix and suffix, we check if it already contains the current index at the front of the list (to avoid duplicates).\nIf not, we insert the word\'s index at the front, ensuring that later occurrences of the same word have a higher priority.\n\nf method\nThis method finds the word\'s index with the given prefix and suffix. If there\'s more than one such word, it returns the one added last.\n\n```\ndef f(self, pref, suff):\n if pref not in self.prefixes or suff not in self.suffixes:\n return -1\n```\n\nFirst, we check if the given prefix or suffix doesn\'t exist in our dictionaries. If either is missing, we immediately return -1 because there\'s no such word.\nThe next part uses a two-pointer technique:\n\n```\n p, s = 0, 0\n while p < len(self.prefixes[pref]) and s < len(self.suffixes[suff]):\n if self.prefixes[pref][p] == self.suffixes[suff][s]:\n return self.prefixes[pref][p]\n if self.prefixes[pref][p] < self.suffixes[suff][s]:\n s += 1\n else:\n p += 1\n```\n\nWe maintain two pointers, p and s, to iterate through the list of indices for the prefix and suffix, respectively.\nIf the current indices are the same, we\'ve found our word.\nIf not, we increment the pointer pointing to the smaller index. Since our lists are in descending order (latest word indices first), this helps us find the intersection efficiently.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass WordFilter:\n def __init__(self, words):\n self.prefixes = defaultdict(list)\n self.suffixes = defaultdict(list)\n\n for idx, word in enumerate(words):\n for i in range(len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n \n if not self.prefixes[prefix] or self.prefixes[prefix][0] != idx:\n self.prefixes[prefix].insert(0, idx)\n if not self.suffixes[suffix] or self.suffixes[suffix][0] != idx:\n self.suffixes[suffix].insert(0, idx)\n\n def f(self, pref, suff):\n if pref not in self.prefixes or suff not in self.suffixes:\n return -1\n\n p, s = 0, 0\n while p < len(self.prefixes[pref]) and s < len(self.suffixes[suff]):\n if self.prefixes[pref][p] == self.suffixes[suff][s]:\n return self.prefixes[pref][p]\n if self.prefixes[pref][p] < self.suffixes[suff][s]:\n s += 1\n else:\n p += 1\n return -1\n\n``` | 1 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
745: Solution with step by step explanation | prefix-and-suffix-search | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__ method\nThis method initializes the WordFilter object and pre-processes the given list of words.\n\n```\ndef __init__(self, words):\n self.prefixes = defaultdict(list)\n self.suffixes = defaultdict(list)\n```\nWe use two dictionaries: prefixes and suffixes to store the indices of words that have the corresponding prefix or suffix.\ndefaultdict(list) ensures that if a prefix/suffix is not already in the dictionary, it gets assigned an empty list by default.\n\n```\nfor idx, word in enumerate(words):\n for i in range(len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n\n```\n\nFor each word in the list, we generate all possible prefixes and suffixes.\nFor example, for the word "apple", prefixes are: ["", "a", "ap", "app", "appl", "apple"] and suffixes are the same but in the reverse order.\n\n```\n if not self.prefixes[prefix] or self.prefixes[prefix][0] != idx:\n self.prefixes[prefix].insert(0, idx)\n if not self.suffixes[suffix] or self.suffixes[suffix][0] != idx:\n self.suffixes[suffix].insert(0, idx)\n```\n\nFor each prefix and suffix, we check if it already contains the current index at the front of the list (to avoid duplicates).\nIf not, we insert the word\'s index at the front, ensuring that later occurrences of the same word have a higher priority.\n\nf method\nThis method finds the word\'s index with the given prefix and suffix. If there\'s more than one such word, it returns the one added last.\n\n```\ndef f(self, pref, suff):\n if pref not in self.prefixes or suff not in self.suffixes:\n return -1\n```\n\nFirst, we check if the given prefix or suffix doesn\'t exist in our dictionaries. If either is missing, we immediately return -1 because there\'s no such word.\nThe next part uses a two-pointer technique:\n\n```\n p, s = 0, 0\n while p < len(self.prefixes[pref]) and s < len(self.suffixes[suff]):\n if self.prefixes[pref][p] == self.suffixes[suff][s]:\n return self.prefixes[pref][p]\n if self.prefixes[pref][p] < self.suffixes[suff][s]:\n s += 1\n else:\n p += 1\n```\n\nWe maintain two pointers, p and s, to iterate through the list of indices for the prefix and suffix, respectively.\nIf the current indices are the same, we\'ve found our word.\nIf not, we increment the pointer pointing to the smaller index. Since our lists are in descending order (latest word indices first), this helps us find the intersection efficiently.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass WordFilter:\n def __init__(self, words):\n self.prefixes = defaultdict(list)\n self.suffixes = defaultdict(list)\n\n for idx, word in enumerate(words):\n for i in range(len(word) + 1):\n prefix = word[:i]\n suffix = word[i:]\n \n if not self.prefixes[prefix] or self.prefixes[prefix][0] != idx:\n self.prefixes[prefix].insert(0, idx)\n if not self.suffixes[suffix] or self.suffixes[suffix][0] != idx:\n self.suffixes[suffix].insert(0, idx)\n\n def f(self, pref, suff):\n if pref not in self.prefixes or suff not in self.suffixes:\n return -1\n\n p, s = 0, 0\n while p < len(self.prefixes[pref]) and s < len(self.suffixes[suff]):\n if self.prefixes[pref][p] == self.suffixes[suff][s]:\n return self.prefixes[pref][p]\n if self.prefixes[pref][p] < self.suffixes[suff][s]:\n s += 1\n else:\n p += 1\n return -1\n\n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Python3 | very easy to understand | basic approach | dictionary | prefix-and-suffix-search | 0 | 1 | ```\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.pref_suf = {}\n for k, word in enumerate(words):\n for i in range(len(word)):\n for j in range(len(word)):\n self.pref_suf[(word[:i+1], word[j:])] = k+1\n\n def f(self, prefix: str, suffix: str) -> int:\n if self.pref_suf.get((prefix, suffix), False):\n return self.pref_suf[(prefix, suffix)]-1\n return -1\n\n``` | 2 | Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`. | Try to find whether each of 26 next letters are in the given string array. |
Python3 | very easy to understand | basic approach | dictionary | prefix-and-suffix-search | 0 | 1 | ```\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.pref_suf = {}\n for k, word in enumerate(words):\n for i in range(len(word)):\n for j in range(len(word)):\n self.pref_suf[(word[:i+1], word[j:])] = k+1\n\n def f(self, prefix: str, suffix: str) -> int:\n if self.pref_suf.get((prefix, suffix), False):\n return self.pref_suf[(prefix, suffix)]-1\n return -1\n\n``` | 2 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
python3 Solution | min-cost-climbing-stairs | 0 | 1 | \n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n n=len(cost)\n prev2=cost[0]\n prev1=cost[1]\n for i in range(2,n):\n temp=cost[i]+min(prev1,prev2)\n prev2=prev1\n prev1=temp\n return min(prev1,prev2) \n \n``` | 2 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
python3 Solution | min-cost-climbing-stairs | 0 | 1 | \n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n n=len(cost)\n prev2=cost[0]\n prev1=cost[1]\n for i in range(2,n):\n temp=cost[i]+min(prev1,prev2)\n prev2=prev1\n prev1=temp\n return min(prev1,prev2) \n \n``` | 2 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3 | min-cost-climbing-stairs | 1 | 1 | # Intuition and approach dicussed in detail in video solution\nhttps://youtu.be/mfKoiEdfMkQ\n\n# Code\nC++\n```\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int sz = cost.size();\n vector<int> minCost(sz);\n minCost[0] = cost[0];\n minCost[1] = cost[1];\n for(int indx = 2; indx < sz; indx++){\n minCost[indx] = cost[indx] + min(minCost[indx - 1], minCost[indx - 2]);\n }\n return min(minCost[sz - 2], minCost[sz - 1]);\n }\n};\n```\nPython 3\n```\nclass Solution:\n def minCostClimbingStairs(self, cost):\n sz = len(cost)\n minCost = [0] * sz\n minCost[0] = cost[0]\n minCost[1] = cost[1]\n for indx in range(2, sz):\n minCost[indx] = cost[indx] + min(minCost[indx - 1], minCost[indx - 2])\n return min(minCost[sz - 2], minCost[sz - 1])\n```\nJava\n```\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int sz = cost.length;\n int minCost[] = new int[sz];\n minCost[0] = cost[0];\n minCost[1] = cost[1];\n for(int indx = 2; indx < sz; indx++){\n minCost[indx] = cost[indx] + Math.min(minCost[indx - 1], minCost[indx - 2]);\n }\n return Math.min(minCost[sz - 2], minCost[sz - 1]);\n }\n}\n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3 | min-cost-climbing-stairs | 1 | 1 | # Intuition and approach dicussed in detail in video solution\nhttps://youtu.be/mfKoiEdfMkQ\n\n# Code\nC++\n```\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int sz = cost.size();\n vector<int> minCost(sz);\n minCost[0] = cost[0];\n minCost[1] = cost[1];\n for(int indx = 2; indx < sz; indx++){\n minCost[indx] = cost[indx] + min(minCost[indx - 1], minCost[indx - 2]);\n }\n return min(minCost[sz - 2], minCost[sz - 1]);\n }\n};\n```\nPython 3\n```\nclass Solution:\n def minCostClimbingStairs(self, cost):\n sz = len(cost)\n minCost = [0] * sz\n minCost[0] = cost[0]\n minCost[1] = cost[1]\n for indx in range(2, sz):\n minCost[indx] = cost[indx] + min(minCost[indx - 1], minCost[indx - 2])\n return min(minCost[sz - 2], minCost[sz - 1])\n```\nJava\n```\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int sz = cost.length;\n int minCost[] = new int[sz];\n minCost[0] = cost[0];\n minCost[1] = cost[1];\n for(int indx = 2; indx < sz; indx++){\n minCost[indx] = cost[indx] + Math.min(minCost[indx - 1], minCost[indx - 2]);\n }\n return Math.min(minCost[sz - 2], minCost[sz - 1]);\n }\n}\n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Beats 100% | O(n) Solution using only one loop | Dynamic Programming Easy Code | min-cost-climbing-stairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be approached as a dynamic programming task where we need to find the minimum cost to reach the top of the staircase. You can start either from the first step (index 0) or the second step (index 1). You can climb one or two steps at a time, and each step has a cost associated with it. To minimize the total cost, you need to make optimal choices at each step.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a dynamic programming array dp of size n + 1, where n is the number of steps in the staircase. The dp array will be used to store the minimum cost to reach each step.\n\n2. Loop through the steps from the 2nd step to the n-th step because you can start either from the 1st or 2nd step.\n\n3. For each step i, calculate the minimum cost to reach that step. You have two options:\n\n- Take one step from the previous step (i - 1) and add the cost of the current step (cost[i - 1]).\n- Take two steps from the step before the previous step (i - 2) and add the cost of the step before the previous one (cost[i - 2]).\n4. Update the dp array at step i with the minimum cost from the two options above.\n\n5. Once the loop is complete, dp[n] will contain the minimum cost to reach the top of the staircase.\n\n6. Return dp[n] as the answer.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the number of steps in the staircase. This is because we iterate through the steps only once to compute the minimum cost.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n + 1), which simplifies to O(n), because we use an additional array dp of size n + 1 to store the minimum cost for each step.\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n = cost.size();\n vector<int> dp(n + 1, 0);\n\n for (int i = 2; i <= n; i++) {\n dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);\n }\n\n return dp[n];\n }\n};\n\n``` | 6 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Beats 100% | O(n) Solution using only one loop | Dynamic Programming Easy Code | min-cost-climbing-stairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be approached as a dynamic programming task where we need to find the minimum cost to reach the top of the staircase. You can start either from the first step (index 0) or the second step (index 1). You can climb one or two steps at a time, and each step has a cost associated with it. To minimize the total cost, you need to make optimal choices at each step.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a dynamic programming array dp of size n + 1, where n is the number of steps in the staircase. The dp array will be used to store the minimum cost to reach each step.\n\n2. Loop through the steps from the 2nd step to the n-th step because you can start either from the 1st or 2nd step.\n\n3. For each step i, calculate the minimum cost to reach that step. You have two options:\n\n- Take one step from the previous step (i - 1) and add the cost of the current step (cost[i - 1]).\n- Take two steps from the step before the previous step (i - 2) and add the cost of the step before the previous one (cost[i - 2]).\n4. Update the dp array at step i with the minimum cost from the two options above.\n\n5. Once the loop is complete, dp[n] will contain the minimum cost to reach the top of the staircase.\n\n6. Return dp[n] as the answer.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the number of steps in the staircase. This is because we iterate through the steps only once to compute the minimum cost.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n + 1), which simplifies to O(n), because we use an additional array dp of size n + 1 to store the minimum cost for each step.\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n = cost.size();\n vector<int> dp(n + 1, 0);\n\n for (int i = 2; i <= n; i++) {\n dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);\n }\n\n return dp[n];\n }\n};\n\n``` | 6 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Easy python code | min-cost-climbing-stairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n cost.append(0)\n for i in range(len(cost)):\n cost[i]+=min(cost[i-1],cost[i-2])\n return cost[-1]\n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Easy python code | min-cost-climbing-stairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n cost.append(0)\n for i in range(len(cost)):\n cost[i]+=min(cost[i-1],cost[i-2])\n return cost[-1]\n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
🔥 Easy solution | JAVA | Python 3 🔥| | min-cost-climbing-stairs | 1 | 1 | # Intuition\nDynamic programming to build up the solution incrementally, considering the minimum cost to reach each step. By the end of the loop, the dp array will contain the minimum cost to reach each step, and the minimum cost to reach the top of the staircase is either in dp[n-1] or dp[n-2]\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, we define a function minCostClimbingStairs that takes a list cost as its argument. This list represents the cost of each step on the staircase.\n\n1. We get the length of the cost list and store it in the variable n. This will be the number of steps in the staircase.\n\n1. We handle two special cases: when there are no steps (empty cost list) and when there is only one step. In these cases, the cost to reach the top is simply 0 or the cost of the single step, so we return 0 or cost[0] accordingly.\n\n1. We create an array dp of length n to store the minimum cost to reach each step. Initially, we fill this array with zeros.\n\n1. We initialize the first two elements of the dp array based on the costs of the first and second steps (dp[0] and dp[1]).\n\n1. We use a loop to fill in the rest of the dp array. For each step i starting from the third step (index 2), we calculate the minimum cost to reach that step based on the costs of the current step and the minimum cost of the previous two steps. We use the recurrence relation:\n\n```\ndp[i] = cost[i] + min(dp[i-1], dp[i-2])\n```\n This means the minimum cost to reach the i-th step is the cost of that step plus the minimum of the costs of the previous two steps (i-1 and i-2).\n\n7. Finally, we return the minimum of the last two elements in the dp array, which represents the minimum cost to reach the top of the staircase. This is done by min(dp[n-1], dp[n-2]).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**Python**\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n n = len(cost)\n if n == 0:\n return 0\n if n == 1:\n return cost[0]\n \n dp = [0] * n\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n \n return min(dp[n-1], dp[n-2])\n```\n**JAVA**\n```\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n if (n == 0) {\n return 0;\n }\n if (n == 1) {\n return cost[0];\n }\n \n int[] dp = new int[n];\n dp[0] = cost[0];\n dp[1] = cost[1];\n \n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]);\n }\n \n return Math.min(dp[n-1], dp[n-2]);\n }\n}\n\n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
🔥 Easy solution | JAVA | Python 3 🔥| | min-cost-climbing-stairs | 1 | 1 | # Intuition\nDynamic programming to build up the solution incrementally, considering the minimum cost to reach each step. By the end of the loop, the dp array will contain the minimum cost to reach each step, and the minimum cost to reach the top of the staircase is either in dp[n-1] or dp[n-2]\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, we define a function minCostClimbingStairs that takes a list cost as its argument. This list represents the cost of each step on the staircase.\n\n1. We get the length of the cost list and store it in the variable n. This will be the number of steps in the staircase.\n\n1. We handle two special cases: when there are no steps (empty cost list) and when there is only one step. In these cases, the cost to reach the top is simply 0 or the cost of the single step, so we return 0 or cost[0] accordingly.\n\n1. We create an array dp of length n to store the minimum cost to reach each step. Initially, we fill this array with zeros.\n\n1. We initialize the first two elements of the dp array based on the costs of the first and second steps (dp[0] and dp[1]).\n\n1. We use a loop to fill in the rest of the dp array. For each step i starting from the third step (index 2), we calculate the minimum cost to reach that step based on the costs of the current step and the minimum cost of the previous two steps. We use the recurrence relation:\n\n```\ndp[i] = cost[i] + min(dp[i-1], dp[i-2])\n```\n This means the minimum cost to reach the i-th step is the cost of that step plus the minimum of the costs of the previous two steps (i-1 and i-2).\n\n7. Finally, we return the minimum of the last two elements in the dp array, which represents the minimum cost to reach the top of the staircase. This is done by min(dp[n-1], dp[n-2]).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**Python**\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n n = len(cost)\n if n == 0:\n return 0\n if n == 1:\n return cost[0]\n \n dp = [0] * n\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n \n return min(dp[n-1], dp[n-2])\n```\n**JAVA**\n```\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n if (n == 0) {\n return 0;\n }\n if (n == 1) {\n return cost[0];\n }\n \n int[] dp = new int[n];\n dp[0] = cost[0];\n dp[1] = cost[1];\n \n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]);\n }\n \n return Math.min(dp[n-1], dp[n-2]);\n }\n}\n\n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
python solution with easy understanding of dynamic approach for beginners to learn | min-cost-climbing-stairs | 0 | 1 | You if like and understand the solution and found helpful so please like my solution and give the star please \uD83D\uDE4F\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.The code uses dynamic programming to find the minimum cost to reach the top of the stairs.\n\n2.It creates an array dp to store the minimum cost at each step.\n\n3.It initializes the first two elements of dp with the cost of the first two steps.\n\n4.Then, it iterates through the cost array starting from the third step.\n\n5.In each iteration, it calculates the minimum cost to reach the current step by considering the minimum cost from the previous step (dp[i-1]) and the cost of the step two positions back (dp[i-2]).\n\n6.It updates the dp array with the calculated minimum cost.\nFinally, it returns the minimum cost to reach the top of the stairs, which is the minimum of the last two values in the dp array.\n# Complexity\n- Time complexity:O(n)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity:O(n)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n dp = [0] * len(cost)\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, len(cost)):\n dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])\n return min(dp[-1],dp[-2]) \n \n``` | 1 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
python solution with easy understanding of dynamic approach for beginners to learn | min-cost-climbing-stairs | 0 | 1 | You if like and understand the solution and found helpful so please like my solution and give the star please \uD83D\uDE4F\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.The code uses dynamic programming to find the minimum cost to reach the top of the stairs.\n\n2.It creates an array dp to store the minimum cost at each step.\n\n3.It initializes the first two elements of dp with the cost of the first two steps.\n\n4.Then, it iterates through the cost array starting from the third step.\n\n5.In each iteration, it calculates the minimum cost to reach the current step by considering the minimum cost from the previous step (dp[i-1]) and the cost of the step two positions back (dp[i-2]).\n\n6.It updates the dp array with the calculated minimum cost.\nFinally, it returns the minimum cost to reach the top of the stairs, which is the minimum of the last two values in the dp array.\n# Complexity\n- Time complexity:O(n)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity:O(n)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n dp = [0] * len(cost)\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, len(cost)):\n dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])\n return min(dp[-1],dp[-2]) \n \n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++ | min-cost-climbing-stairs | 1 | 1 | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nAppend 0 to the last.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LopoDDa4dLY\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Min Cost Climbing Stairs\n`1:43` Explain a basic idea to solve Min Cost Climbing Stairs\n`6:03` Coding\n`8:21` Summarize the algorithm of Min Cost Climbing Stairs\n\nThe video was taken about six month ago, so that was old UI.\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,692\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n### How we think about a solution\n\nOur goal is "Return the minimum cost to reach the top of the floor". But where is the top of the floor? Look at Example 1 in the description.\n\n```\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n```\n\nAccording to the example, From `index 1`, we reach the top by two steps, so\n\n\n---\n\n\u2B50\uFE0F Points\n\nThe goal position is out of bounds place. In this case `index 3`.\n\n---\n\n### How can we calculate costs including out of bounds place?\n\nMy strategy is append `0` to the last position of input array.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe can calculate total min cost easily by appending `0` to the last and avoid out of bounds.\n\nIn addition to that, `0` doesn\'t affect the result of calculation.\n\n---\n\n### How do we calculate min cost easily?\n\nWe know that we can take one or two steps every time.\n\nIt will be tough if we start calculating from beginning, because we will have a lot of ways to calculate when we move on.\n\nFor example,\n\n---\n\n#1, 1 step or 2 steps\n#2, If take 1 step in #1, then 1 step or 2 steps from here\n#3, If take 2 steps in #1, then 1 step or 2 steps from here\n#4, If take 1 step in #2, then 1 step or 2 steps from here\n#5, If take 2 steps in #2, then 1 step or 2 steps from here\n....\n\n\nMoreover, the description says "You can either start from the step with index 0, or the step with index 1".\n\n---\n\nWe have two chocies every time. Seems like though right?\n\n\n---\n\n\u2B50\uFE0F Points\n\nMy strategy is to start from end, so that we can narrow ways to calculate min costs.\n\n---\n\nLet\'s see one by one.\n\n```\nInput: cost = [10,15,20]\n````\n\nFirst of all, Append `0` to the last.\n\n```\n[10,15,20,0]\n```\n\nLet\'s think about `20`\n\nIf we take 1 step, we can reach the goal, so min cost from `index 2` is `20`\n```\n[10,15,20,0]\n\nMin cost from index 2: 20\n```\n\nLet\'s think about `15`\n\nIf we take 1 step from `index 1`, total min cost should be \n```\n15 + 20 = 35\n```\nIf we take 2 steps from `index 1`, total min cost should be\n```\n15 + 0 = 15\n```\n\nSo,\n\n```\nmin(35, 15) = 15\n\nMin cost from index 2: 20\nMin cost from index 1: 15\n```\n\nLet\'s think about `10`.\n\nIf we take 1 step and 2 steps from `index 0`, total min cost should be \n```\n1 step: 10 + 15 = 25\n2 steps: 10 + 20 = 30\n\nmin(25, 30) = 25\n\nMin cost from index 2: 20\nMin cost from index 1: 15\nMin cost from index 0: 25\n```\n\nAt last, we can start from index 0 or index 1, so\n\n```\nmin(cost[0], cost[1]) = min(25, 15)\n\nOutput: 15\n```\n\nI must say one more advantage about why we should calculate from end.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe start calculating from end. That means each cost indicates that they are total costs from each postion to the goal position, so we can easily calculate total min costs with them for the rest of positions(eariler indcies).\n\n---\n\nOne little tip, we can start iteration from `end - 4` because the last appended index is `goal` and we can definitely reach the goal `the last index - 1` and `the last index - 2`, so we don\'t have to calculate min costs for the places.\n\nLet\'s see a real algorithm and solution codes.\n\n\n### Algorithm Overview:\n\nThis is based on Python. Others might be different.\n\n1. Append 0 to the end of the \'cost\' array.\n2. Traverse the \'cost\' array in reverse, updating each element with the minimum cost to reach the top from that position.\n3. Return the minimum of the first two elements in the updated \'cost\' array.\n\n### Detailed Explanation:\n1. Append 0 to the end of the \'cost\' array:\n - Append 0 to account for reaching the top, making the last step from the top cost-free.\n\n2. Traverse the \'cost\' array in reverse:\n - Start from the second-to-last element and iterate in reverse.\n - Update each element with the minimum cost of either taking one step or two steps to reach the top.\n\n3. Return the minimum of the first two elements:\n - Return the minimum of the first two elements, representing the minimum cost of reaching the top from the ground floor.\n\n\n# Complexity\n\nThis is based on Python. Others might be different.\n\n- Time complexity: $$O(n)$$\n\n - Appending 0 to the \'cost\' array takes $$O(1)$$ time.\n - The loop to update the \'cost\' array iterates n times, where n is the length of the \'cost\' array. Since the loop is going backward for at most n elements, it takes O(n) time.\n - Finding the minimum cost after the loop takes $$O(1)$$ time.\n\n - Overall, the time complexity is $$O(n)$$.\n\n- Space complexity: $$O(1)$$ or $$O(n)$$\n - The additional space used is constant, except for the input `cost` array.\n - Therefore, the space complexity is $$O(1)$$, not considering the input space (i.e., `cost` array). If considering the input space, it\'s $$O(n)$$ due to the `cost` array.\n\n```python []\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n cost.append(0) # top [10,15,20,0]\n \n for i in range(len(cost) - 4, -1, -1):\n cost[i] += min(cost[i+1], cost[i+2])\n \n return min(cost[0], cost[1])\n```\n```javascript []\n/**\n * @param {number[]} cost\n * @return {number}\n */\nvar minCostClimbingStairs = function(cost) {\n cost.push(0);\n\n for (let i = cost.length - 4; i >= 0; i--) {\n cost[i] += Math.min(cost[i + 1], cost[i + 2]);\n }\n\n return Math.min(cost[0], cost[1]); \n};\n```\n```java []\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int[] dp = new int[n];\n\n dp[0] = cost[0];\n dp[1] = cost[1];\n\n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);\n }\n\n return Math.min(dp[n - 1], dp[n - 2]);\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n = cost.size();\n cost.push_back(0); // Append 0 for the top step\n\n for (int i = n - 3; i >= 0; i--) {\n cost[i] += min(cost[i + 1], cost[i + 2]);\n }\n\n return min(cost[0], cost[1]); \n }\n};\n```\n\n---\n\n\n\nThank you for reading my post.\n\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n### My next post and video for daily coding challenge\n\npost\nhttps://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/solutions/4169623/video-give-me-10-minutes-how-we-think-abou-a-solution-python-javascript-java-c/\n\nvideo\nhttps://youtu.be/uC0nI4E7ozw\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`0:05` Two key points to solve this question\n`0:21` Explain the first key point\n`1:28` Explain the second key point\n`2:36` Break down and explain real algorithms\n`6:09` Demonstrate how it works\n`10:17` Coding\n`12:58` Time Complexity and Space Complexity\n\n\n### My previous post and video for daily coding challenge\n\npost\nhttps://leetcode.com/problems/find-in-mountain-array/solutions/4159293/video-give-me-10-minutes-how-we-think-about-a-solution-python-javascript-java-c/\n\nvideo\nhttps://youtu.be/09RZINmppQI\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`2:45` An important point when you find peak index\n`4:47` An important point when you find peak index\n`6:13` Coding\n`11:45` Time Complexity and Space Complexity\n\n\n | 43 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++ | min-cost-climbing-stairs | 1 | 1 | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nAppend 0 to the last.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LopoDDa4dLY\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Min Cost Climbing Stairs\n`1:43` Explain a basic idea to solve Min Cost Climbing Stairs\n`6:03` Coding\n`8:21` Summarize the algorithm of Min Cost Climbing Stairs\n\nThe video was taken about six month ago, so that was old UI.\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 2,692\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n### How we think about a solution\n\nOur goal is "Return the minimum cost to reach the top of the floor". But where is the top of the floor? Look at Example 1 in the description.\n\n```\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n```\n\nAccording to the example, From `index 1`, we reach the top by two steps, so\n\n\n---\n\n\u2B50\uFE0F Points\n\nThe goal position is out of bounds place. In this case `index 3`.\n\n---\n\n### How can we calculate costs including out of bounds place?\n\nMy strategy is append `0` to the last position of input array.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe can calculate total min cost easily by appending `0` to the last and avoid out of bounds.\n\nIn addition to that, `0` doesn\'t affect the result of calculation.\n\n---\n\n### How do we calculate min cost easily?\n\nWe know that we can take one or two steps every time.\n\nIt will be tough if we start calculating from beginning, because we will have a lot of ways to calculate when we move on.\n\nFor example,\n\n---\n\n#1, 1 step or 2 steps\n#2, If take 1 step in #1, then 1 step or 2 steps from here\n#3, If take 2 steps in #1, then 1 step or 2 steps from here\n#4, If take 1 step in #2, then 1 step or 2 steps from here\n#5, If take 2 steps in #2, then 1 step or 2 steps from here\n....\n\n\nMoreover, the description says "You can either start from the step with index 0, or the step with index 1".\n\n---\n\nWe have two chocies every time. Seems like though right?\n\n\n---\n\n\u2B50\uFE0F Points\n\nMy strategy is to start from end, so that we can narrow ways to calculate min costs.\n\n---\n\nLet\'s see one by one.\n\n```\nInput: cost = [10,15,20]\n````\n\nFirst of all, Append `0` to the last.\n\n```\n[10,15,20,0]\n```\n\nLet\'s think about `20`\n\nIf we take 1 step, we can reach the goal, so min cost from `index 2` is `20`\n```\n[10,15,20,0]\n\nMin cost from index 2: 20\n```\n\nLet\'s think about `15`\n\nIf we take 1 step from `index 1`, total min cost should be \n```\n15 + 20 = 35\n```\nIf we take 2 steps from `index 1`, total min cost should be\n```\n15 + 0 = 15\n```\n\nSo,\n\n```\nmin(35, 15) = 15\n\nMin cost from index 2: 20\nMin cost from index 1: 15\n```\n\nLet\'s think about `10`.\n\nIf we take 1 step and 2 steps from `index 0`, total min cost should be \n```\n1 step: 10 + 15 = 25\n2 steps: 10 + 20 = 30\n\nmin(25, 30) = 25\n\nMin cost from index 2: 20\nMin cost from index 1: 15\nMin cost from index 0: 25\n```\n\nAt last, we can start from index 0 or index 1, so\n\n```\nmin(cost[0], cost[1]) = min(25, 15)\n\nOutput: 15\n```\n\nI must say one more advantage about why we should calculate from end.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe start calculating from end. That means each cost indicates that they are total costs from each postion to the goal position, so we can easily calculate total min costs with them for the rest of positions(eariler indcies).\n\n---\n\nOne little tip, we can start iteration from `end - 4` because the last appended index is `goal` and we can definitely reach the goal `the last index - 1` and `the last index - 2`, so we don\'t have to calculate min costs for the places.\n\nLet\'s see a real algorithm and solution codes.\n\n\n### Algorithm Overview:\n\nThis is based on Python. Others might be different.\n\n1. Append 0 to the end of the \'cost\' array.\n2. Traverse the \'cost\' array in reverse, updating each element with the minimum cost to reach the top from that position.\n3. Return the minimum of the first two elements in the updated \'cost\' array.\n\n### Detailed Explanation:\n1. Append 0 to the end of the \'cost\' array:\n - Append 0 to account for reaching the top, making the last step from the top cost-free.\n\n2. Traverse the \'cost\' array in reverse:\n - Start from the second-to-last element and iterate in reverse.\n - Update each element with the minimum cost of either taking one step or two steps to reach the top.\n\n3. Return the minimum of the first two elements:\n - Return the minimum of the first two elements, representing the minimum cost of reaching the top from the ground floor.\n\n\n# Complexity\n\nThis is based on Python. Others might be different.\n\n- Time complexity: $$O(n)$$\n\n - Appending 0 to the \'cost\' array takes $$O(1)$$ time.\n - The loop to update the \'cost\' array iterates n times, where n is the length of the \'cost\' array. Since the loop is going backward for at most n elements, it takes O(n) time.\n - Finding the minimum cost after the loop takes $$O(1)$$ time.\n\n - Overall, the time complexity is $$O(n)$$.\n\n- Space complexity: $$O(1)$$ or $$O(n)$$\n - The additional space used is constant, except for the input `cost` array.\n - Therefore, the space complexity is $$O(1)$$, not considering the input space (i.e., `cost` array). If considering the input space, it\'s $$O(n)$$ due to the `cost` array.\n\n```python []\nclass Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n cost.append(0) # top [10,15,20,0]\n \n for i in range(len(cost) - 4, -1, -1):\n cost[i] += min(cost[i+1], cost[i+2])\n \n return min(cost[0], cost[1])\n```\n```javascript []\n/**\n * @param {number[]} cost\n * @return {number}\n */\nvar minCostClimbingStairs = function(cost) {\n cost.push(0);\n\n for (let i = cost.length - 4; i >= 0; i--) {\n cost[i] += Math.min(cost[i + 1], cost[i + 2]);\n }\n\n return Math.min(cost[0], cost[1]); \n};\n```\n```java []\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int[] dp = new int[n];\n\n dp[0] = cost[0];\n dp[1] = cost[1];\n\n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);\n }\n\n return Math.min(dp[n - 1], dp[n - 2]);\n }\n}\n```\n\n```C++ []\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n = cost.size();\n cost.push_back(0); // Append 0 for the top step\n\n for (int i = n - 3; i >= 0; i--) {\n cost[i] += min(cost[i + 1], cost[i + 2]);\n }\n\n return min(cost[0], cost[1]); \n }\n};\n```\n\n---\n\n\n\nThank you for reading my post.\n\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n### My next post and video for daily coding challenge\n\npost\nhttps://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/solutions/4169623/video-give-me-10-minutes-how-we-think-abou-a-solution-python-javascript-java-c/\n\nvideo\nhttps://youtu.be/uC0nI4E7ozw\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`0:05` Two key points to solve this question\n`0:21` Explain the first key point\n`1:28` Explain the second key point\n`2:36` Break down and explain real algorithms\n`6:09` Demonstrate how it works\n`10:17` Coding\n`12:58` Time Complexity and Space Complexity\n\n\n### My previous post and video for daily coding challenge\n\npost\nhttps://leetcode.com/problems/find-in-mountain-array/solutions/4159293/video-give-me-10-minutes-how-we-think-about-a-solution-python-javascript-java-c/\n\nvideo\nhttps://youtu.be/09RZINmppQI\n\n\u25A0 Timeline of the video\n`0:04` How we think about a solution\n`2:45` An important point when you find peak index\n`4:47` An important point when you find peak index\n`6:13` Coding\n`11:45` Time Complexity and Space Complexity\n\n\n | 43 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Simple Code || 100 % beats | min-cost-climbing-stairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis problem can be solved using dynamic programming. The idea is to calculate the minimum cost to reach each step in the staircase. You can do this by iterating through the cost list and updating the cost at each step. Specifically:\n\nInitialize an array dp of the same size as the cost list to keep track of the minimum cost to reach each step.\n\nInitialize the first two elements of dp with the cost of the first two steps since there are no other choices initially.\n\nIterate through the cost list starting from the third element (index 2). For each step, update dp[i] by taking the minimum of two possibilities:\n\nThe cost of reaching the current step from the previous step, i.e., cost[i] + dp[i-1].\n\nThe cost of reaching the current step from two steps back, i.e., cost[i] + dp[i-2].\n\nReturn the minimum value between dp[n-1] and dp[n-2], where n is the total number of steps in the staircase.\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(1)\n\n# Code\n\n```c++ []\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n=cost.size();\n for(int i=2;i<n;i++)\n {\n cost[i]+=min(cost[i-1],cost[i-2]);\n }\n return min(cost[n-1],cost[n-2]);\n }\n};\n```\n```python []\nclass Solution:\n def minCostClimbingStairs(self, cost):\n n = len(cost)\n dp = [0] * n\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n \n return min(dp[n-1], dp[n-2])\n```\n```java []\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int[] dp = new int[n];\n dp[0] = cost[0];\n dp[1] = cost[1];\n \n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]);\n }\n \n return Math.min(dp[n-1], dp[n-2]);\n }\n}\n```\n | 9 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
Simple Code || 100 % beats | min-cost-climbing-stairs | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis problem can be solved using dynamic programming. The idea is to calculate the minimum cost to reach each step in the staircase. You can do this by iterating through the cost list and updating the cost at each step. Specifically:\n\nInitialize an array dp of the same size as the cost list to keep track of the minimum cost to reach each step.\n\nInitialize the first two elements of dp with the cost of the first two steps since there are no other choices initially.\n\nIterate through the cost list starting from the third element (index 2). For each step, update dp[i] by taking the minimum of two possibilities:\n\nThe cost of reaching the current step from the previous step, i.e., cost[i] + dp[i-1].\n\nThe cost of reaching the current step from two steps back, i.e., cost[i] + dp[i-2].\n\nReturn the minimum value between dp[n-1] and dp[n-2], where n is the total number of steps in the staircase.\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(1)\n\n# Code\n\n```c++ []\nclass Solution {\npublic:\n int minCostClimbingStairs(vector<int>& cost) {\n int n=cost.size();\n for(int i=2;i<n;i++)\n {\n cost[i]+=min(cost[i-1],cost[i-2]);\n }\n return min(cost[n-1],cost[n-2]);\n }\n};\n```\n```python []\nclass Solution:\n def minCostClimbingStairs(self, cost):\n n = len(cost)\n dp = [0] * n\n dp[0] = cost[0]\n dp[1] = cost[1]\n \n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n \n return min(dp[n-1], dp[n-2])\n```\n```java []\nclass Solution {\n public int minCostClimbingStairs(int[] cost) {\n int n = cost.length;\n int[] dp = new int[n];\n dp[0] = cost[0];\n dp[1] = cost[1];\n \n for (int i = 2; i < n; i++) {\n dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]);\n }\n \n return Math.min(dp[n-1], dp[n-2]);\n }\n}\n```\n | 9 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
A Beginner's Guide on DP validation & How to come up with a Recursive solution [Python 3] | min-cost-climbing-stairs | 0 | 1 | ### Section 1: DP Validation \nOur first question should be: **Is Dynamic Programming (DP) suitable for this question?**\n\nIn its essence, DP is just **doing brute force recursion smartly**, so we should first check if the question can be done **recursively** (whether we can break it down into **smaller subproblems**) \n\nThen, to check if we can apply DP, we look at 2 distinct properties of DP: \n1. **Overlapping subproblems**: Does finding the solution require us to calculate the same subproblem multiple times? \n2. **Optimal Substructure Property**: Can the optimal solution be constructed from the optimal solutions of its subproblems? (Are the subproblems independent from each other? \n\n**Thought Process**\nWe can use recursion to solve the problem because we can break it into smaller subproblems: \n* If we want to know the **min cost to reach stair #n**, It will be tremendously helpful to know the **min cost to reach step #n-1** and **step #n-2** (because we can reach step #n in one step from them)\n\nNow that we know we can use recursion, should we use DP? Let\'s check if the question contains the two properties that I mentioned above\n1. **Overlapping Subproblems**: \n\t* minCost(n) will be the short form of min cost to reach stair #n\n\t* We know that minCost(n) depends on minCost(n-1) and **minCost(n-2)**, then by the same logic minCost(n-1) depends on **minCost(n-2)** and minCost(n-3). \n\t* Notice that we have the same expression twice (bolded), this shows that **we have overlapping subproblems!** \n\n2. **Optimal Substructure Property**\n\t* let\'s take cost = [4,2,3] for example, what\'s minCost(3)?\n\t* To reach stair #3, we have to start from either stair #1 or #2, since we want to minimize cost so we choose stair #2 (2 < 4) and climb one step to reach #3\n\t* To reach stair #2, since we can choose to start at #2 (step with index 1), it\'s already the optimal solution.\n\t* We see that the optimal solution of one subproblem leads up to the optimal solution of the problem, therefore **this property is present!**\n\nAfter we have both properties fulfilled, we know that we can tackle this problem using DP with confidence! \n\n..............................................................\n### Section 2: How to come up with a recursive solution? \nThe key to solving any DP problem is to **identify a recursive solution**, then we can identify the overlapping subproblems and then apply **memoization (top-down)** or **tabulation (bottom-up)** methods to optimize based of the recursive solution\n\nBelow is a strategy we can use to find a recursive solution\n1. **Identify what variable is changing between each subproblem**\n2. **Create the recursive function based on #1 and clearly defines its meaning**\n3. **State transition formula (Find a formula that connects a problem to its subproblems)**\n4. **Define the base cases of recursion** \n\n**Walkthrough**\n1. **Changing Variables:** \n\t* From the problem, we can see that there are 2 changing variables\n\t* index of the current stair (stair #n) \n\t* minimum cost to reach the current stair \n2. **Create function:** \n\t* We can associate the 2 variables together by creating a function minCost(n), where n is the index of the current stair, and minCost(n) represents the min cost to reach stair #n\n\t* This is the same function that we came up with in section 1 based on pure intuition \n3. **Get State transition formula:** \n\t * Get a formula to connect a problem to its subproblems, we first check what is moving the problem forward. By reading the problem, we see that the key info is that **you can either climb one or two steps.**\n\t * Based of this info, we know that minCost(n) has strong relationship to minCost(n-1) and minCost(n-2), because you can reach n from both n-1 and n-2 stairs \n\t * Keep reading the question, we see that we should **pay the cost at each stair** and **get minimum cost**, so the relationship between them becomes clear as shown below\n\t * minCost(n) = cost[n] + min(minCost(n-1), minCost(n-2))\n4. **Define base cases:**\n\t* This part is easy, from the problem statement we know we can start from either stair index 0 or index 1\n\t* So base cases would be the first 2 stairs. minCost(0) = cost[0] and minCost(1) = cost[1] \n\nWith all the above info, it\'s easy to construct a recursive solution as shown below: \n```\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n # identify what is changing from subproblems to subproblems: \n # n - step #n dp(n) - min cost to get to step #n \n def dp(n): \n # write down base cases\n if n < 2: \n return cost[n] \n # write recursive function based on what you can change (climb one or two steps)\n return cost[n] + min(dp(n-1), dp(n-2))\n\t\t\n\t\t# since we want to know the min cost to get to the final step, we use the code below \n length = len(cost) \n return min(dp(length-1), dp(length-2))\n```\n..............................................................\n### Section 3: Extra\n* To see how to use DP techniques (top-down, bottom-up) to make recursion more efficient, check out https://leetcode.com/problems/min-cost-climbing-stairs/discuss/476388/4-ways-or-Step-by-step-from-Recursion-greater-top-down-DP-greater-bottom-up-DP-greater-fine-tuning\n\n* Please leave a comment to let me know any confusion or feedback :)\n\n* This problem took me a while to understand, and I wish to share the thought process for the first few very important parts \n\n* Thank you for reading, have a nice day! | 402 | You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999` | For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te". |
A Beginner's Guide on DP validation & How to come up with a Recursive solution [Python 3] | min-cost-climbing-stairs | 0 | 1 | ### Section 1: DP Validation \nOur first question should be: **Is Dynamic Programming (DP) suitable for this question?**\n\nIn its essence, DP is just **doing brute force recursion smartly**, so we should first check if the question can be done **recursively** (whether we can break it down into **smaller subproblems**) \n\nThen, to check if we can apply DP, we look at 2 distinct properties of DP: \n1. **Overlapping subproblems**: Does finding the solution require us to calculate the same subproblem multiple times? \n2. **Optimal Substructure Property**: Can the optimal solution be constructed from the optimal solutions of its subproblems? (Are the subproblems independent from each other? \n\n**Thought Process**\nWe can use recursion to solve the problem because we can break it into smaller subproblems: \n* If we want to know the **min cost to reach stair #n**, It will be tremendously helpful to know the **min cost to reach step #n-1** and **step #n-2** (because we can reach step #n in one step from them)\n\nNow that we know we can use recursion, should we use DP? Let\'s check if the question contains the two properties that I mentioned above\n1. **Overlapping Subproblems**: \n\t* minCost(n) will be the short form of min cost to reach stair #n\n\t* We know that minCost(n) depends on minCost(n-1) and **minCost(n-2)**, then by the same logic minCost(n-1) depends on **minCost(n-2)** and minCost(n-3). \n\t* Notice that we have the same expression twice (bolded), this shows that **we have overlapping subproblems!** \n\n2. **Optimal Substructure Property**\n\t* let\'s take cost = [4,2,3] for example, what\'s minCost(3)?\n\t* To reach stair #3, we have to start from either stair #1 or #2, since we want to minimize cost so we choose stair #2 (2 < 4) and climb one step to reach #3\n\t* To reach stair #2, since we can choose to start at #2 (step with index 1), it\'s already the optimal solution.\n\t* We see that the optimal solution of one subproblem leads up to the optimal solution of the problem, therefore **this property is present!**\n\nAfter we have both properties fulfilled, we know that we can tackle this problem using DP with confidence! \n\n..............................................................\n### Section 2: How to come up with a recursive solution? \nThe key to solving any DP problem is to **identify a recursive solution**, then we can identify the overlapping subproblems and then apply **memoization (top-down)** or **tabulation (bottom-up)** methods to optimize based of the recursive solution\n\nBelow is a strategy we can use to find a recursive solution\n1. **Identify what variable is changing between each subproblem**\n2. **Create the recursive function based on #1 and clearly defines its meaning**\n3. **State transition formula (Find a formula that connects a problem to its subproblems)**\n4. **Define the base cases of recursion** \n\n**Walkthrough**\n1. **Changing Variables:** \n\t* From the problem, we can see that there are 2 changing variables\n\t* index of the current stair (stair #n) \n\t* minimum cost to reach the current stair \n2. **Create function:** \n\t* We can associate the 2 variables together by creating a function minCost(n), where n is the index of the current stair, and minCost(n) represents the min cost to reach stair #n\n\t* This is the same function that we came up with in section 1 based on pure intuition \n3. **Get State transition formula:** \n\t * Get a formula to connect a problem to its subproblems, we first check what is moving the problem forward. By reading the problem, we see that the key info is that **you can either climb one or two steps.**\n\t * Based of this info, we know that minCost(n) has strong relationship to minCost(n-1) and minCost(n-2), because you can reach n from both n-1 and n-2 stairs \n\t * Keep reading the question, we see that we should **pay the cost at each stair** and **get minimum cost**, so the relationship between them becomes clear as shown below\n\t * minCost(n) = cost[n] + min(minCost(n-1), minCost(n-2))\n4. **Define base cases:**\n\t* This part is easy, from the problem statement we know we can start from either stair index 0 or index 1\n\t* So base cases would be the first 2 stairs. minCost(0) = cost[0] and minCost(1) = cost[1] \n\nWith all the above info, it\'s easy to construct a recursive solution as shown below: \n```\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n # identify what is changing from subproblems to subproblems: \n # n - step #n dp(n) - min cost to get to step #n \n def dp(n): \n # write down base cases\n if n < 2: \n return cost[n] \n # write recursive function based on what you can change (climb one or two steps)\n return cost[n] + min(dp(n-1), dp(n-2))\n\t\t\n\t\t# since we want to know the min cost to get to the final step, we use the code below \n length = len(cost) \n return min(dp(length-1), dp(length-2))\n```\n..............................................................\n### Section 3: Extra\n* To see how to use DP techniques (top-down, bottom-up) to make recursion more efficient, check out https://leetcode.com/problems/min-cost-climbing-stairs/discuss/476388/4-ways-or-Step-by-step-from-Recursion-greater-top-down-DP-greater-bottom-up-DP-greater-fine-tuning\n\n* Please leave a comment to let me know any confusion or feedback :)\n\n* This problem took me a while to understand, and I wish to share the thought process for the first few very important parts \n\n* Thank you for reading, have a nice day! | 402 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Easy Python Solution | largest-number-at-least-twice-of-others | 0 | 1 | # Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n maxx,index=nums[0],0\n for i,v in enumerate(nums):\n maxx=max(maxx,v)\n if maxx==v:\n index=i\n for i in range(len(nums)):\n if nums[i]!=maxx and maxx<2*nums[i]:\n return -1\n\n return index\n \n \n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Easy Python Solution | largest-number-at-least-twice-of-others | 0 | 1 | # Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n maxx,index=nums[0],0\n for i,v in enumerate(nums):\n maxx=max(maxx,v)\n if maxx==v:\n index=i\n for i in range(len(nums)):\n if nums[i]!=maxx and maxx<2*nums[i]:\n return -1\n\n return index\n \n \n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python Elegant & Short | O(n) time one pass | O(1) space | 98.3% faster | 99.7% memory | largest-number-at-least-twice-of-others | 0 | 1 | \n\n```\ndef dominantIndex(self, nums: List[int]) -> int:\n\tfirst_max = second_max = -1\n\tmax_ind = 0\n\n\tfor i, num in enumerate(nums):\n\t\tif num >= first_max:\n\t\t\tfirst_max, second_max = num, first_max\n\t\t\tmax_ind = i\n\t\telif num > second_max:\n\t\t\tsecond_max = num\n\n\tif first_max < 2*second_max:\n\t\tmax_ind = -1\n\n\treturn max_ind\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n\n | 24 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Python Elegant & Short | O(n) time one pass | O(1) space | 98.3% faster | 99.7% memory | largest-number-at-least-twice-of-others | 0 | 1 | \n\n```\ndef dominantIndex(self, nums: List[int]) -> int:\n\tfirst_max = second_max = -1\n\tmax_ind = 0\n\n\tfor i, num in enumerate(nums):\n\t\tif num >= first_max:\n\t\t\tfirst_max, second_max = num, first_max\n\t\t\tmax_ind = i\n\t\telif num > second_max:\n\t\t\tsecond_max = num\n\n\tif first_max < 2*second_max:\n\t\tmax_ind = -1\n\n\treturn max_ind\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n\n | 24 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
747: Solution with step by step explanation | largest-number-at-least-twice-of-others | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n \n # Step 1: Initialization\n # We will start by initializing two indices, `max_idx` for the largest number and \n # `second_max_idx` for the second largest number. Both are set to -1 initially.\n max_idx, second_max_idx = -1, -1\n\n # Step 2: Finding the largest and second largest numbers\n # We will loop through each number in the `nums` list.\n for i, num in enumerate(nums):\n \n # If we encounter a number larger than the current maximum (or if it\'s the first iteration),\n # the current maximum becomes the second maximum and the new number becomes the new maximum.\n if max_idx == -1 or num > nums[max_idx]:\n second_max_idx = max_idx\n max_idx = i\n \n # Otherwise, if the number is larger than the second maximum (or if it\'s the first iteration after the max),\n # the new number becomes the new second maximum.\n elif second_max_idx == -1 or num > nums[second_max_idx]:\n second_max_idx = i\n \n # Step 3: Validate the dominant condition\n # If the largest number is at least twice as large as the second largest number, \n # we return the index of the largest number. Otherwise, return -1.\n if nums[max_idx] >= 2 * nums[second_max_idx]:\n return max_idx\n else:\n return -1\n```\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n\n max_idx, second_max_idx = -1, -1\n\n for i, num in enumerate(nums):\n if max_idx == -1 or num > nums[max_idx]:\n second_max_idx = max_idx\n max_idx = i\n elif second_max_idx == -1 or num > nums[second_max_idx]:\n second_max_idx = i\n\n if nums[max_idx] >= 2 * nums[second_max_idx]:\n return max_idx\n else:\n return -1\n\n``` | 1 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
747: Solution with step by step explanation | largest-number-at-least-twice-of-others | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n \n # Step 1: Initialization\n # We will start by initializing two indices, `max_idx` for the largest number and \n # `second_max_idx` for the second largest number. Both are set to -1 initially.\n max_idx, second_max_idx = -1, -1\n\n # Step 2: Finding the largest and second largest numbers\n # We will loop through each number in the `nums` list.\n for i, num in enumerate(nums):\n \n # If we encounter a number larger than the current maximum (or if it\'s the first iteration),\n # the current maximum becomes the second maximum and the new number becomes the new maximum.\n if max_idx == -1 or num > nums[max_idx]:\n second_max_idx = max_idx\n max_idx = i\n \n # Otherwise, if the number is larger than the second maximum (or if it\'s the first iteration after the max),\n # the new number becomes the new second maximum.\n elif second_max_idx == -1 or num > nums[second_max_idx]:\n second_max_idx = i\n \n # Step 3: Validate the dominant condition\n # If the largest number is at least twice as large as the second largest number, \n # we return the index of the largest number. Otherwise, return -1.\n if nums[max_idx] >= 2 * nums[second_max_idx]:\n return max_idx\n else:\n return -1\n```\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n\n max_idx, second_max_idx = -1, -1\n\n for i, num in enumerate(nums):\n if max_idx == -1 or num > nums[max_idx]:\n second_max_idx = max_idx\n max_idx = i\n elif second_max_idx == -1 or num > nums[second_max_idx]:\n second_max_idx = i\n\n if nums[max_idx] >= 2 * nums[second_max_idx]:\n return max_idx\n else:\n return -1\n\n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Beats 100% - Easy Java, C++ and Python Solution | largest-number-at-least-twice-of-others | 1 | 1 | # Intuition\nWe will find the highest and second highest number in nums. Then finally, check if:\nhighest >= (second highest * 2)\nIf it is, we return the index of the highest element.\nIf not, then we return -1.\n# Approach\nSince all the numbers in nums are positive, we set highest and second highest as both -1 at the start, and index to 0.\nThen we iterate over nums, and check if the nums[i] > highest. If it is, we set second to highest and then highest to i. Also, we set index to i.\n\nIf it is not, then we check if nums[i] > second, since nums[i] may not be the highest element, but it might be the second highest element. If it is, we set second to nums[i].\n\nAfter this loop, we get the highest and second highest elements. After that, we check if highest >= second * 2. If this is true, it must be true for the third highest, fourth highest....lowest number in nums as well. \n\nIf this is true, then we return index. If not, we return -1.\n\n# Complexity\n- Time complexity:\nO(n)\n\n# C++ Code\n```\nclass Solution {\npublic:\n int dominantIndex(vector<int>& nums) {\n int highest = -1;\n int second = -1;\n int index = 0;\n for (int i = 0; i < nums.size(); i++)\n {\n if (nums[i] > highest)\n {\n second = highest;\n highest = nums[i];\n index = i;\n }\n else if (nums[i] > second)\n {\n second = nums[i];\n }\n }\n if (highest >= second * 2)\n {\n return index;\n }\n else\n {\n return -1;\n }\n }\n};\n```\n# Java Code\n```\nclass Solution {\n public int dominantIndex(int[] nums) {\n int highest = -1;\n int second = -1;\n int index = 0;\n for (int i = 0; i < nums.length; i++)\n {\n if (nums[i] > highest)\n {\n second = highest;\n highest = nums[i];\n index = i;\n }\n else if (nums[i] > second)\n {\n second = nums[i];\n }\n }\n if (highest >= second * 2)\n {\n return index;\n }\n else\n {\n return -1;\n }\n }\n}\n```\n\n# Python Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n highest = -1\n second = -1\n index = 0\n for i in range(len(nums)):\n if nums[i] > highest:\n second = highest\n highest = nums[i]\n index = i\n elif nums[i] > second:\n second = nums[i]\n if highest >= second * 2:\n return index\n else:\n return -1\n``` | 3 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Beats 100% - Easy Java, C++ and Python Solution | largest-number-at-least-twice-of-others | 1 | 1 | # Intuition\nWe will find the highest and second highest number in nums. Then finally, check if:\nhighest >= (second highest * 2)\nIf it is, we return the index of the highest element.\nIf not, then we return -1.\n# Approach\nSince all the numbers in nums are positive, we set highest and second highest as both -1 at the start, and index to 0.\nThen we iterate over nums, and check if the nums[i] > highest. If it is, we set second to highest and then highest to i. Also, we set index to i.\n\nIf it is not, then we check if nums[i] > second, since nums[i] may not be the highest element, but it might be the second highest element. If it is, we set second to nums[i].\n\nAfter this loop, we get the highest and second highest elements. After that, we check if highest >= second * 2. If this is true, it must be true for the third highest, fourth highest....lowest number in nums as well. \n\nIf this is true, then we return index. If not, we return -1.\n\n# Complexity\n- Time complexity:\nO(n)\n\n# C++ Code\n```\nclass Solution {\npublic:\n int dominantIndex(vector<int>& nums) {\n int highest = -1;\n int second = -1;\n int index = 0;\n for (int i = 0; i < nums.size(); i++)\n {\n if (nums[i] > highest)\n {\n second = highest;\n highest = nums[i];\n index = i;\n }\n else if (nums[i] > second)\n {\n second = nums[i];\n }\n }\n if (highest >= second * 2)\n {\n return index;\n }\n else\n {\n return -1;\n }\n }\n};\n```\n# Java Code\n```\nclass Solution {\n public int dominantIndex(int[] nums) {\n int highest = -1;\n int second = -1;\n int index = 0;\n for (int i = 0; i < nums.length; i++)\n {\n if (nums[i] > highest)\n {\n second = highest;\n highest = nums[i];\n index = i;\n }\n else if (nums[i] > second)\n {\n second = nums[i];\n }\n }\n if (highest >= second * 2)\n {\n return index;\n }\n else\n {\n return -1;\n }\n }\n}\n```\n\n# Python Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n highest = -1\n second = -1\n index = 0\n for i in range(len(nums)):\n if nums[i] > highest:\n second = highest\n highest = nums[i]\n index = i\n elif nums[i] > second:\n second = nums[i]\n if highest >= second * 2:\n return index\n else:\n return -1\n``` | 3 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python3||Beats 95.1% || Easy beginner solution | largest-number-at-least-twice-of-others | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n nums1 = sorted(nums)\n if nums1[len(nums1)-1]>= 2*nums1[len(nums1)-2]:\n for i in range(len(nums)):\n if nums[i] == nums1[len(nums1)-1]:\n return i\n break\n else:\n return -1\n```\n\n | 4 | You are given an integer array `nums` where the largest integer is **unique**.
Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** nums = \[3,6,1,0\]
**Output:** 1
**Explanation:** 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** -1
**Explanation:** 4 is less than twice the value of 3, so we return -1.
**Constraints:**
* `2 <= nums.length <= 50`
* `0 <= nums[i] <= 100`
* The largest element in `nums` is unique. | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.