title
stringlengths 3
77
| title_slug
stringlengths 3
77
| question_content
stringlengths 38
1.55k
⌀ | tag
stringclasses 643
values | level
stringclasses 3
values | question_hints
stringclasses 869
values | view_count
int64 19
630k
| vote_count
int64 5
3.67k
| content
stringlengths 0
43.9k
| __index_level_0__
int64 0
109k
|
---|---|---|---|---|---|---|---|---|---|
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 15,674 | 62 | ![Screenshot 2023-12-21 050230.png]()\n\n---\n# Intuition\n##### The problem asks for the widest vertical area between two points on a 2D plane. To find this, we can sort the given points based on their x-coordinates. After sorting, we can iterate through the sorted points and calculate the horizontal distance between consecutive points. The maximum of these distances will be the widest vertical area.\n---\n\n# Approach\n 1. #### Sort the points based on their x-coordinates.\n 2. #### Initialize a variable `max_width` to store the maximum width.\n 3. #### Iterate through the sorted points starting from index 1.\n 4. #### For each pair of consecutive points, calculate the width by subtracting the x-coordinate of the previous point from the x-coordinate of the current point.\n 5. #### Update `max_width` with the maximum of its current value and the calculated width.\n 6. #### After the iteration, `max_width` will contain the result.\n---\n# Complexity\n- ### Time complexity:\n##### $$O(n * log(n))$$ due to the sorting operation, where n is the number of points.\n- ### Space complexity:\n##### $$O(1)$$ as we use a constant amount of space for variables.\n---\n# Code\n\n```python []\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n points.sort(key=lambda x: x[0])\n\n max_width = 0\n\n for i in range(1, len(points)):\n width = points[i][0] - points[i-1][0]\n max_width = max(max_width, width)\n\n return max_width\n```\n```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(std::vector<std::vector<int>>& points) {\n std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) {\n return a[0] < b[0];\n });\n\n int max_width = 0;\n\n for (int i = 1; i < points.size(); ++i) {\n int width = points[i][0] - points[i - 1][0];\n max_width = std::max(max_width, width);\n }\n\n return max_width;\n }\n};\n```\n```javascript []\nvar maxWidthOfVerticalArea = function(points) {\n points.sort((a, b) => a[0] - b[0]);\n\n let maxWidth = 0;\n\n for (let i = 1; i < points.length; i++) {\n let width = points[i][0] - points[i - 1][0];\n maxWidth = Math.max(maxWidth, width);\n }\n\n return maxWidth;\n};\n\n```\n```java []\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));\n\n int max_width = 0;\n\n for (int i = 1; i < points.length; i++) {\n int width = points[i][0] - points[i - 1][0];\n max_width = Math.max(max_width, width);\n }\n\n return max_width;\n }\n}\n```\n```C# []\npublic class Solution {\n public int MaxWidthOfVerticalArea(int[][] points) {\n Array.Sort(points, (a, b) => a[0].CompareTo(b[0]));\n\n int maxWidth = 0;\n\n for (int i = 1; i < points.Length; i++) {\n int width = points[i][0] - points[i - 1][0];\n maxWidth = Math.Max(maxWidth, width);\n }\n\n return maxWidth;\n }\n}\n```\n```PHP []\nclass Solution {\n function maxWidthOfVerticalArea($points) {\n usort($points, function ($a, $b) {\n return $a[0] - $b[0];\n });\n\n $maxWidth = 0;\n\n for ($i = 1; $i < count($points); $i++) {\n $width = $points[$i][0] - $points[$i - 1][0];\n $maxWidth = max($maxWidth, $width);\n }\n\n return $maxWidth;\n }\n}\n\n```\n```ruby []\ndef max_width_of_vertical_area(points)\n points.sort! { |a, b| a[0] - b[0] }\n\n max_width = 0\n\n (1...points.length).each do |i|\n width = points[i][0] - points[i - 1][0]\n max_width = [max_width, width].max\n end\n\n max_width\nend\n\n```\n---\n![Screenshot 2023-08-20 065922.png]()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 86,699 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 2,585 | 49 | # Intuition\nSort x-coordinates\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:06` Explain key points\n`3:16` Coding\n`4:38` Time Complexity and Space Complexity\n`4:57` Step by step algorithm of my solution code\n`5:08` Bonus coding in Python\n`6:19` Time Complexity and Space Complexity for Bonus\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,571\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nWe need to find widest vertical area, so simply we sort x-coordinates in input array, then find the widest area.\n\n```\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\n```\nWe don\'t need `y-coordinates`, so take `all x-coordinates` only and sort them.\n\n```\n[[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\n\u2193\n[3,9,1,1,5,8]\n\u2193\nx_sorted = [1, 1, 3, 5, 8, 9]\n```\nSince it\'s sorted, the latter number should be larger. Width between two points should be\n\n```\nwidth = (number at current index + 1) - (number at current index)\n```\nLet\'s see one by one. Number of loop should be `length of x_sorted - 1` to prevent out of bounds\n\n```\nindex = 0\n\n[1, 1, 3, 5, 8, 9]\n\nmax_width = max(max_width(= 0), 1 - 1)\n\nfirst 1 from index 1\nsecond 1 from index 0\n\nmax_width = 0\n```\n```\nindex = 1\n\n[1, 1, 3, 5, 8, 9]\n\nmax_width = max(max_width(= 0), 3 - 1)\n\n3 from index 2\n1 from index 1\n\nmax_width = 2\n```\n```\nindex = 2\n\n[1, 1, 3, 5, 8, 9]\n\nmax_width = max(max_width(= 2), 5 - 3)\n\n5 from index 3\n3 from index 2\n\nmax_width = 2\n```\n```\nindex = 3\n\n[1, 1, 3, 5, 8, 9]\n\nmax_width = max(max_width(= 2), 8 - 5)\n\n8 from index 4\n5 from index 3\n\nmax_width = 3\n```\n```\nindex = 4\n\n[1, 1, 3, 5, 8, 9]\n\nmax_width = max(max_width(= 3), 9 - 8)\n\n9 from index 5\n8 from index 4\n\nmax_width = 3\n```\n```\nOutput: 3\n```\n\nEasy!\uD83D\uDE04\nLet\'s see solution codes.\n\n---\n\n# Complexity & Solution codes\n- Time complexity: $$O(n log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$\nDepends on language you use. Sorting need some extra space.\n\n```python []\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n x_sorted = sorted([x for x, _ in points])\n\n max_width = 0\n for i in range(len(x_sorted) - 1):\n max_width = max(max_width, x_sorted[i + 1] - x_sorted[i])\n\n return max_width \n```\n```javascript []\n/**\n * @param {number[][]} points\n * @return {number}\n */\nvar maxWidthOfVerticalArea = function(points) {\n const xSorted = points.map(([x, _]) => x).sort((a, b) => a - b);\n\n let maxWidth = 0;\n for (let i = 0; i < xSorted.length - 1; i++) {\n maxWidth = Math.max(maxWidth, xSorted[i + 1] - xSorted[i]);\n }\n\n return maxWidth; \n};\n```\n```java []\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n int[] xSorted = Arrays.stream(points).mapToInt(point -> point[0]).sorted().toArray();\n\n int maxWidth = 0;\n for (int i = 0; i < xSorted.length - 1; i++) {\n maxWidth = Math.max(maxWidth, xSorted[i + 1] - xSorted[i]);\n }\n\n return maxWidth; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n vector<int> xSorted;\n for (const auto& point : points) {\n xSorted.push_back(point[0]);\n }\n\n sort(xSorted.begin(), xSorted.end());\n\n int maxWidth = 0;\n for (int i = 0; i < xSorted.size() - 1; i++) {\n maxWidth = max(maxWidth, xSorted[i + 1] - xSorted[i]);\n }\n\n return maxWidth; \n }\n};\n```\n\n## Step by step algorithm\n\n1. **Sorting the x-coordinates:**\n ```python\n x_sorted = sorted([x for x, _ in points])\n ```\n This line creates a list `x_sorted` by extracting the x-coordinates from the input `points` and sorting them in ascending order.\n\n2. **Initializing the maximum width variable:**\n ```python\n max_width = 0\n ```\n Here, `max_width` is initialized to zero. This variable will be used to track the maximum width between consecutive x-coordinates.\n\n3. **Iterating through the sorted list:**\n ```python\n for i in range(len(x_sorted) - 1):\n ```\n The loop iterates through the sorted list of x-coordinates. The `- 1` ensures that the loop doesn\'t go out of bounds, as we are comparing each element with the next one.\n\n4. **Calculating and updating the maximum width:**\n ```python\n max_width = max(max_width, x_sorted[i + 1] - x_sorted[i])\n ```\n Within the loop, the width between the current x-coordinate (`x_sorted[i]`) and the next one (`x_sorted[i + 1]`) is calculated. If this width is greater than the current `max_width`, it updates `max_width` to store the maximum width encountered so far.\n\n5. **Returning the maximum width:**\n ```python\n return max_width\n ```\n Finally, the function returns the maximum width between consecutive x-coordinates.\n\nIn summary, the algorithm sorts the x-coordinates, iterates through the sorted list, calculates the width between consecutive x-coordinates, and keeps track of the maximum width encountered. The sorted order ensures that the latter number in each pair is larger, simplifying the width calculation. The final result is the maximum width between any two consecutive x-coordinates.\n\n\n---\n\n# Bonus\n\nIn python, if we can use `itertools.pairwise`\n\n```python []\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n x_sorted = sorted([x for x, _ in points])\n return max(x2 - x1 for x1, x2 in itertools.pairwise(x_sorted)) \n```\n`itertools.pairwise` takes adjacent two numbers like\n```\n[1,2,3,4,5]\n\u2193\nx1, x2\n1, 2: first loop\n2, 3: second loop\n3, 4: third loop\n4, 5: fourth loop\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:03` Explain key points\n`2:40` coding\n`4:49` Time Complexity and Space Complexity\n`5:02` Step by step algorithm of my solution code\n | 86,700 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 5,553 | 39 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n#### ***Approach 1(Sorting)***\n1. **Sorting Points:**\n\n- The function begins by sorting the `points` vector based on the x-coordinate of each point. This is done using `sort(points.begin(), points.end())`.\n1. **Calculating Maximum Width:**\n\n- It then iterates through the sorted points.\n- For each pair of consecutive points, it calculates the difference in x-coordinates (`points[i][0] - points[i-1][0]`).\n- It updates the `diff` variable to hold the maximum difference encountered while traversing the sorted points.\n1. **Returning the Maximum Width:**\n\n- Finally, it returns the maximum `diff`, which represents the maximum width between two consecutive x-coordinates among the sorted points.\n\n\n# Complexity\n- Time complexity:\n $$O(nlogn)$$\n \n\n- Space complexity:\n $$O(logn)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n sort(points.begin(),points.end());\n int diff =0;\n for(int i =1;i<points.size();i++){\n diff = max(diff,points[i][0]-points[i-1][0]);\n }\n return diff;\n }\n};\n\n\n\n\n```\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));\n int diff = 0;\n for (int i = 1; i < points.length; i++) {\n diff = Math.max(diff, points[i][0] - points[i - 1][0]);\n }\n return diff;\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n points.sort()\n diff = 0\n for i in range(1, len(points)):\n diff = max(diff, points[i][0] - points[i - 1][0])\n return diff\n\n\n\n```\n```javascript []\nvar maxWidthOfVerticalArea = function(points) {\n points.sort((a, b) => a[0] - b[0]);\n let diff = 0;\n for (let i = 1; i < points.length; i++) {\n diff = Math.max(diff, points[i][0] - points[i - 1][0]);\n }\n return diff;\n};\n\n\n```\n\n---\n\n#### ***Approach 2(With Sets)***\n1. The function `maxWidthOfVerticalArea` takes a vector of vectors points representing coordinates.\n1. It utilizes a set `xCoordinates` to store unique x-coordinates from the input points.\n1. Iterates through each point, extracting its x-coordinate and inserts it into the set.\n1. Initializes variables `maxDiff` to keep track of the maximum difference between x-coordinates and `prevX` to hold the previous x-coordinate.\n1. Iterates through the set of x-coordinates:\n - Updates `maxDiff` by finding the maximum difference between the current x-coordinate and the previous x-coordinate.\n - Updates `prevX` with the current x-coordinate for the next iteration.\n1. Returns the `maxDiff`, which represents the maximum width of the vertical area.\n\n\n# Complexity\n- Time complexity:\n $$O(nlogn)$$\n \n\n- Space complexity:\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n set<int> xCoordinates; // Using a set to store unique x-coordinates\n \n for (const auto& point : points) {\n xCoordinates.insert(point[0]); // Inserting x-coordinates into the set\n }\n \n int maxDiff = 0;\n int prevX = INT_MIN;\n \n for (int x : xCoordinates) {\n if (prevX != INT_MIN) {\n maxDiff = max(maxDiff, x - prevX); // Calculate the maximum difference\n }\n prevX = x;\n }\n \n return maxDiff;\n }\n};\n\n\n\n```\n```Java []\n\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n Set<Integer> xCoordinates = new TreeSet<>();\n \n for (int[] point : points) {\n xCoordinates.add(point[0]);\n }\n \n int maxDiff = 0;\n Integer prevX = null;\n \n for (int x : xCoordinates) {\n if (prevX != null) {\n maxDiff = Math.max(maxDiff, x - prevX);\n }\n prevX = x;\n }\n \n return maxDiff;\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n x_coordinates = sorted(set(point[0] for point in points))\n max_diff = 0\n prev_x = None\n \n for x in x_coordinates:\n if prev_x is not None:\n max_diff = max(max_diff, x - prev_x)\n prev_x = x\n \n return max_diff\n\n\n\n```\n```javascript []\n\nvar maxWidthOfVerticalArea = function(points) {\n let xCoordinates = new Set();\n \n for (let point of points) {\n xCoordinates.add(point[0]);\n }\n \n let maxDiff = 0;\n let prevX = null;\n \n for (let x of [...xCoordinates].sort((a, b) => a - b)) {\n if (prevX !== null) {\n maxDiff = Math.max(maxDiff, x - prevX);\n }\n prevX = x;\n }\n \n return maxDiff;\n};\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 86,701 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 830 | 15 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly x-coordinate is important.\n\nUsing sorting is easy; a 2 line code for python\nThe 2nd Python code is also 2 line code which uses the matrix-transpose-like zip & beats 100% in speed.\n\nC++ has 3 solutions, not only uses sort, but also `set` & `priority_queue`.\n\nMy own Python 1-liner is made thanks to comments of @Sergei & @maria_q pointing out the solutions of @MikPosp\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince the constraints `0 <= xi, yi <= 10^9`, using counting sort is not possible. The normal sort is very useful.\n\nBesides the normal sorting, there are other methods:\n- ordered set (C++ set)\n- max Heap (C++ priority_queue )\n\nDue to implementation experience, the performance of priority_queue is superior to the one of set.\n\nThe C++ solutions drop out the info on y-coordinates.\nThe implementation using x-sort&adjacent_difference is the fast one.\n|Method|Elasped Time|speed record|Memory|\n|---|---|---|---|\n|C++ priority_queue|157 ms| 98.06%|67.26MB|\n|C++ set| 199 ms|79.19%|79.97MB|\n|C++ x-sort&adjacent_difference|121ms|99.68% |66.98MB| \n|Python sort|731 ms|84.94%|60.28MB|\n|Python sort+ sorted(list(zip(*points))[0])|677ms|100%|59.62MB\n|Python 1-liner|657ms|100%|60.03MB|\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Python 1-liner\n```\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n return max([x1-x0 for x0, x1 in pairwise(sorted(list(zip(*points))[0]))])\n \n```\n# Python Code 2-liner using sorted\n```\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n x=[x0 for x0, _ in sorted(points)]\n return max([x[i+1]-x[i] for i in range(len(x)-1)])\n \n```\n# Python 2-line Code using sorted(list(zip(*points))[0]) 677ms Beats 100%\n```\nclass Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n x= sorted(list(zip(*points))[0])\n return max([x[i+1]-x[i] for i in range(len(x)-1)])\n \n```\n# C++ using Max Heap\uFF08priority_queue\uFF09157 ms Beats 98.06%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n priority_queue<int> pq;//Max heap\n for(auto& coord: points)\n pq.push(coord[0]);\n int mdiff=0, prev=pq.top();\n while(!pq.empty()){\n int curr=pq.top();\n pq.pop();\n mdiff=max(mdiff, prev-curr);\n prev=curr;\n }\n return mdiff; \n }\n};\n```\n# C++ using set\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n set<int> x;\n for(auto& coord: points)\n x.insert(coord[0]);\n int mdiff=0, prev=*x.begin();\n for (int x1: x){\n mdiff=max(mdiff, x1-prev);\n prev=x1;\n }\n return mdiff; \n }\n};\n\n```\n# C++ using x-sorting&adjacent_difference 121ms Beats 99.68%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n vector<int> x;\n for (auto& coord: points)\n x.push_back(coord[0]);\n sort(x.begin(), x.end());\n adjacent_difference(x.begin(), x.end(), x.begin());\n\n return *max_element(x.begin()+1, x.end()); \n }\n};\n```\n\n\n | 86,702 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 1,674 | 12 | \n---\n\n\n# **Please Upvote If It Is Helpfull**\n\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. **Sort Points by X-Coordinates:** The code begins by sorting the `points` vector based on their x-coordinates. This ensures that points are arranged from left to right, which is crucial for calculating widths accurately.\n\n2. **Initialize Maximum Width:** It initializes `ans` to 0, which will store the maximum width found so far.\n\n3. **Iterate Through Sorted Points:** A loop iterates through the sorted points, starting from the second point. This is because the width is calculated between pairs of points.\n\n4. **Calculate Width and Update Maximum:** For each pair of consecutive points (current and previous), it calculates the width by subtracting the x-coordinate of the previous point from the x-coordinate of the current point. This difference represents the horizontal distance between them. The `ans` variable is updated if this width is greater than the current maximum width.\n\n5. **Return Maximum Width:** After iterating through all pairs, the code returns the `ans` variable, which holds the largest width found among all pairs of points in the vertical area.\n\n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n sort(points.begin(), points.end());\n \n int ans = 0;\n for (int i = 1; i < points.size(); i++) {\n ans = max(ans, points[i][0] - points[i - 1][0]);\n }\n \n return ans;\n }\n};\n```\n```java []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n Arrays.sort(points, (p1, p2) -> Integer.compare(p1[0], p2[0])); // Sort by x-coordinates\n \n int maxWidth = 0;\n for (int i = 1; i < points.length; i++) {\n maxWidth = Math.max(maxWidth, points[i][0] - points[i - 1][0]);\n }\n \n return maxWidth;\n }\n};\n```\n```python []\nclass Solution(object):\n def maxWidthOfVerticalArea(self, points):\n """\n :type points: List[List[int]]\n :rtype: int\n """\n points.sort(key=lambda p: p[0]) # Sort by x-coordinates\n\n maxWidth = 0\n for i in range(1, len(points)):\n maxWidth = max(maxWidth, points[i][0] - points[i - 1][0])\n\n return maxWidth\n \n```\n```javascript []\n/**\n * @param {number[][]} points\n * @return {number}\n */\nvar maxWidthOfVerticalArea = function(points) {\n points.sort((a, b) => a[0] - b[0]); // Sort by x-coordinates\n\n let maxWidth = 0;\n for (let i = 1; i < points.length; i++) {\n maxWidth = Math.max(maxWidth, points[i][0] - points[i - 1][0]);\n }\n\n return maxWidth;\n};\n```\n```ruby []\n# @param {Integer[][]} points\n# @return {Integer}\ndef max_width_of_vertical_area(points)\n points.sort_by! { |p| p[0] } # Sort by x-coordinates\n\n max_width = 0\n 1.upto(points.length - 1) do |i|\n max_width = [max_width, points[i][0] - points[i - 1][0]].max\n end\n\n max_width\nend\n```\n```go []\nfunc maxWidthOfVerticalArea(points [][]int) int {\n sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) // Sort by x-coordinates\n\n maxWidth := 0\n for i := 1; i < len(points); i++ {\n maxWidth = max(maxWidth, points[i][0] - points[i-1][0])\n }\n\n return maxWidth\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n\n```\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n **Here\'s the approach in 5 points:**\n\n1. **Collect Unique X-Coordinates:**\n - Creates a `set` named `uniqueX` to store unique x-coordinates from the input `points`.\n - Iterates through `points` and inserts each point\'s x-coordinate into `uniqueX`.\n\n2. **Initialize Variables:**\n - Sets `maxDifference` to 0 to track the largest width found so far.\n - Sets `previousX` to `INT_MIN` to represent the absence of a previous x-coordinate.\n\n3. **Iterate Through Unique X-Coordinates:**\n - Iterates through each distinct x-coordinate `x` in the `uniqueX` set.\n\n4. **Calculate Width and Update Maximum:**\n - If `previousX` is not `INT_MIN` (meaning a previous x-coordinate exists), it calculates the width between the current and previous x-coordinates (`x - previousX`).\n - Updates `maxDifference` if the calculated width is larger than the current maximum.\n\n5. **Return Maximum Width:**\n - After processing all unique x-coordinates, the code returns `maxDifference`, representing the largest width found in the vertical area.\n\n\n\n# Complexity\n- Time complexity:O(nlogn)\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```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n set<int> uniqueX; \n \n for (const auto& point : points) {\n uniqueX.insert(point[0]); \n }\n \n int maxDifference = 0;\n int previousX = INT_MIN;\n \n for (int x : uniqueX) {\n if (previousX != INT_MIN) {\n maxDifference = max(maxDifference, x - previousX); \n }\n previousX = x;\n }\n \n return maxDifference;\n }\n};\n```\n```java []\nimport java.util.HashSet;\nimport java.util.Set;\n\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n Set<Integer> uniqueX = new HashSet<>();\n\n for (int[] point : points) {\n uniqueX.add(point[0]);\n }\n\n int maxDifference = 0;\n int previousX = Integer.MIN_VALUE;\n\n for (int x : uniqueX) {\n if (previousX != Integer.MIN_VALUE) {\n maxDifference = Math.max(maxDifference, x - previousX);\n }\n previousX = x;\n }\n\n return maxDifference;\n }\n}\n\n```\n```python []\ndef maxWidthOfVerticalArea(points):\n unique_x = set()\n\n for point in points:\n unique_x.add(point[0])\n\n max_difference = 0\n previous_x = float(\'-inf\') # Represents negative infinity\n\n for x in unique_x:\n if previous_x != float(\'-inf\'):\n max_difference = max(max_difference, x - previous_x)\n previous_x = x\n\n return max_difference\n\n \n```\n```javascript []\n/**\n * @param {number[][]} points\n * @return {number}\n */\nfunction maxWidthOfVerticalArea(points) {\n const uniqueX = new Set();\n\n for (const point of points) {\n uniqueX.add(point[0]);\n }\n\n let maxDifference = 0;\n let previousX = Number.MIN_SAFE_INTEGER;\n\n for (const x of uniqueX) {\n if (previousX !== Number.MIN_SAFE_INTEGER) {\n maxDifference = Math.max(maxDifference, x - previousX);\n }\n previousX = x;\n }\n\n return maxDifference;\n}\n\n```\n```ruby []\n# @param {Integer[][]} points\n# @return {Integer}\ndef max_width_of_vertical_area(points)\n unique_x = Set.new\n\n points.each { |point| unique_x.add(point[0]) }\n\n max_difference = 0\n previous_x = -Float::INFINITY # Represents negative infinity\n\n unique_x.each do |x|\n if previous_x != -Float::INFINITY\n max_difference = [max_difference, x - previous_x].max\n end\n previous_x = x\n end\n\n max_difference\nend\n\n```\n```go []\nfunc maxWidthOfVerticalArea(points [][]int) int {\n uniqueX := make(map[int]struct{}) // Use a map to store unique x-coordinates\n\n for _, point := range points {\n uniqueX[point[0]] = struct{}{}\n }\n\n maxWidth := 0\n previousX := math.MinInt32 // Represents negative infinity\n\n for x := range uniqueX {\n if previousX != math.MinInt32 {\n maxWidth = max(maxWidth, x-previousX)\n }\n previousX = x\n }\n\n return maxWidth\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n\n```\n\n\n---\n![imgleetcode.png]()\n\n\n\n\n\n | 86,703 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 361 | 10 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nignore Y and try to sort the x axis elements\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Traverse through the given vector of points and extract the `x-coordinates` (first element of each point) into a separate vector `ans`.\n- `Sort` the `ans` vector in ascending order. This step is crucial for finding the maximum width.\n- Iterate through the sorted `ans` vector and calculate the difference between consecutive x-coordinates. Keep track of the `maximum` width encountered.\n- The variable `maxi` now holds the maximum width of the vertical area, and it can be returned.\n\n# Complexity\n- Time complexity:$$O(nlogn)$$\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```C++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n vector<int> ans;\n int maxi=0;\n int sndMax=0;\n for(int i=0;i<points.size();i++)\n {\n for(int j=0;j<points[0].size();j++)\n {\n ans.push_back(points[i][0]);\n }\n }\n sort(ans.begin(),ans.end());\n for(int i=ans.size()-1;i>=1;i--)\n {\n maxi=max(maxi,ans[i]-ans[i-1]);\n }\n return maxi;\n }\n};\n```\n```python []\nclass Solution:\n def maxWidthOfVerticalArea(self, points):\n ans = []\n maxi = 0\n\n for point in points:\n ans.append(point[0])\n\n ans.sort()\n\n for i in range(len(ans) - 1, 0, -1):\n maxi = max(maxi, ans[i] - ans[i-1])\n\n return maxi\n```\n\n![upvote.jpg]()\n\n | 86,704 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 697 | 8 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nGiven the problem description, our focus is solely on the x coordinates, disregarding the y coordinates. In this context, we can efficiently address the issue by gathering and sorting all x coordinates, utilizing a set to eliminate duplicates. Subsequently, we can iterate through the sorted set, monitoring the maximum difference between adjacent points.\n\n# Complexity\n- Time complexity:\nThe dominant factor in the time complexity is the insertion of elements into the set (s.insert(i[0])), which takes O(log n) time for each element. If there are \'n\' elements, the overall time complexity becomes O(n log n).\n- Space complexity:\nThe set s stores the unique x-coordinates from the input points. In the worst case, all x-coordinates are distinct, and the set will have \'n\' elements, resulting in O(n) space complexity.\n```c++ []\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n set<int> s;\n int res = 0;\n for (auto i : points)\n {\n s.insert(i[0]);\n }\n for (auto it = next(begin(s)); it != end(s); ++it)\n {\n res = max(res, *it - *prev(it));\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def maxWidthOfVerticalArea(self, points):\n s = set()\n res = 0\n for i in points:\n s.add(i[0])\n sorted_set = sorted(s)\n for i in range(1, len(sorted_set)):\n res = max(res, sorted_set[i] - sorted_set[i-1])\n return res\n\n```\n```java []\nclass Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n Set<Integer> set = new HashSet<>();\n int res = 0;\n for (int[] point : points) {\n set.add(point[0]);\n }\n Integer[] sortedSet = set.toArray(new Integer[0]);\n Arrays.sort(sortedSet);\n for (int i = 1; i < sortedSet.length; i++) {\n res = Math.max(res, sortedSet[i] - sortedSet[i - 1]);\n }\n return res;\n }\n}\n```\n![WhatsApp Image 2023-10-20 at 08.23.29.jpeg]()\n\n | 86,705 |
Widest Vertical Area Between Two Points Containing No Points | widest-vertical-area-between-two-points-containing-no-points | Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area. A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width. Note that points on the edge of a vertical area are not considered included in the area. | Array,Sorting | Medium | Try sorting the points Think is the y-axis of a point relevant | 330 | 6 | # Intuition \uD83E\uDD14\nThe problem asks us to find the widest vertical area between two points on a 2D plane, such that no other points lie inside this area. The width of the area is determined by the difference in x-coordinates of two consecutive points when the points are sorted. We want to maximize this width.\n\n![Screenshot 2023-12-21 082420.png]()\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \uD83D\uDE80\n1. **Sort the points**: To find the width, we first need to sort the points based on their x-coordinates.\n2. **Calculate Widths**: Iterate through the sorted points and calculate the width between each pair of consecutive points. Keep track of the maximum width encountered so far.\n3. **Maximize Width**: Update the maximum width whenever a wider vertical area is found.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- **Time Complexity: \u23F0**\nThe dominant operation is the sorting of the points, which takes O(n log n) time, where n is the number of points. The subsequent iteration takes O(n) time. Therefore, the overall time complexity is O(n log n).\n\n- **Space Complexity: \uD83E\uDDE0**\nThe space complexity is O(1) since we are using a constant amount of extra space (no additional data structures) regardless of the input size.\n\n# Code\n- **Sorting:** `sort(points.begin(), points.end())` sorts the points based on their x-coordinates.\n- **Width Calculation:** Iterate through the sorted points, calculating the width between consecutive points using `currX - prevX`.\n- **Maximum Width Update:** `ans = max(ans, currX - prevX)` updates the maximum width whenever a wider vertical area is found.\n- **Input/Output Optimization:** `ios_base::sync_with_stdio(false)` and related lines optimize input/output for faster execution.\n```\nclass Solution {\npublic:\n int maxWidthOfVerticalArea(vector<vector<int>>& points) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n sort(points.begin(),points.end());\n int ans = 0;\n for(int i = 1; i < points.size(); i++)\n {\n int prevX = points[i - 1][0];\n int currX = points[i][0];\n ans = max(ans, currX - prevX);\n }\n return ans;\n }\n};\n```\n![lc1.png]()\n | 86,706 |
Count Substrings That Differ by One Character | count-substrings-that-differ-by-one-character | Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in "computer" and "computation" only differ by the 'e'/'a', so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string. | Hash Table,String,Dynamic Programming | Medium | Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary. | 785 | 6 | Believe me, this ques is like must to have in the mind, as this gonna help you solve many such questions.\n1. We have to calculate all substrings which differ by just a character.\n2. So, maintain 2 states, first one will be for the count of substrings which is present in "t" string as well(all characters equal). The second one will keep the count with 1 different character.\n3. Traverse the 2 strings using 2 pointers using 2 loops. If the char which are being pointed are same, which means we will have our ans from already differed strings, which already have a character different. So just use that.\n4. If they are different, then go for all the strings which have all the characters same, because the current is gonna be a different one.\n5. Now just keep maintaining these 2 states for all the indices.\n6. Didn\'t get it, read it for 3-4 times atleast. And you\'re free to comment down :)\n```\ndef countSubstrings(self, s: str, t: str) -> int:\n\tls, lt = len(s), len(t)\n\tequal_prev, unequal_prev = [0] * (lt+1), [0] * (lt+1)\n\tans = 0\n\tfor i in range(ls):\n\t\tequal_curr, unequal_curr = [0] * (lt+1), [0] * (lt+1)\n\t\tfor j in range(lt):\n\t\t\tif(s[i] == t[j]):\n\t\t\t\tequal_curr[j+1] = 1+equal_prev[j]\n\t\t\tunequal_curr[j+1] = 1+equal_prev[j] if(s[i] != t[j]) else unequal_prev[j]\n\t\t\tans += unequal_curr[j+1]\n\t\tequal_prev, unequal_prev = equal_curr, unequal_curr\n\treturn ans\n``` | 86,766 |
Number of Ways to Form a Target String Given a Dictionary | number-of-ways-to-form-a-target-string-given-a-dictionary | You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. | Array,String,Dynamic Programming | Hard | For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array, | 10,132 | 57 | # Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Number of Ways to Form a Target String Given a Dictionary` by `Aryan Mittal`\n![Google5.png]()\n\n\n# Approach & Intution\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int numWays(vector<string>& words, string target) {\n int n = words[0].size();\n int m = target.size();\n int mod = 1000000007;\n vector<int> dp(m+1, 0);\n dp[0] = 1;\n \n vector<vector<int>> count(n, vector<int>(26, 0));\n for (const string& word : words) {\n for (int i = 0; i < n; i++) {\n count[i][word[i] - \'a\']++;\n }\n }\n \n for (int i = 0; i < n; i++) {\n for (int j = m-1; j >= 0; j--) {\n dp[j+1] += (int)((long)dp[j] * count[i][target[j] - \'a\'] % mod);\n dp[j+1] %= mod;\n }\n }\n \n return dp[m];\n }\n};\n```\n```Java []\nclass Solution {\n public int numWays(String[] words, String target) {\n int n = words[0].length();\n int m = target.length();\n int mod = 1000000007;\n int[] dp = new int[m+1];\n dp[0] = 1;\n \n int[][] count = new int[n][26];\n for (String word : words) {\n for (int i = 0; i < n; i++) {\n count[i][word.charAt(i) - \'a\']++;\n }\n }\n \n for (int i = 0; i < n; i++) {\n for (int j = m-1; j >= 0; j--) {\n dp[j+1] += (int)((long)dp[j] * count[i][target.charAt(j) - \'a\'] % mod);\n dp[j+1] %= mod;\n }\n }\n \n return dp[m];\n }\n}\n```\n```Python []\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n n = len(words[0])\n m = len(target)\n mod = 10**9 + 7\n dp = [0] * (m+1)\n dp[0] = 1\n \n count = [[0] * 26 for _ in range(n)]\n for i in range(n):\n for word in words:\n count[i][ord(word[i]) - ord(\'a\')] += 1\n \n for i in range(n):\n for j in range(m-1, -1, -1):\n dp[j+1] += dp[j] * count[i][ord(target[j]) - ord(\'a\')]\n dp[j+1] %= mod\n \n return dp[m]\n```\n | 86,828 |
Number of Ways to Form a Target String Given a Dictionary | number-of-ways-to-form-a-target-string-given-a-dictionary | You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. | Array,String,Dynamic Programming | Hard | For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array, | 691 | 9 | ```cpp\nclass Solution {\npublic:\n int numWays(vector<string>& words, string target) {\n int M = 1e9 + 7, n = words[0].size(), m = target.size();\n vector<vector<long long>> dp(n, vector<long long>(m, -1));\n vector<vector<long long>> cnt(n, vector<long long>(26));\n // count character frequency for each j-th column\n for (int i = 0; i < words.size(); i++) {\n for (int j = 0; j < n; j++) {\n cnt[j][words[i][j] - \'a\']++;\n }\n }\n function<int(int,int)> dfs = [&](int i, int j) {\n // reach end of target\n if (j == m) return 1;\n // reach end of words\n if (i == n) return 0;\n if (dp[i][j] != -1) return (int) dp[i][j];\n // skip i-th character\n int res = dfs(i + 1, j), c = target[j] - \'a\';\n if (cnt[i][c]) res = (res + cnt[i][c] * dfs(i + 1, j + 1)) % M;\n // memoize the result\n return (int) (dp[i][j] = res);\n };\n return dfs(0, 0);\n }\n};\n```\n\n```py\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n M = 10 ** 9 + 7\n n, m = len(words[0]), len(target)\n cnt = [[0] * 26 for _ in range(n)]\n # count character frequency for each j-th column\n for i in range(len(words)):\n for j in range(n):\n cnt[j][ord(words[i][j]) - ord(\'a\')] += 1\n @lru_cache(None)\n def dfs(i, j):\n # reach target\n if j == m:\n return 1\n # reach the end of the word\n if i == n:\n return 0\n # not take\n res = dfs(i + 1, j)\n # take\n c = ord(target[j]) - ord(\'a\')\n if cnt[i][c] > 0:\n res += cnt[i][c] * dfs(i + 1, j + 1)\n return res % M\n return dfs(0, 0)\n``` | 86,829 |
Number of Ways to Form a Target String Given a Dictionary | number-of-ways-to-form-a-target-string-given-a-dictionary | You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. | Array,String,Dynamic Programming | Hard | For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array, | 4,513 | 44 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n >The idea is to use dynamic programming to calculate the number of ways to form the target string using the frequency of each character in each column of the matrix. We can keep track of the frequency of each character in each column of the matrix and then use a dp array to store the number of ways to form the prefix of target with the characters in the first i columns of the matrix. At each step, we can use the frequency array to calculate the number of ways to add the next character of the target to the prefix using the ith column of the matrix.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n>1. Calculate the frequency of each character in each column of the matrix using a 2D frequency array.\n\n> 2. Initialize a 2D dp array with dp[i][j] = number of ways to form the prefix of target with length j using the first i columns of the matrix.\n\n> 3. Initialize dp[0][0] = 1 to account for the empty prefix.\n \n> 4. Use a nested loop to iterate over the columns and characters of the matrix and target string respectively.\n \n> 5. Calculate the number of times the current character of the target appears in the current column of the matrix using the frequency array.\n \n> 6. Update the dp array at each step using the recurrence relation dp[i][j] = dp[i-1][j] + charCount * dp[i-1][j-1], where charCount is the number of times the current character appears in the current column.\n \n> 7. Return dp[n][target.length()], where n is the number of columns in the matrix.\n\n# Complexity\n>- Time complexity:\n >$$O(nm|target|)$$, where n is the number of columns in the matrix, m is the length of each word in the matrix, and |target| is the length of the target string.\n\n\n\n\n> - Space complexity:\n>Space complexity: $$O(n*|target|)$$, for the dp array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n![image.png]()\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n# Code\n``` Java []\nclass Solution {\n public int numWays(String[] words, String target) {\n int mod = 1000000007;\n int n = words[0].length();\n int[][] freq = new int[n][26]; // freq[i][j] = frequency of j+\'a\' in the ith column of the matrix\n \n for (int i = 0; i < words.length; i++) {\n for (int j = 0; j < n; j++) {\n freq[j][words[i].charAt(j) - \'a\']++;\n }\n }\n \n int[][] dp = new int[n+1][target.length()+1]; // dp[i][j] = number of ways to form the prefix of target with length j using the first i columns of the matrix\n \n for (int i = 0; i <= n; i++) {\n dp[i][0] = 1;\n }\n \n for (int i = 1; i <= n; i++) {\n for (int j = 1; j <= target.length(); j++) {\n int charCount = freq[i-1][target.charAt(j-1) - \'a\'];\n dp[i][j] = (dp[i-1][j] + (int)((long)charCount * dp[i-1][j-1] % mod)) % mod;\n }\n }\n \n return dp[n][target.length()];\n }\n}\n\n```\n```python []\nclass Solution(object):\n def numWays(self, words, target):\n """\n :type words: List[str]\n :type target: str\n :rtype: int\n """\n mod = 10**9 + 7\n m, n = len(words), len(words[0])\n \n # frequency array for each character in each column\n freq = [[0] * 26 for _ in range(n)]\n for j in range(n):\n for i in range(m):\n freq[j][ord(words[i][j]) - ord(\'a\')] += 1\n \n # dp array to store the number of ways to form the prefix of target\n dp = [1] + [0] * len(target)\n \n # fill dp array from left to right\n for j in range(n):\n for i in range(len(target), 0, -1):\n dp[i] += dp[i-1] * freq[j][ord(target[i-1]) - ord(\'a\')]\n dp[i] %= mod\n \n return dp[len(target)]\n```\n```C++ []\nclass Solution {\npublic:\n int numWays(vector<string>& words, string target) {\n int mod = 1e9 + 7;\n int m = words.size(), n = words[0].size();\n \n // frequency array for each character in each column\n vector<vector<int>> freq(n, vector<int>(26, 0));\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < m; i++) {\n freq[j][words[i][j] - \'a\']++;\n }\n }\n \n // dp array to store the number of ways to form the prefix of target\n vector<long long> dp(target.size() + 1, 0);\n dp[0] = 1;\n \n // fill dp array from left to right\n for (int j = 0; j < n; j++) {\n for (int i = target.size(); i > 0; i--) {\n dp[i] = (dp[i] + dp[i-1] * freq[j][target[i-1] - \'a\']) % mod;\n }\n }\n \n return dp[target.size()];\n }\n};\n```\n\n```JavaScript []\n/**\n * @param {string[]} words\n * @param {string} target\n * @return {number}\n */\nvar numWays = function(words, target) {\n const mod = 1e9 + 7;\n const m = words.length;\n const n = words[0].length;\n \n // frequency array for each character in each column\n const freq = Array.from({ length: n }, () => Array(26).fill(0));\n for (let j = 0; j < n; j++) {\n for (let i = 0; i < m; i++) {\n freq[j][words[i].charCodeAt(j) - 97]++;\n }\n }\n \n // dp array to store the number of ways to form the prefix of target\n const dp = Array(target.length + 1).fill(0);\n dp[0] = 1;\n \n // fill dp array from left to right\n for (let j = 0; j < n; j++) {\n for (let i = target.length; i > 0; i--) {\n dp[i] += dp[i-1] * freq[j][target.charCodeAt(i-1) - 97];\n dp[i] %= mod;\n }\n }\n \n return dp[target.length];\n};\n\n```\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n``` | 86,830 |
Number of Ways to Form a Target String Given a Dictionary | number-of-ways-to-form-a-target-string-given-a-dictionary | You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rules: Notice that you can use multiple characters from the same string in words provided the conditions above are met. Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7. | Array,String,Dynamic Programming | Hard | For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array, | 435 | 10 | If you\'ve done it this way, you\'re almost there!\n```\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n @cache\n def dfs(i, k):\n if i == T: # ran out of chars in target\n return 1 # 1 way\n if k == W: # ran out of chars in word[j]\n return 0\n \n ways = 0\n for j in range(N): # loop over words\n for x in range(k, W): # loop over chars in words\n if words[j][x] == target[i]:\n ways += dfs(i + 1, x + 1)\n return ways\n \n N = len(words)\n W = len(words[0])\n T = len(target)\n return dfs(0, 0) % (10 ** 9 + 7)\n```\nThis obviously will TLE.\nWe need to replace N\\*W loop with something O(1) or O(logn).\nInstead of Running N\\*W again and again we can precompute `char count @ pos in words` and then\n`dfs(i + 1, k + 1) * char_count_@_pos`.\n```\nchar_pos_count = [[0] * W for _ in range(26)]\nfor w in words:\n for pos,c in enumerate(w):\n char_pos_count[ord(c) - 97][pos] += 1\n```\nThis way we get O(1) for the same 2 loops.\n\n---\nThere was a quesiton: *How does it work?*\nAnswer:\nAn example:\ntarget:\n`abc`\ninput words:\n1.`a...`\n2.`a...`\n3.`a...`\n4.`a...`\n...\n100.`a...`\n\nNow imagine you need to calculate how many ways you can form `a` from input words.\nIn brute force you will first find that you have target[0] = `a`. Next you need to find all `a` in the words. How will you do it? Loop over word[j][0] and count all found `a`s.\nThis loop can be replaced with O(1) instead of O(#num_of_words) if we precalculate those `a` for each column in advance.\n\n---\nSource code for Top-Down -> 2D BU -> 1D BU:\n```\nclass Solution:\n def numWays(self, words: List[str], target: str) -> int:\n ### top-down\n @cache\n def dfs(i, k):\n if i == T:\n return 1\n if k == W:\n return 0\n \n char_idx = ord(target[i]) - 97\n ways = dfs(i, k + 1) # skip k-th idx in words\n if char_pos_count[char_idx][k]:\n ways += dfs(i + 1, k + 1) * char_pos_count[char_idx][k]\n return ways\n \n N = len(words)\n W = len(words[0])\n T = len(target)\n \n char_pos_count = [[0] * W for _ in range(26)]\n for w in words:\n for pos,c in enumerate(w):\n char_pos_count[ord(c) - 97][pos] += 1\n \n return dfs(0, 0) % (10 ** 9 + 7)\n\n # bottom-up 2d\n # precomputation copy + paste from top-down\n dp = [[0] * (W + 1) for _ in range(T + 1)]\n dp[T][W] = 1\n\n for k in reversed(range(W)):\n dp[T][k] = 1\n for i in reversed(range(T)):\n char_idx = ord(target[i]) - 97\n dp[i][k] = dp[i][k + 1] # skip k-th idx in words\n if char_pos_count[char_idx][k]:\n dp[i][k] += dp[i + 1][k + 1] * char_pos_count[char_idx][k]\n\n return dp[0][0] % (10 ** 9 + 7)\n\n # bottom-up 1d\n # precomputation copy + paste from top-down\n dp = [0] * (T + 1)\n dp[T] = 1\n\n for k in reversed(range(W)):\n for i in range(T):\n dp[i] += dp[i + 1] * char_pos_count[ord(target[i]) - 97][k]\n\n return dp[0] % (10 ** 9 + 7)\n``` | 86,848 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 1,268 | 13 | Memoize the first occurrence of a character. \n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = -1\n seen = {}\n for i, c in enumerate(s): \n if c in seen: ans = max(ans, i - seen[c] - 1)\n seen.setdefault(c, i)\n return ans \n``` | 86,871 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 1,385 | 17 | For each character `ch` that occurs in `s` one or more times the length of the longest contained substring equals to `s.rfind(ch) - s.find(ch) -1`. If a character occurs only once at position `x` this expression equals to ` x - x - 1 = -1`. The solution is largest of all longest contained substring lengths for the elements of `set(s)`:\n```\nclass SolutionI:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n return max(s.rfind(ch) - s.find(ch) - 1 for ch in set(s))\n```\n\nTime complexity: **O(n)**; Space complexity: **O(1)** | 86,873 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 478 | 6 | 1. Create a map to keep the first occurrence of the character in the string ```s```.\n2. If the next character is already on the map - we update the max distance.\n\nComplexity O(N) - one loop\nMemory: at first sight, it is also O(N). But if the number of characters is limited by the English alphabet, then to store the map we need only O(26) which is O(1).\n\n*Please upvote if you like for motivation and karma :)*\n\n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n \n charToID = dict()\n maxDist = -1\n \n for i, ch in enumerate(s):\n if ch not in charToID:\n charToID[ch] = i\n else:\n maxDist = max(maxDist, i - charToID[ch] -1)\n \n return maxDist\n``` | 86,876 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 685 | 8 | ```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = [-1]\n \n for i in set(s):\n if(s.count(i) >= 2):\n ans.append(s.rindex(i) - s.index(i) - 1 )\n \n return max(ans)\n``` | 86,877 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 894 | 6 | ```\nclass Solution(object):\n def maxLengthBetweenEqualCharacters(self, s):\n lastSeen = dict()\n maxDist = -1\n for index, char in enumerate(s):\n if char not in lastSeen:\n lastSeen[char] = index\n else:\n maxDist = max(index - lastSeen[char], maxDist)\n \n return maxDist - 1 if maxDist > -1 else -1\n \n``` | 86,888 |
Largest Substring Between Two Equal Characters | largest-substring-between-two-equal-characters | Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1. A substring is a contiguous sequence of characters within a string. | Hash Table,String | Easy | Try saving the first and last position of each character Try finding every pair of indexes with equal characters | 924 | 9 | ```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans \n``` | 86,889 |
Lexicographically Smallest String After Applying Operations | lexicographically-smallest-string-after-applying-operations | You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b. You can apply either of the following two operations any number of times and in any order on s: Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s. A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, "0158" is lexicographically smaller than "0190" because the first position they differ is at the third letter, and '5' comes before '9'. | String,Breadth-First Search | Medium | Since the length of s is even, the total number of possible sequences is at most 10 * 10 * s.length. You can generate all possible sequences and take their minimum. Keep track of already generated sequences so they are not processed again. | 657 | 9 | Traverse the whole graph via the two operations, and return the minimum string. \n\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n op1 = lambda s: "".join(str((int(c)+a)%10) if i&1 else c for i, c in enumerate(s))\n op2 = lambda s: s[-b:] + s[:-b]\n \n seen = set()\n stack = [s]\n while stack: \n s = stack.pop()\n seen.add(s)\n if (ss := op1(s)) not in seen: stack.append(ss)\n if (ss := op2(s)) not in seen: stack.append(ss)\n return min(seen)\n``` | 86,911 |
Slowest Key | slowest-key | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. | Array,String | Easy | Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer. | 925 | 10 | **Python :**\n\n```\ndef slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n\tkey = [keysPressed[0]]\n\tmax_dur = releaseTimes[0]\n\n\tfor i in range(1, len(releaseTimes)):\n\t\tif releaseTimes[i] - releaseTimes[i - 1] == max_dur:\n\t\t\tkey.append(keysPressed[i])\n\n\t\tif releaseTimes[i] - releaseTimes[i - 1] > max_dur:\n\t\t\tmax_dur = releaseTimes[i] - releaseTimes[i - 1]\n\t\t\tkey = [keysPressed[i]]\n\n\n\treturn max(key)\n```\n\n**Like it ? please upvote !** | 87,017 |
Slowest Key | slowest-key | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. | Array,String | Easy | Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer. | 649 | 7 | ```\nclass Solution:\n def slowestKey(self, r: List[int], k: str) -> str:\n times = {r[0]: [k[0]]}\n \n for i in range(1 , len(r)):\n t = r[i] - r[i - 1]\n if(t in times):\n times[t].append(k[i])\n else:\n times[t] = [k[i]]\n \n keys = times[max(times.keys())]\n \n return max(keys)\n``` | 87,022 |
Slowest Key | slowest-key | A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released. The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0]. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration. Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses. | Array,String | Easy | Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer. | 905 | 9 | ```\nclass Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n max_dur = releaseTimes[0]\n max_key = keysPressed[0]\n \n for i in range(1, len(releaseTimes)):\n if releaseTimes[i] - releaseTimes[i-1] > max_dur:\n max_dur = releaseTimes[i] - releaseTimes[i-1]\n max_key = keysPressed[i]\n elif releaseTimes[i] - releaseTimes[i-1] == max_dur and max_key < keysPressed[i]:\n max_key = keysPressed[i]\n \n return max_key \n```\t\t\n\t\t | 87,025 |
Arithmetic Subarrays | arithmetic-subarrays | A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: The following sequence is not arithmetic: You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. | Array,Sorting | Medium | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic. | 292 | 5 | # Code\n```js\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n return[all(arr[i+1]-arr[i]==arr[1]-arr[0]for i in range(len(arr)-1))for arr in[sorted(nums[a:b+1])for a,b in zip(l,r)]] \n```\n\n![](*-EcY1mOZ_fDmCFizJvsMkg.jpeg) | 87,049 |
Arithmetic Subarrays | arithmetic-subarrays | A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: The following sequence is not arithmetic: You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. | Array,Sorting | Medium | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic. | 5,690 | 29 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(With Sorting)***\n1. **check function:** Sorts the given array and checks if the elements form an arithmetic sequence by verifying if the difference between consecutive elements remains constant.\n1. **checkArithmeticSubarrays function:** Loops through the provided ranges `l` and `r` to extract subarrays from `nums`, then checks each subarray using the `check` function to determine if they form arithmetic sequences.\n1. **ans vector:** Stores the boolean results indicating whether each subarray is an arithmetic sequence or not.\n1. **Return:** Returns the vector containing results for each subarray\'s arithmetic sequence check.\n\n# Complexity\n- *Time complexity:*\n $$O(m\u22C5n\u22C5logn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n // Function to check if the given array forms an arithmetic sequence\n bool check(vector<int>& arr) {\n sort(arr.begin(), arr.end()); // Sort the array\n int diff = arr[1] - arr[0]; // Calculate the difference between the first two elements\n \n // Check if the difference remains the same for consecutive elements\n for (int i = 2; i < arr.size(); i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false; // If the difference changes, it\'s not an arithmetic sequence\n }\n }\n \n return true; // If all differences are the same, it\'s an arithmetic sequence\n }\n \n // Function to check arithmetic subarrays in the given range\n vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {\n vector<bool> ans; // Vector to store results\n \n // Iterate through the ranges and check each subarray\n for (int i = 0; i < l.size(); i++) {\n // Extract the subarray from nums using the given range [l[i], r[i]]\n vector<int> arr(begin(nums) + l[i], begin(nums) + r[i] + 1);\n ans.push_back(check(arr)); // Check if the subarray forms an arithmetic sequence\n }\n \n return ans; // Return the results for each subarray\n }\n};\n\n\n```\n```C []\nbool check(int arr[], int size) {\n // Sort the array\n // (Implementation of sorting is not provided here)\n\n int diff = arr[1] - arr[0]; // Calculate the difference between the first two elements\n \n // Check if the difference remains the same for consecutive elements\n for (int i = 2; i < size; i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false; // If the difference changes, it\'s not an arithmetic sequence\n }\n }\n\n return true; // If all differences are the same, it\'s an arithmetic sequence\n}\n\n// Function to check arithmetic subarrays in the given range\nvoid checkArithmeticSubarrays(int nums[], int numsSize, int l[], int r[], int queriesSize) {\n bool ans[queriesSize]; // Array to store results\n \n // Iterate through the ranges and check each subarray\n for (int i = 0; i < queriesSize; i++) {\n int subarraySize = r[i] - l[i] + 1;\n int arr[subarraySize]; // Create a subarray\n \n // Extract the subarray from nums using the given range [l[i], r[i]]\n int index = 0;\n for (int j = l[i]; j <= r[i]; j++) {\n arr[index++] = nums[j];\n }\n \n ans[i] = check(arr, subarraySize); // Check if the subarray forms an arithmetic sequence\n }\n \n // Printing the results\n for (int i = 0; i < queriesSize; i++) {\n if (ans[i]) {\n printf("true ");\n } else {\n printf("false ");\n }\n }\n printf("\\n");\n}\n\n\n```\n\n```Java []\nclass Solution {\n public Boolean check(int[] arr) {\n Arrays.sort(arr);\n int diff = arr[1] - arr[0];\n \n for (int i = 2; i < arr.length; i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false;\n }\n }\n \n return true;\n }\n \n public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List<Boolean> ans = new ArrayList();\n for (int i = 0; i < l.length; i++) {\n int[] arr = new int[r[i] - l[i] + 1];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = nums[l[i] + j];\n }\n \n ans.add(check(arr));\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\n\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n def check(arr):\n arr.sort()\n diff = arr[1] - arr[0]\n \n for i in range(2, len(arr)):\n if arr[i] - arr[i - 1] != diff:\n return False\n \n return True\n \n ans = []\n for i in range(len(l)):\n arr = nums[l[i] : r[i] + 1]\n ans.append(check(arr))\n \n return ans\n\n```\n```javascript []\nfunction check(arr) {\n arr.sort((a, b) => a - b); // Sort the array\n let diff = arr[1] - arr[0]; // Calculate the difference between the first two elements\n\n // Check if the difference remains the same for consecutive elements\n for (let i = 2; i < arr.length; i++) {\n if (arr[i] - arr[i - 1] !== diff) {\n return false; // If the difference changes, it\'s not an arithmetic sequence\n }\n }\n\n return true; // If all differences are the same, it\'s an arithmetic sequence\n}\n\nfunction checkArithmeticSubarrays(nums, l, r) {\n const ans = [];\n\n // Iterate through the ranges and check each subarray\n for (let i = 0; i < l.length; i++) {\n const arr = nums.slice(l[i], r[i] + 1); // Extract the subarray from nums using the given range [l[i], r[i]]\n ans.push(check(arr)); // Check if the subarray forms an arithmetic sequence\n }\n\n return ans; // Return the results for each subarray\n}\n\n```\n\n---\n\n#### ***Approach 2(Without Sorting)***\n1. **Libraries included:**\n\n - **<vector>:** To use the `vector` container for arrays.\n - **<unordered_set>:** To utilize an unordered set for efficient element lookup.\n - **<climits>:** For using `INT_MAX` and `INT_MIN` constants for integer limits.\n1. **Class Solution:**\n\n - Contains two methods:\n - **bool check(vector<int>& arr):** Checks if an array forms an arithmetic sequence.\n - **vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r):** Checks arithmetic subarrays in the given range.\n1. **bool check(vector<int>& arr) function:**\n\n - Calculates minimum and maximum elements in the array and stores them in `minElement` and `maxElement`.\n - Populates an `unordered_set` named `arrSet` with elements from the array `arr`.\n - Determines if the array elements can form an arithmetic sequence:\n - Computes the expected common difference diff if the elements are in an arithmetic sequence.\n - Validates the sequence by checking if the elements satisfy the arithmetic sequence condition:\n - Verifies the evenly spaced property using the modulus operation.\n - Validates if the expected elements are present by checking each one against the set.\n1. **vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) function:**\n\n - Iterates through the ranges defined by vectors `l` and `r`.\n - Extracts subarrays from `nums` based on the provided range.\n - Applies the `check` function to each subarray and stores the result in the `ans` vector.\n1. **Overall Process:**\n\n - The code first defines methods to verify if a given array is an arithmetic sequence and then applies this check to multiple subarrays within a range.\n\n# Complexity\n- *Time complexity:*\n $$O(m\u22C5n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n // Function to check if the given array forms an arithmetic sequence\n bool check(vector<int>& arr) {\n int minElement = INT_MAX; // Variable to store the minimum element in the array\n int maxElement = INT_MIN; // Variable to store the maximum element in the array\n unordered_set<int> arrSet; // Set to store elements of the array\n \n // Finding minimum and maximum elements and populating the set\n for (int num : arr) {\n minElement = min(minElement, num);\n maxElement = max(maxElement, num);\n arrSet.insert(num);\n }\n \n // Check if the elements can form an arithmetic sequence\n if ((maxElement - minElement) % (arr.size() - 1) != 0) {\n return false; // If not evenly spaced, it\'s not an arithmetic sequence\n }\n \n int diff = (maxElement - minElement) / (arr.size() - 1); // Calculate the common difference\n int curr = minElement + diff; // Initialize current element\n \n // Check for each expected element in the sequence\n while (curr < maxElement) {\n if (arrSet.find(curr) == arrSet.end()) {\n return false; // If any element is missing, it\'s not an arithmetic sequence\n }\n curr += diff; // Move to the next expected element\n }\n \n return true; // If all conditions satisfy, it\'s an arithmetic sequence\n }\n \n // Function to check arithmetic subarrays in the given range\n vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {\n vector<bool> ans; // Vector to store results\n \n // Iterate through the ranges and check each subarray\n for (int i = 0; i < l.size(); i++) {\n // Extract the subarray from nums using the given range [l[i], r[i]]\n vector<int> arr(begin(nums) + l[i], begin(nums) + r[i] + 1);\n ans.push_back(check(arr)); // Check if the subarray forms an arithmetic sequence\n }\n \n return ans; // Return the results for each subarray\n }\n};\n\n\n\n```\n```C []\n\nint check(int arr[], int size) {\n int minElement = INT_MAX; // Variable to store the minimum element in the array\n int maxElement = INT_MIN; // Variable to store the maximum element in the array\n int arrSet[MAX_SIZE] = {0}; // Array to store elements of the array\n \n // Finding minimum and maximum elements and populating the set\n for (int i = 0; i < size; i++) {\n minElement = (arr[i] < minElement) ? arr[i] : minElement;\n maxElement = (arr[i] > maxElement) ? arr[i] : maxElement;\n arrSet[arr[i]] = 1;\n }\n \n // Check if the elements can form an arithmetic sequence\n if ((maxElement - minElement) % (size - 1) != 0) {\n return 0; // If not evenly spaced, it\'s not an arithmetic sequence\n }\n \n int diff = (maxElement - minElement) / (size - 1); // Calculate the common difference\n int curr = minElement + diff; // Initialize current element\n \n // Check for each expected element in the sequence\n while (curr < maxElement) {\n if (arrSet[curr] == 0) {\n return 0; // If any element is missing, it\'s not an arithmetic sequence\n }\n curr += diff; // Move to the next expected element\n }\n \n return 1; // If all conditions satisfy, it\'s an arithmetic sequence\n}\n\n// Function to check arithmetic subarrays in the given range\nint* checkArithmeticSubarrays(int* nums, int* l, int* r, int size) {\n int* ans = (int*)malloc(size * sizeof(int)); // Array to store results\n \n // Iterate through the ranges and check each subarray\n for (int i = 0; i < size; i++) {\n int subArraySize = r[i] - l[i] + 1;\n int subArray[subArraySize];\n \n // Extract the subarray from nums using the given range [l[i], r[i]]\n for (int j = l[i], k = 0; j <= r[i]; j++, k++) {\n subArray[k] = nums[j];\n }\n \n ans[i] = check(subArray, subArraySize); // Check if the subarray forms an arithmetic sequence\n }\n \n return ans; // Return the results for each subarray\n}\n\n\n```\n\n```Java []\nclass Solution {\n public Boolean check(int[] arr) {\n int minElement = Integer.MAX_VALUE;\n int maxElement = Integer.MIN_VALUE;\n Set<Integer> arrSet = new HashSet();\n \n for (int num : arr) {\n minElement = Math.min(minElement, num);\n maxElement = Math.max(maxElement, num);\n arrSet.add(num);\n }\n \n if ((maxElement - minElement) % (arr.length - 1) != 0) {\n return false;\n }\n \n int diff = (maxElement - minElement) / (arr.length - 1);\n int curr = minElement + diff;\n \n while (curr < maxElement) {\n if (!arrSet.contains(curr)) {\n return false;\n }\n \n curr += diff;\n }\n \n return true;\n }\n \n public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List<Boolean> ans = new ArrayList();\n for (int i = 0; i < l.length; i++) {\n int[] arr = new int[r[i] - l[i] + 1];\n for (int j = 0; j < arr.length; j++) {\n arr[j] = nums[l[i] + j];\n }\n \n ans.add(check(arr));\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n def check(arr):\n min_element = min(arr)\n max_element = max(arr)\n\n if (max_element - min_element) % (len(arr) - 1) != 0:\n return False\n\n diff = (max_element - min_element) / (len(arr) - 1)\n \n arr_set = set(arr)\n curr = min_element + diff\n while curr < max_element:\n if curr not in arr_set:\n return False\n \n curr += diff\n \n return True\n\n ans = []\n for i in range(len(l)):\n arr = nums[l[i] : r[i] + 1]\n ans.append(check(arr))\n \n return ans\n\n\n```\n```javascript []\nclass Solution {\n check(arr) {\n let minElement = Number.MAX_SAFE_INTEGER; // Variable to store the minimum element in the array\n let maxElement = Number.MIN_SAFE_INTEGER; // Variable to store the maximum element in the array\n let arrSet = new Set(); // Set to store elements of the array\n \n // Finding minimum and maximum elements and populating the set\n arr.forEach(num => {\n minElement = Math.min(minElement, num);\n maxElement = Math.max(maxElement, num);\n arrSet.add(num);\n });\n \n // Check if the elements can form an arithmetic sequence\n if ((maxElement - minElement) % (arr.length - 1) !== 0) {\n return false; // If not evenly spaced, it\'s not an arithmetic sequence\n }\n \n let diff = (maxElement - minElement) / (arr.length - 1); // Calculate the common difference\n let curr = minElement + diff; // Initialize current element\n \n // Check for each expected element in the sequence\n while (curr < maxElement) {\n if (!arrSet.has(curr)) {\n return false; // If any element is missing, it\'s not an arithmetic sequence\n }\n curr += diff; // Move to the next expected element\n }\n \n return true; // If all conditions satisfy, it\'s an arithmetic sequence\n }\n \n checkArithmeticSubarrays(nums, l, r) {\n let ans = []; // Array to store results\n \n // Iterate through the ranges and check each subarray\n for (let i = 0; i < l.length; i++) {\n // Extract the subarray from nums using the given range [l[i], r[i]]\n let arr = nums.slice(l[i], r[i] + 1);\n ans.push(this.check(arr)); // Check if the subarray forms an arithmetic sequence\n }\n \n return ans; // Return the results for each subarray\n }\n}\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 87,051 |
Arithmetic Subarrays | arithmetic-subarrays | A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. For example, these are arithmetic sequences: The following sequence is not arithmetic: You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed. Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise. | Array,Sorting | Medium | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic. | 1,902 | 10 | When you\'re faced with a bunch of numbers and you want to know if they can make an arithmetic sequence, here\'s the drill: sort them.\n\nNow, when you get a query, it\'s like someone hands you a sub-array, a chunk of numbers in a certain order. Take that chunk, sort it out, and now you\'ve got a sorted sequence. The crucial part? Check if this sorted sequence is an arithmetic sequence. If it is, well, you\'ve cracked the code for that set of numbers.\n\nIt\'s a straightforward process\u2014 Just sort, check, and you\'re good to go.\n\n#### Cpp\n```cpp\nclass Solution {\npublic:\n bool check(vector<int>& arr){\n sort(arr.begin(), arr.end());\n int diff = arr[1] - arr[0];\n for(int i = 2; i<arr.size(); i++ ){\n if (arr[i] - arr[i-1] != diff) return false;\n }\n return true;\n }\n \n vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {\n vector<bool> ans;\n for(int i=0; i<l.size(); i++){\n vector<int> subarray(nums.begin() + l[i], nums.begin() + r[i] + 1); \n ans.push_back(check(subarray));\n }\n return ans;\n }\n};\n```\n\n#### Java\n```java\nclass Solution {\n public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List<Boolean> ans = new ArrayList<>();\n\n for (int i = 0; i < l.length; i++) {\n int[] subarray = Arrays.copyOfRange(nums, l[i], r[i] + 1);\n ans.add(check(subarray));\n }\n\n return ans;\n }\n\n private boolean check(int[] arr) {\n Arrays.sort(arr);\n int diff = arr[1] - arr[0];\n \n for (int i = 2; i < arr.length; i++) {\n if (arr[i] - arr[i - 1] != diff) {\n return false;\n }\n }\n \n return true;\n }\n}\n```\n\n#### Python\n```python\nclass Solution:\n def checkArithmeticSubarrays(self, nums, l, r):\n ans = []\n\n for i in range(len(l)):\n subarray = nums[l[i]: r[i] + 1]\n ans.append(self.check(subarray))\n\n return ans\n\n def check(self, arr):\n arr.sort()\n diff = arr[1] - arr[0]\n\n for i in range(2, len(arr)):\n if arr[i] - arr[i - 1] != diff:\n return False\n\n return True\n\n``` | 87,054 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 490 | 8 | # Intuition\r\nUsing min heap and BFS.\r\n\r\n---\r\n\r\n# Solution Video\r\n\r\n\r\n\r\nIn the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\r\n\r\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\r\n\r\n**\u25A0 Subscribe URL**\r\n\r\n\r\nSubscribers: 2,350\r\nThank you for your support!\r\n\r\n---\r\n\r\n# Approach\r\nThis is based on Python. Other might be different a bit.\r\n\r\n### Algorithm Overview:\r\n1. **Input Validation:**\r\n - Check if the input `heights` is empty. If it is, return 0 (no effort needed).\r\n\r\n2. **Initialization:**\r\n - Initialize variables: `rows`, `cols` to store the number of rows and columns in `heights`.\r\n - Create a min heap `min_heap` to store tuples (effort, row, col) starting with (0, 0, 0).\r\n - Initialize `max_effort` to 0, which stores the maximum effort encountered so far.\r\n - Create a set `visited` to keep track of visited cells.\r\n\r\n3. **Dijkstra\'s Algorithm using Heap:**\r\n - Begin a loop while the min heap is not empty:\r\n - Pop the tuple with the smallest effort from the min heap.\r\n - Update `max_effort` if the current effort is greater than `max_effort`.\r\n - If the current cell is the bottom-right cell, return `max_effort`.\r\n - Mark the current cell as visited.\r\n\r\n4. **Explore Neighbors:**\r\n - Iterate through the four directions (down, up, right, left):\r\n - Calculate the new row and column based on the current direction.\r\n - If the new cell is within the grid bounds and has not been visited:\r\n - Calculate the new effort for this step.\r\n - If the new effort is less than the effort for the current cell, update the heap and set `new_effort`.\r\n\r\n5. **Return Maximum Effort:**\r\n - If the bottom-right cell is not reached, return `max_effort`.\r\n\r\n### Detailed Explanation:\r\n1. **Input Validation:**\r\n - Check if `heights` is an empty list. If so, return 0 indicating no effort is needed.\r\n\r\n2. **Initialization:**\r\n - Get the number of rows `rows` and columns `cols` in the input grid.\r\n - Create a min heap `min_heap` and initialize `max_effort` to store the maximum effort encountered so far.\r\n - Create a set `visited` to keep track of visited cells.\r\n\r\n3. **Dijkstra\'s Algorithm using Heap:**\r\n - While the min heap is not empty:\r\n - Pop the tuple with the smallest effort from the min heap.\r\n - Update `max_effort` if the current effort is greater than `max_effort`.\r\n - If the current cell is the bottom-right cell, return `max_effort`.\r\n - Mark the current cell as visited.\r\n\r\n4. **Explore Neighbors:**\r\n - Iterate through the four directions (down, up, right, left):\r\n - Calculate the new row and column based on the current direction.\r\n - If the new cell is within the grid bounds and has not been visited:\r\n - Calculate the new effort for this step.\r\n - If the new effort is less than the effort for the current cell, update the heap and set `new_effort`.\r\n\r\n5. **Return Maximum Effort:**\r\n - If the bottom-right cell is not reached, return `max_effort`.\r\n\r\nThis algorithm uses Dijkstra\'s algorithm to find the path with the minimum effort. It explores cells in a priority-based manner, where the priority is the effort required to reach the cell. The min heap helps in efficiently selecting cells with the minimum effort.\r\n\r\n# Complexity\r\n\r\n### Time Complexity:\r\n- The main loop in Dijkstra\'s algorithm iterates until the min heap is empty or until reaching the bottom-right cell.\r\n- Extracting the minimum from the min heap (heapify) and pushing elements into the min heap takes O(log n) time, where n is the number of elements in the heap.\r\n- In the worst case, the min heap can contain all cells (rows * columns).\r\n\r\nTherefore, the overall time complexity is approximately `O((R * C) * log(R * C))`, where R is the number of rows and C is the number of columns in the grid. The log term arises from the heap operations.\r\n\r\n### Space Complexity:\r\n- The `min_heap` can have at most R * C elements, so the space complexity for the min heap is O(R * C) and `visited` also has (R * C) data.\r\n- Other variables (e.g., `max_effort`, `effort`, `cur_row`, `cur_col`, `new_row`, `new_col`, `new_effort`) and constants use O(1) additional space.\r\n\r\nTherefore, the overall space complexity is `O(R * C)` due to the min heap, where R is the number of rows and C is the number of columns in the grid.\r\n\r\n```python []\r\nclass Solution:\r\n def minimumEffortPath(self, heights):\r\n if not heights:\r\n return 0\r\n \r\n rows, cols = len(heights), len(heights[0])\r\n min_heap = [(0, 0, 0)] # (effort, row, col)\r\n max_effort = 0\r\n visited = set()\r\n\r\n while min_heap:\r\n effort, cur_row, cur_col = heapq.heappop(min_heap)\r\n\r\n max_effort = max(max_effort, effort)\r\n if (cur_row, cur_col) == (rows - 1, cols - 1):\r\n return max_effort\r\n visited.add((cur_row, cur_col))\r\n\r\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\r\n new_row, new_col = cur_row + dr, cur_col + dc\r\n\r\n if 0 <= new_row < rows and 0 <= new_col < cols and(new_row, new_col) not in visited:\r\n new_effort = abs(heights[new_row][new_col] - heights[cur_row][cur_col])\r\n heapq.heappush(min_heap, (new_effort, new_row, new_col))\r\n \r\n return max_effort\r\n```\r\n```javascript []\r\n/**\r\n * @param {number[][]} heights\r\n * @return {number}\r\n */\r\nvar minimumEffortPath = function(heights) {\r\n const rows = heights.length, cols = heights[0].length;\r\n const curEffort = Array.from(Array(rows), () => Array(cols).fill(Infinity));\r\n const minHeap = [[0, 0, 0]]; // [effort, row, col]\r\n \r\n curEffort[0][0] = 0;\r\n const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\n \r\n while (minHeap.length > 0) {\r\n const [effort, row, col] = minHeap.shift();\r\n \r\n if (effort > curEffort[row][col]) continue;\r\n \r\n if (row === rows - 1 && col === cols - 1) return effort;\r\n \r\n for (const [dr, dc] of directions) {\r\n const newRow = row + dr, newCol = col + dc;\r\n if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\r\n const newEffort = Math.max(effort, Math.abs(heights[row][col] - heights[newRow][newCol]));\r\n if (newEffort < curEffort[newRow][newCol]) {\r\n curEffort[newRow][newCol] = newEffort;\r\n minHeap.push([newEffort, newRow, newCol]);\r\n minHeap.sort((a, b) => a[0] - b[0]);\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n};\r\n```\r\n```java []\r\nclass Solution {\r\n public int minimumEffortPath(int[][] heights) {\r\n if (heights.length == 0) {\r\n return 0;\r\n }\r\n \r\n int rows = heights.length;\r\n int cols = heights[0].length;\r\n PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); // [effort, row, col]\r\n minHeap.offer(new int[]{0, 0, 0});\r\n int maxEffort = 0;\r\n Set<String> visited = new HashSet<>();\r\n\r\n while (!minHeap.isEmpty()) {\r\n int[] current = minHeap.poll();\r\n int effort = current[0];\r\n int curRow = current[1];\r\n int curCol = current[2];\r\n\r\n maxEffort = Math.max(maxEffort, effort);\r\n if (curRow == rows - 1 && curCol == cols - 1) {\r\n return maxEffort;\r\n }\r\n visited.add(curRow + "," + curCol);\r\n\r\n int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\r\n for (int[] direction : directions) {\r\n int newRow = curRow + direction[0];\r\n int newCol = curCol + direction[1];\r\n\r\n if (0 <= newRow && newRow < rows && 0 <= newCol && newCol < cols &&\r\n !visited.contains(newRow + "," + newCol)) {\r\n int newEffort = Math.abs(heights[newRow][newCol] - heights[curRow][curCol]);\r\n minHeap.offer(new int[]{newEffort, newRow, newCol});\r\n }\r\n }\r\n }\r\n \r\n return maxEffort; \r\n }\r\n}\r\n```\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int minimumEffortPath(vector<vector<int>>& heights) {\r\n if (heights.empty()) {\r\n return 0;\r\n }\r\n \r\n int rows = heights.size();\r\n int cols = heights[0].size();\r\n std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, std::greater<std::vector<int>>> minHeap; // {effort, row, col}\r\n minHeap.push({0, 0, 0});\r\n int maxEffort = 0;\r\n std::set<std::string> visited;\r\n\r\n while (!minHeap.empty()) {\r\n auto current = minHeap.top();\r\n minHeap.pop();\r\n int effort = current[0];\r\n int curRow = current[1];\r\n int curCol = current[2];\r\n\r\n maxEffort = std::max(maxEffort, effort);\r\n if (curRow == rows - 1 && curCol == cols - 1) {\r\n return maxEffort;\r\n }\r\n visited.insert(std::to_string(curRow) + "," + std::to_string(curCol));\r\n\r\n std::vector<std::vector<int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\r\n for (const auto& direction : directions) {\r\n int newRow = curRow + direction[0];\r\n int newCol = curCol + direction[1];\r\n\r\n if (0 <= newRow && newRow < rows && 0 <= newCol && newCol < cols &&\r\n visited.find(std::to_string(newRow) + "," + std::to_string(newCol)) == visited.end()) {\r\n int newEffort = std::abs(heights[newRow][newCol] - heights[curRow][curCol]);\r\n minHeap.push({newEffort, newRow, newCol});\r\n }\r\n }\r\n }\r\n \r\n return maxEffort; \r\n }\r\n};\r\n```\r\n | 87,100 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 14,288 | 95 | # Comprehensive Guide to Solving "Path With Minimum Effort": Conquering the Terrain Efficiently\r\n\r\n## Introduction & Problem Statement\r\n\r\nGreetings, algorithmic adventurers! Today\'s quest leads us through a matrix of heights, representing terrains that a hiker needs to cross. The task is to find the path that requires the minimum effort. The effort is calculated as the maximum absolute difference in heights between two consecutive cells of the route. Intriguing, isn\'t it?\r\n\r\n## Key Concepts and Constraints\r\n\r\n### What Makes This Problem Unique?\r\n\r\n1. **Graph Representation**: \r\n This problem can be mapped to a graph where each cell in the 2D matrix is a node. The edges connecting these nodes represent the "effort" required to move from one cell to another.\r\n\r\n2. **Variants of Shortest Path Algorithms**: \r\n The objective is similar to finding the shortest path, but with a different metric. We need to minimize the maximum absolute difference between adjacent nodes.\r\n\r\n3. **Constraints**: \r\n - $$1 \\leq \\text{rows, columns} \\leq 100$$\r\n - $$1 \\leq \\text{heights}[i][j] \\leq 10^6$$\r\n\r\n### Strategies to Tackle the Problem\r\n\r\n1. **Dijkstra\'s Algorithm**: \r\n A classic algorithm for finding the shortest path in a weighted graph, adapted for this problem.\r\n\r\n---\r\n\r\n## Live Coding Dijkstra\'s + Explain\r\n\r\n\r\n## Dijkstra\'s Algorithm Explained\r\n\r\n### What is Dijkstra\'s Algorithm?\r\n\r\nDijkstra\'s Algorithm is a classic graph algorithm that finds the shortest path from a source node to all other nodes in a weighted graph. In this case, the graph is represented by a 2D grid of cells, where each cell is a node and the edges between them represent the effort to move from one cell to another.\r\n\r\n### Mechanics of Dijkstra\'s Algorithm in "Path With Minimum Effort"\r\n\r\n1. **Initialize Priority Queue**: \r\n - The algorithm starts at the top-left corner (the source). The priority queue is initialized to store the effort needed to reach each cell from the source. The effort for the source itself is zero.\r\n\r\n2. **Distance Matrix**: \r\n - A 2D array keeps track of the minimum effort required to reach each cell. Initially, this is set to infinity for all cells except the source.\r\n\r\n3. **Iterate and Update Distances**: \r\n - The algorithm pops the cell with the smallest effort from the priority queue and explores its neighbors. The effort required to reach a neighbor is updated if a smaller effort is found.\r\n\r\n4. **Early Exit**: \r\n - The algorithm stops when it reaches the bottom-right corner, returning the effort required to get there.\r\n\r\n### Time and Space Complexity\r\n\r\n- **Time Complexity**: $$O(M \\times N \\log(M \\times N))$$, where $$M$$ and $$N$$ are the dimensions of the grid. This is primarily due to the operations on the priority queue.\r\n- **Space Complexity**: $$O(M \\times N)$$, needed for the distance matrix and the priority queue.\r\n\r\n# Code Dijkstra\r\n``` Python []\r\nclass Solution:\r\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\r\n rows, cols = len(heights), len(heights[0])\r\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\r\n dist = [[math.inf for _ in range(cols)] for _ in range(rows)]\r\n dist[0][0] = 0\r\n minHeap = [(0, 0, 0)] \r\n \r\n while minHeap:\r\n effort, x, y = heappop(minHeap)\r\n\r\n if x == rows - 1 and y == cols - 1:\r\n return effort\r\n \r\n for dx, dy in directions:\r\n nx, ny = x + dx, y + dy\r\n \r\n if 0 <= nx < rows and 0 <= ny < cols:\r\n new_effort = max(effort, abs(heights[x][y] - heights[nx][ny]))\r\n \r\n if new_effort < dist[nx][ny]:\r\n dist[nx][ny] = new_effort\r\n heappush(minHeap, (new_effort, nx, ny))\r\n```\r\n``` Rust []\r\nuse std::collections::BinaryHeap;\r\nuse std::cmp::Reverse;\r\n\r\nimpl Solution {\r\n pub fn minimum_effort_path(heights: Vec<Vec<i32>>) -> i32 {\r\n let rows = heights.len();\r\n let cols = heights[0].len();\r\n let mut dist = vec![vec![i32::MAX; cols]; rows];\r\n let mut min_heap: BinaryHeap<Reverse<(i32, usize, usize)>> = BinaryHeap::new();\r\n \r\n dist[0][0] = 0;\r\n min_heap.push(Reverse((0, 0, 0)));\r\n \r\n let directions = [(0, 1), (0, -1), (1, 0), (-1, 0)];\r\n \r\n while let Some(Reverse((effort, x, y))) = min_heap.pop() {\r\n if effort > dist[x][y] {\r\n continue;\r\n }\r\n if x == rows - 1 && y == cols - 1 {\r\n return effort;\r\n }\r\n for (dx, dy) in directions.iter() {\r\n let nx = (x as i32 + dx) as usize;\r\n let ny = (y as i32 + dy) as usize;\r\n if nx < rows && ny < cols {\r\n let new_effort = std::cmp::max(effort, (heights[x][y] - heights[nx][ny]).abs());\r\n if new_effort < dist[nx][ny] {\r\n dist[nx][ny] = new_effort;\r\n min_heap.push(Reverse((new_effort, nx, ny)));\r\n }\r\n }\r\n }\r\n }\r\n -1\r\n }\r\n}\r\n```\r\n``` Go []\r\ntype Item struct {\r\n\teffort, x, y int\r\n}\r\n\r\ntype PriorityQueue []Item\r\n\r\nfunc (pq PriorityQueue) Len() int { return len(pq) }\r\n\r\nfunc (pq PriorityQueue) Less(i, j int) bool {\r\n\treturn pq[i].effort < pq[j].effort\r\n}\r\n\r\nfunc (pq PriorityQueue) Swap(i, j int) {\r\n\tpq[i], pq[j] = pq[j], pq[i]\r\n}\r\n\r\nfunc (pq *PriorityQueue) Push(x interface{}) {\r\n\t*pq = append(*pq, x.(Item))\r\n}\r\n\r\nfunc (pq *PriorityQueue) Pop() interface{} {\r\n\told := *pq\r\n\tn := len(old)\r\n\titem := old[n-1]\r\n\t*pq = old[0 : n-1]\r\n\treturn item\r\n}\r\n\r\nfunc minimumEffortPath(heights [][]int) int {\r\n\trows, cols := len(heights), len(heights[0])\r\n\tdist := make([][]int, rows)\r\n\tfor i := range dist {\r\n\t\tdist[i] = make([]int, cols)\r\n\t\tfor j := range dist[i] {\r\n\t\t\tdist[i][j] = math.MaxInt32\r\n\t\t}\r\n\t}\r\n\tdist[0][0] = 0\r\n\tdirections := [][2]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}\r\n\r\n\tpq := &PriorityQueue{Item{0, 0, 0}}\r\n\theap.Init(pq)\r\n\r\n\tfor pq.Len() > 0 {\r\n\t\titem := heap.Pop(pq).(Item)\r\n\t\teffort, x, y := item.effort, item.x, item.y\r\n\t\tif effort > dist[x][y] {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tif x == rows-1 && y == cols-1 {\r\n\t\t\treturn effort\r\n\t\t}\r\n\t\tfor _, dir := range directions {\r\n\t\t\tnx, ny := x+dir[0], y+dir[1]\r\n\t\t\tif nx >= 0 && nx < rows && ny >= 0 && ny < cols {\r\n\t\t\t\tnewEffort := int(math.Max(float64(effort), math.Abs(float64(heights[x][y]-heights[nx][ny]))))\r\n\t\t\t\tif newEffort < dist[nx][ny] {\r\n\t\t\t\t\tdist[nx][ny] = newEffort\r\n\t\t\t\t\theap.Push(pq, Item{newEffort, nx, ny})\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1\r\n}\r\n```\r\n``` C++ []\r\nclass Solution {\r\npublic:\r\n int minimumEffortPath(vector<vector<int>>& heights) {\r\n int rows = heights.size(), cols = heights[0].size();\r\n vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX));\r\n priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> minHeap;\r\n minHeap.emplace(0, 0, 0);\r\n dist[0][0] = 0;\r\n \r\n int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\r\n \r\n while (!minHeap.empty()) {\r\n auto [effort, x, y] = minHeap.top();\r\n minHeap.pop();\r\n \r\n if (effort > dist[x][y]) continue;\r\n \r\n if (x == rows - 1 && y == cols - 1) return effort;\r\n \r\n for (auto& dir : directions) {\r\n int nx = x + dir[0], ny = y + dir[1];\r\n if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {\r\n int new_effort = max(effort, abs(heights[x][y] - heights[nx][ny]));\r\n if (new_effort < dist[nx][ny]) {\r\n dist[nx][ny] = new_effort;\r\n minHeap.emplace(new_effort, nx, ny);\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n }\r\n};\r\n```\r\n``` Java []\r\npublic class Solution {\r\n public int minimumEffortPath(int[][] heights) {\r\n int rows = heights.length, cols = heights[0].length;\r\n int[][] dist = new int[rows][cols];\r\n PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));\r\n minHeap.add(new int[]{0, 0, 0});\r\n \r\n for (int i = 0; i < rows; i++) {\r\n for (int j = 0; j < cols; j++) {\r\n dist[i][j] = Integer.MAX_VALUE;\r\n }\r\n }\r\n dist[0][0] = 0;\r\n \r\n int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\r\n \r\n while (!minHeap.isEmpty()) {\r\n int[] top = minHeap.poll();\r\n int effort = top[0], x = top[1], y = top[2];\r\n \r\n if (effort > dist[x][y]) continue;\r\n \r\n if (x == rows - 1 && y == cols - 1) return effort;\r\n \r\n for (int[] dir : directions) {\r\n int nx = x + dir[0], ny = y + dir[1];\r\n if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {\r\n int new_effort = Math.max(effort, Math.abs(heights[x][y] - heights[nx][ny]));\r\n if (new_effort < dist[nx][ny]) {\r\n dist[nx][ny] = new_effort;\r\n minHeap.add(new int[]{new_effort, nx, ny});\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n }\r\n}\r\n```\r\n``` C# []\r\npublic class Solution {\r\n public int MinimumEffortPath(int[][] heights) {\r\n int rows = heights.Length, cols = heights[0].Length;\r\n int[,] dist = new int[rows, cols];\r\n var minHeap = new SortedSet<(int effort, int x, int y)>();\r\n minHeap.Add((0, 0, 0));\r\n \r\n for (int i = 0; i < rows; i++) {\r\n for (int j = 0; j < cols; j++) {\r\n dist[i, j] = int.MaxValue;\r\n }\r\n }\r\n dist[0, 0] = 0;\r\n \r\n int[][] directions = new int[][] { new int[]{ 0, 1 }, new int[]{ 0, -1 }, new int[]{ 1, 0 }, new int[]{ -1, 0 }};\r\n \r\n while (minHeap.Count > 0) {\r\n var (effort, x, y) = minHeap.Min;\r\n minHeap.Remove(minHeap.Min);\r\n \r\n if (effort > dist[x, y]) continue;\r\n \r\n if (x == rows - 1 && y == cols - 1) return effort;\r\n \r\n foreach (var dir in directions) {\r\n int nx = x + dir[0], ny = y + dir[1];\r\n if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {\r\n int new_effort = Math.Max(effort, Math.Abs(heights[x][y] - heights[nx][ny]));\r\n if (new_effort < dist[nx, ny]) {\r\n dist[nx, ny] = new_effort;\r\n minHeap.Add((new_effort, nx, ny));\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n }\r\n}\r\n```\r\n``` JavaScript []\r\n/**\r\n * @param {number[][]} heights\r\n * @return {number}\r\n */\r\nvar minimumEffortPath = function(heights) {\r\n const rows = heights.length, cols = heights[0].length;\r\n const dist = Array.from(Array(rows), () => Array(cols).fill(Infinity));\r\n const minHeap = [[0, 0, 0]]; // [effort, x, y]\r\n \r\n dist[0][0] = 0;\r\n const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\n \r\n while (minHeap.length > 0) {\r\n const [effort, x, y] = minHeap.shift();\r\n \r\n if (effort > dist[x][y]) continue;\r\n \r\n if (x === rows - 1 && y === cols - 1) return effort;\r\n \r\n for (const [dx, dy] of directions) {\r\n const nx = x + dx, ny = y + dy;\r\n if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {\r\n const newEffort = Math.max(effort, Math.abs(heights[x][y] - heights[nx][ny]));\r\n if (newEffort < dist[nx][ny]) {\r\n dist[nx][ny] = newEffort;\r\n minHeap.push([newEffort, nx, ny]);\r\n minHeap.sort((a, b) => a[0] - b[0]);\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n};\r\n```\r\n``` PHP []\r\nclass Solution {\r\n\r\n function minimumEffortPath($heights) {\r\n $rows = count($heights);\r\n $cols = count($heights[0]);\r\n $dist = array_fill(0, $rows, array_fill(0, $cols, PHP_INT_MAX));\r\n \r\n $minHeap = new SplPriorityQueue();\r\n $minHeap->insert([0, 0, 0], 0);\r\n \r\n $dist[0][0] = 0;\r\n $directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];\r\n \r\n while (!$minHeap->isEmpty()) {\r\n list($effort, $x, $y) = $minHeap->extract();\r\n \r\n if ($effort > $dist[$x][$y]) continue;\r\n \r\n if ($x === $rows - 1 && $y === $cols - 1) return $effort;\r\n \r\n foreach ($directions as $dir) {\r\n list($dx, $dy) = $dir;\r\n $nx = $x + $dx;\r\n $ny = $y + $dy;\r\n \r\n if ($nx >= 0 && $nx < $rows && $ny >= 0 && $ny < $cols) {\r\n $newEffort = max($effort, abs($heights[$x][$y] - $heights[$nx][$ny]));\r\n if ($newEffort < $dist[$nx][$ny]) {\r\n $dist[$nx][$ny] = $newEffort;\r\n $minHeap->insert([$newEffort, $nx, $ny], -$newEffort);\r\n }\r\n }\r\n }\r\n }\r\n return -1;\r\n }\r\n}\r\n```\r\n\r\n## Performance\r\n\r\n| Language | Algorithm | Time (ms) | Memory (MB) |\r\n|-------------|-----------|-----------|-------------|\r\n| Rust | Dijkstra | 22 | 2.4 |\r\n| Java | Dijkstra | 40 | 44.4 |\r\n| Go | Dijkstra | 73 | 7.7 |\r\n| C++ | Dijkstra | 111 | 20.5 |\r\n| JavaScript | Dijkstra | 152 | 51.9 |\r\n| PHP | Dijkstra | 191 | 22.6 |\r\n| C# | Dijkstra | 261 | 65 |\r\n| Python3 | Dijkstra | 515 | 17.8 |\r\n\r\n![p4.png]()\r\n\r\n\r\n## Code Highlights and Best Practices\r\n\r\n- Dijkstra\'s algorithm is straightforward to implement and can be optimized using a 2D array for storing distances.\r\n\r\nMastering these algorithms will not only help you solve this particular problem but will also give you tools that are highly applicable in various domains. So, are you ready to find the path with minimum effort? Let\'s do it! | 87,108 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 7,283 | 59 | # Problem Description\r\nYou are a hiker preparing for an upcoming hike and need to plan your route efficiently. Given a 2D array of heights representing the elevation of each cell, your objective is to find the path from the **top-left** cell to the **bottom-right** cell with the **minimum** effort for the whole path.\r\nThe **effort** of a route is defined as the **maximum** absolute difference in heights between **two consecutive** cells along the path. Your goal is to determine the **minimum** effort needed to traverse from the **starting** point to the **destination** in this manner.\r\n\r\n- Constraints:\r\n - `rows == heights.length`\r\n - `columns == heights[i].length`\r\n - `1 <= rows, columns <= 100`\r\n - `1 <= heights[i][j] <= 10e6`\r\n \r\n\r\n---\r\n\r\n\r\n\r\n# Intuition\r\nHello There\uD83D\uDE00\r\nLet\'s take a look on our interesting problem\uD83D\uDE80\r\nOur problem says that we have matrix `M * N` of cells and each cell has some value of **height**.\r\nour goal is to find the path that has **minimum** effort for the `top-left` cell to the `bottom-right` cell.\r\n- Let\'s focus on **two important** things:\r\n - We want to find a **path** between two cells.\r\n - We want to **minimize** some obejective.\r\n\r\n## Dijkstra\'s Algorithm\r\nIt looks something that **Dijkstra\'s Algorithm** can solve !\r\n\r\nBut what is **DIJKSTRA** ?!!\r\nDijkstra\'s Algorithm is an algorithm to find the **shortest** path between two nodes in a **graph** or two cells in a **matrix** like our problem. \r\nIt\'s part of a **family** of algorithms designed to uncover the shortest path between nodes or cells **like** BFS, Bellman-Ford Algorithm, Floyd-Warsahll Algorithm. Each algorithm has its **unique** applications.\r\n- Let\'s focus on Dijkstra\'s Algorithm:\r\n - **Nature:** It\'s a single-source, multiple-destination algorithm. In simpler terms, it pinpoints the shortest path from a starting node to any other node in our graph.\r\n - **Constraints:** Dijkstra\'s Algorithm is suitable for graphs or problems featuring positive weights. If we encounter negative weights, we\'d choose alternative algorithms such as Bellman-Ford.\r\n \r\nAnd there you have it! Dijkstra\'s Algorithm is the **key** to our problem, well-known for tackling precisely these types of challenges.\r\n\r\n\r\n## Binary Search\r\nAnother **interesting** approach to solve this problem is to use **binary search**. But how? What if we shift our **perspective** a bit?\r\n\r\nI put it in this post because I found it a **unique** solution to a problem that we can solve using Dijkstra\'s Algorithm. \r\n\r\nInstead of focusing solely on finding the **shortest** path between the starting and ending cells, let\'s consider **traversing** the entire matrix. We can approach this much like a **DFS** (Depth-First Search) like any other simple problem.\r\n\r\n**Picture** this: As we navigate through the matrix using **DFS**, we\'re mindful of this **effort limit**. The goal? To reach the end cell while ensuring that our **maximum** effort remains below this specified **limit**.\r\n\r\nNow, here comes the interesting part\u2014let\'s integrate **binary search** into this. We\'ll perform a binary search around this **limit effort** in our DFS traversal. By doing so, we can effectively hone in on the optimal effort threshold that guarantees our success in reaching the end cell. If we achieve this within the defined effort threshold, it indicates a **possibility** to reach the goal cell with an even **lower** effort.\r\n\r\nIn essence, this creative approach combines the power of binary search with **DFS**, enriching our problem-solving repertoire.\r\n\r\n---\r\n\r\n\r\n# Proposed Approaches\r\n## Dijkstra\'s Algorithm\r\n### Steps\r\n- Create a 2D `effort` array and define **directional** **changes** using `dx` and `dy`.\r\n- Initialize cell `efforts` to **maximum** value.\r\n- Call **dijkstra** to find the **minimum** effort.\r\n- Initialize a `priority` queue to store (-effort, {x, y}) to make it return the **minimum** element.\r\n- Push the `top-left` cell into the queue with `initial` effort as `0`.\r\n- While the priority queue is **not empty**:\r\n - **Pop** the cell with the **least** effort.\r\n - If cost is **greater** than existing effort, **skip**.\r\n - If at **bottom-right** cell, **return minimum** effort.\r\n - **Explore** four directions, update efforts, and push to queue if lower effort found.\r\n- **Return** the minimum effort from top-left to bottom-right cell.\r\n\r\n### Complexity\r\n- **Time complexity:**$$O(M * N * log(M * N))$$\r\nThe time complexity for Dijkstra\'s Algorithm is `O(E * log(E))`, where `E` is the number of edges in the graph. In our case, we can consider the number of edges are `M * N`.\r\n- **Space complexity:**$$O(M * N)$$\r\nSince we are storing the minimum effort for the path from the starting point to each cell, then the space complexity is `O(M * N)`.\r\n\r\n---\r\n## Binary Search\r\n### Steps\r\n- **Create** a 2D array `visited` to track visited cells and define **directional changes** using `dx` and `dy`.\r\n- Set the **lower** and **upper** limits for `binary search`.\r\n- Perform `binary search` to find the minimum effort needed:\r\n - Use `DFS` to traverse the matrix within the effort **limits**.\r\n - **Update** the search **range** accordingly based on `DFS` results.\r\n- `Depth-First Search` (DFS) Function:\r\n - Mark the current cell as **visited**.\r\n - **Stop** if the bottom-right cell is reached.\r\n - **Explore** each direction (up, down, left, right):\r\n - Check if the new coordinates are within **bounds**.\r\n - Move to the next cell if the effort is within the specified **limit**.\r\n- Return **minimum** effort\r\n\r\n### Complexity\r\n- **Time complexity:**$$O(M * N * log(10^6))$$\r\nThe time complexity for **Binary Search** is `log(upper_bound - lower_bound)` and in our case the maximum range in `10^6`. and since we are doing **DFS** in each iteration knowing that the time complexity for the single **DFS** is O(N * M) then the total time complexity is `O(M * N * log(10^6))`.\r\n- **Space complexity:**$$O(M * N)$$\r\nSince we are storing the visited array for each cell and the **DFS** recursion stack complexity is also `O(M * N)`, then the space complexity is `O(M * N)`.\r\n\r\n\r\n---\r\n\r\n\r\n# Code\r\n## Dijkstra\'s Algorithm\r\n```C++ []\r\nclass Solution {\r\nprivate:\r\n int effort[105][105]; // Store effort for each cell\r\n int dx[4] = {0, 1, -1, 0}; // Changes in x coordinate for each direction\r\n int dy[4] = {1, 0, 0, -1}; // Changes in y coordinate for each direction\r\n\r\npublic:\r\n // Dijkstra\'s Algorithm to find minimum effort\r\n int dijkstra(vector<vector<int>>& heights) {\r\n int rows = heights.size();\r\n int cols = heights[0].size();\r\n\r\n // Priority queue to store {effort, {x, y}}\r\n std::priority_queue<std::pair<int, std::pair<int, int>>> pq;\r\n pq.push({0, {0, 0}}); // Start from the top-left cell\r\n effort[0][0] = 0; // Initial effort at the starting cell\r\n\r\n while (!pq.empty()) {\r\n auto current = pq.top().second;\r\n int cost = -pq.top().first; // Effort for the current cell\r\n pq.pop();\r\n\r\n int x = current.first;\r\n int y = current.second;\r\n\r\n // Skip if we\'ve already found a better effort for this cell\r\n if (cost > effort[x][y])\r\n continue;\r\n\r\n // Stop if we\'ve reached the bottom-right cell\r\n if (x == rows - 1 && y == cols - 1)\r\n return cost;\r\n\r\n // Explore each direction (up, down, left, right)\r\n for (int i = 0; i < 4; i++) {\r\n int new_x = x + dx[i];\r\n int new_y = y + dy[i];\r\n\r\n // Check if the new coordinates are within bounds\r\n if (new_x < 0 || new_x >= rows || new_y < 0 || new_y >= cols)\r\n continue;\r\n\r\n // Calculate new effort for the neighboring cell\r\n int new_effort = std::max(effort[x][y], std::abs(heights[x][y] - heights[new_x][new_y]));\r\n\r\n // Update effort if a lower effort is found for the neighboring cell\r\n if (new_effort < effort[new_x][new_y]) {\r\n effort[new_x][new_y] = new_effort;\r\n pq.push({-new_effort, {new_x, new_y}});\r\n }\r\n }\r\n }\r\n return effort[rows - 1][cols - 1]; // Minimum effort for the path to the bottom-right cell\r\n }\r\n\r\n // Function to find the minimum effort path\r\n int minimumEffortPath(vector<vector<int>>& heights) {\r\n // Initialize effort for each cell to maximum value\r\n for (int i = 0; i < heights.size(); i++) {\r\n for (int j = 0; j < heights[i].size(); j++) {\r\n effort[i][j] = INT_MAX;\r\n }\r\n }\r\n return dijkstra(heights); // Find minimum effort using dijkstra\r\n }\r\n};\r\n```\r\n```Java []\r\nclass Solution {\r\n private int[][] effort = new int[105][105]; // Store effort for each cell\r\n private int[] dx = {0, 1, -1, 0}; // Changes in x coordinate for each direction\r\n private int[] dy = {1, 0, 0, -1}; // Changes in y coordinate for each direction\r\n\r\n // Dijkstra\'s Algorithm to find minimum effort\r\n private int dijkstra(int[][] heights) {\r\n int rows = heights.length;\r\n int cols = heights[0].length;\r\n\r\n // Priority queue to store {effort, {x, y}}\r\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(-a[0], -b[0]));\r\n pq.add(new int[]{0, 0, 0}); // Start from the top-left cell\r\n effort[0][0] = 0; // Initial effort at the starting cell\r\n\r\n while (!pq.isEmpty()) {\r\n int[] current = pq.poll();\r\n int cost = -current[0]; // Effort for the current cell\r\n\r\n int x = current[1];\r\n int y = current[2];\r\n\r\n // Skip if we\'ve already found a better effort for this cell\r\n if (cost > effort[x][y])\r\n continue;\r\n\r\n // Stop if we\'ve reached the bottom-right cell\r\n if (x == rows - 1 && y == cols - 1)\r\n return cost;\r\n\r\n // Explore each direction (up, down, left, right)\r\n for (int i = 0; i < 4; i++) {\r\n int new_x = x + dx[i];\r\n int new_y = y + dy[i];\r\n\r\n // Check if the new coordinates are within bounds\r\n if (new_x < 0 || new_x >= rows || new_y < 0 || new_y >= cols)\r\n continue;\r\n\r\n // Calculate new effort for the neighboring cell\r\n int new_effort = Math.max(effort[x][y], Math.abs(heights[x][y] - heights[new_x][new_y]));\r\n\r\n // Update effort if a lower effort is found for the neighboring cell\r\n if (new_effort < effort[new_x][new_y]) {\r\n effort[new_x][new_y] = new_effort;\r\n pq.add(new int[]{-new_effort, new_x, new_y});\r\n }\r\n }\r\n }\r\n return effort[rows - 1][cols - 1]; // Minimum effort for the path to the bottom-right cell\r\n }\r\n\r\n // Function to find the minimum effort path\r\n public int minimumEffortPath(int[][] heights) {\r\n int rows = heights.length;\r\n int cols = heights[0].length;\r\n\r\n // Initialize effort for each cell to maximum value\r\n for (int i = 0; i < rows; i++) {\r\n Arrays.fill(effort[i], Integer.MAX_VALUE);\r\n }\r\n\r\n return dijkstra(heights); // Find minimum effort using dijkstra\r\n }\r\n}\r\n```\r\n```Python []\r\nclass Solution:\r\n def __init__(self):\r\n self.effort = [[float(\'inf\')] * 105 for _ in range(105)]\r\n self.dx = [0, 1, -1, 0]\r\n self.dy = [1, 0, 0, -1]\r\n\r\n def dijkstra(self, heights) -> int:\r\n rows = len(heights)\r\n cols = len(heights[0])\r\n\r\n pq = [(0, 0, 0)] # Priority queue to store (-effort, x, y)\r\n self.effort[0][0] = 0 # Initial effort at the starting cell\r\n\r\n while pq:\r\n cost, x, y = heapq.heappop(pq)\r\n\r\n # Skip if we\'ve already found a better effort for this cell\r\n if cost > self.effort[x][y]:\r\n continue\r\n\r\n # Stop if we\'ve reached the bottom-right cell\r\n if x == rows - 1 and y == cols - 1:\r\n return cost\r\n\r\n # Explore each direction (up, down, left, right)\r\n for i in range(4):\r\n new_x = x + self.dx[i]\r\n new_y = y + self.dy[i]\r\n\r\n # Check if the new coordinates are within bounds\r\n if not (0 <= new_x < rows and 0 <= new_y < cols):\r\n continue\r\n\r\n # Calculate new effort for the neighboring cell\r\n new_effort = max(self.effort[x][y], abs(heights[x][y] - heights[new_x][new_y]))\r\n\r\n # Update effort if a lower effort is found for the neighboring cell\r\n if new_effort < self.effort[new_x][new_y]:\r\n self.effort[new_x][new_y] = new_effort\r\n heapq.heappush(pq, (new_effort, new_x, new_y))\r\n\r\n return self.effort[rows - 1][cols - 1] # Minimum effort for the path to the bottom-right cell\r\n\r\n def minimumEffortPath(self, heights) -> int:\r\n rows = len(heights)\r\n cols = len(heights[0])\r\n\r\n # Initialize effort for each cell to maximum value\r\n for i in range(rows):\r\n for j in range(cols):\r\n self.effort[i][j] = float(\'inf\')\r\n\r\n return self.dijkstra(heights) # Find minimum effort using dijkstra\r\n```\r\n\r\n## Binary Search\r\n```C++ []\r\nclass Solution {\r\nprivate:\r\n bool visited[105][105]; // Visited cells tracker\r\n int directions_x[4] = {0, 1, -1, 0}; // Changes in x coordinate for four directions\r\n int directions_y[4] = {1, 0, 0, -1}; // Changes in y coordinate for four directions\r\n int numRows, numCols; // Number of rows and columns in the matrix\r\n\r\npublic:\r\n\r\n // Depth-First Search to explore the path with a given limit effort\r\n void dfs(int x, int y, int limitEffort, vector<vector<int>>& heights){\r\n if (visited[x][y])\r\n return;\r\n visited[x][y] = true;\r\n\r\n // Stop if we\'ve reached the bottom-right cell\r\n if (x == numRows - 1 && y == numCols - 1)\r\n return ;\r\n\r\n // Explore each direction (up, down, left, right)\r\n for (int i = 0; i < 4; i++) {\r\n int new_x = x + directions_x[i];\r\n int new_y = y + directions_y[i];\r\n\r\n // Check if the new coordinates are within bounds\r\n if (new_x < 0 || new_x >= numRows || new_y < 0 || new_y >= numCols)\r\n continue;\r\n \r\n // Go to next cell if the effort is within limit\r\n int newEffort = abs(heights[x][y] - heights[new_x][new_y]);\r\n if (newEffort <= limitEffort)\r\n dfs(new_x, new_y, limitEffort, heights);\r\n }\r\n }\r\n\r\n int minimumEffortPath(vector<vector<int>>& heights) {\r\n numRows = heights.size(); \r\n numCols = heights[0].size();\r\n\r\n // Bound for our binary search\r\n int lowerLimit = 0, upperLimit = 1e6;\r\n\r\n while (lowerLimit < upperLimit) {\r\n int mid = (upperLimit + lowerLimit) / 2;\r\n memset(visited, 0, sizeof visited);\r\n dfs(0, 0, mid, heights);\r\n\r\n if (visited[numRows - 1][numCols - 1])\r\n upperLimit = mid;\r\n else\r\n lowerLimit = mid + 1;\r\n }\r\n\r\n return lowerLimit;\r\n }\r\n};\r\n```\r\n```Java []\r\nclass Solution {\r\n private boolean[][] visited; // Visited cells tracker\r\n private int[] directions_x = {0, 1, -1, 0}; // Changes in x coordinate for four directions\r\n private int[] directions_y = {1, 0, 0, -1}; // Changes in y coordinate for four directions\r\n private int numRows, numCols; // Number of rows and columns in the matrix\r\n\r\n // Depth-First Search to explore the path with a given limit effort\r\n private void dfs(int x, int y, int limitEffort, int[][] heights) {\r\n if (visited[x][y])\r\n return;\r\n visited[x][y] = true;\r\n\r\n // Stop if we\'ve reached the bottom-right cell\r\n if (x == numRows - 1 && y == numCols - 1)\r\n return;\r\n\r\n // Explore each direction (up, down, left, right)\r\n for (int i = 0; i < 4; i++) {\r\n int new_x = x + directions_x[i];\r\n int new_y = y + directions_y[i];\r\n\r\n // Check if the new coordinates are within bounds\r\n if (new_x < 0 || new_x >= numRows || new_y < 0 || new_y >= numCols)\r\n continue;\r\n\r\n // Go to next cell if the effort is within limit\r\n int newEffort = Math.abs(heights[x][y] - heights[new_x][new_y]);\r\n if (newEffort <= limitEffort)\r\n dfs(new_x, new_y, limitEffort, heights);\r\n }\r\n }\r\n\r\n public int minimumEffortPath(int[][] heights) {\r\n numRows = heights.length;\r\n numCols = heights[0].length;\r\n\r\n // Initialize visited array\r\n visited = new boolean[numRows][numCols];\r\n\r\n // Bound for our binary search\r\n int lowerLimit = 0, upperLimit = 1_000_000;\r\n\r\n while (lowerLimit < upperLimit) {\r\n int mid = (upperLimit + lowerLimit) / 2;\r\n for (boolean[] row : visited) {\r\n Arrays.fill(row, false);\r\n }\r\n\r\n dfs(0, 0, mid, heights);\r\n\r\n if (visited[numRows - 1][numCols - 1])\r\n upperLimit = mid;\r\n else\r\n lowerLimit = mid + 1;\r\n }\r\n\r\n return lowerLimit;\r\n }\r\n}\r\n```\r\n```Python []\r\nclass Solution:\r\n def __init__(self):\r\n self.visited = [] # Visited cells tracker\r\n self.directions_x = [0, 1, -1, 0] # Changes in x coordinate for four directions\r\n self.directions_y = [1, 0, 0, -1] # Changes in y coordinate for four directions\r\n self.numRows = 0\r\n self.numCols = 0\r\n\r\n # Depth-First Search to explore the path with a given maximum effort\r\n def dfs(self, x, y, limit_effort, heights) -> None:\r\n if self.visited[x][y]:\r\n return\r\n self.visited[x][y] = True\r\n\r\n # Stop if we\'ve reached the bottom-right cell\r\n if x == self.numRows - 1 and y == self.numCols - 1:\r\n return\r\n\r\n # Explore each direction (up, down, left, right)\r\n for i in range(4):\r\n new_x = x + self.directions_x[i]\r\n new_y = y + self.directions_y[i]\r\n\r\n # Check if the new coordinates are within bounds\r\n if new_x < 0 or new_x >= self.numRows or new_y < 0 or new_y >= self.numCols:\r\n continue\r\n\r\n # Go to next cell if the effort is within maximum\r\n new_effort = abs(heights[x][y] - heights[new_x][new_y])\r\n if new_effort <= limit_effort:\r\n self.dfs(new_x, new_y, limit_effort, heights)\r\n\r\n def minimumEffortPath(self, heights) -> int:\r\n self.numRows = len(heights)\r\n self.numCols = len(heights[0])\r\n\r\n # Initialize visited array\r\n self.visited = [[False for _ in range(self.numCols)] for _ in range(self.numRows)]\r\n\r\n # Bound for our binary search\r\n lower_limit, upper_limit = 0, 1000000\r\n\r\n while lower_limit < upper_limit:\r\n mid = (upper_limit + lower_limit) // 2\r\n\r\n # Reset visited array\r\n self.visited = [[False for _ in range(self.numCols)] for _ in range(self.numRows)]\r\n\r\n self.dfs(0, 0, mid, heights)\r\n\r\n if self.visited[self.numRows - 1][self.numCols - 1]:\r\n upper_limit = mid\r\n else:\r\n lower_limit = mid + 1\r\n\r\n return lower_limit\r\n```\r\n\r\n\r\n![leet_sol.jpg]()\r\n\r\n | 87,124 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 1,806 | 30 | # We will use 2 Approach Please see the code->\uD83D\uDC47\n<!-- Describe your first thoughts on how to solve this problem. -->\n# **\u2714\uFE0F Solution 1: Dijikstra**\n\n- **If we observe, this problem is to find the shortest path from a source cell (0, 0) to a destination cell (m-1, n-1)**. Here, total path cost is defined as **maximum absolute difference in heights between two consecutive cells of the path.**\n- **Thus, we could use Dijikstra\'s algorithm** which is used to find the shortest path in a weighted graph with a slight modification of **criteria for the shortest path,** which costs **O(E log V)**, where E is number of edges **E = 4*M*N,** V is number of veritices **V = M*N**\n\n```C++ []\n#include <vector>\n#include <queue>\n#include <climits>\n\nclass Solution {\npublic:\n std::vector<int> DIR = {0, 1, 0, -1, 0};\n \n int minimumEffortPath(std::vector<std::vector<int>>& heights) {\n int m = heights.size();\n int n = heights[0].size();\n \n // Initialize a 2D array to store distances with max values.\n std::vector<std::vector<int>> dist(m, std::vector<int>(n, INT_MAX));\n \n // Create a min-heap to store distance, row, and column values.\n std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, std::greater<std::vector<int>>> minHeap;\n \n // Initialize the min heap with starting point (distance, row, col).\n minHeap.push({0, 0, 0});\n \n // Set the distance to the starting point as 0.\n dist[0][0] = 0;\n \n while (!minHeap.empty()) {\n std::vector<int> top = minHeap.top();\n minHeap.pop();\n \n int d = top[0];\n int r = top[1];\n int c = top[2];\n \n // If this is an outdated version, skip it.\n if (d > dist[r][c]) continue;\n \n // If we reach the bottom right, return the distance.\n if (r == m - 1 && c == n - 1) return d;\n \n // Explore neighboring cells.\n for (int i = 0; i < 4; i++) {\n int nr = r + DIR[i];\n int nc = c + DIR[i + 1];\n \n // Check if the neighbor is within bounds.\n if (nr >= 0 && nr < m && nc >= 0 && nc < n) {\n // Calculate the new distance.\n int newDist = std::max(d, std::abs(heights[nr][nc] - heights[r][c]));\n \n // If the new distance is smaller, update the distance and add to the heap.\n if (dist[nr][nc] > newDist) {\n dist[nr][nc] = newDist;\n minHeap.push({dist[nr][nc], nr, nc});\n }\n }\n }\n }\n \n return 0;\n }\n};\n\n```\n```Java []\nclass Solution {\n int[] DIR = new int[]{0, 1, 0, -1, 0};\n public int minimumEffortPath(int[][] heights) {\n int m = heights.length, n = heights[0].length;\n int[][] dist = new int[m][n];\n for (int i = 0; i < m; i++) Arrays.fill(dist[i], Integer.MAX_VALUE);\n \n PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n minHeap.offer(new int[]{0, 0, 0}); // distance, row, col\n dist[0][0] = 0;\n \n while (!minHeap.isEmpty()) {\n int[] top = minHeap.poll();\n int d = top[0], r = top[1], c = top[2];\n if (d > dist[r][c]) continue; // this is an outdated version -> skip it\n if (r == m - 1 && c == n - 1) return d; // Reach to bottom right\n for (int i = 0; i < 4; i++) {\n int nr = r + DIR[i], nc = c + DIR[i + 1];\n if (nr >= 0 && nr < m && nc >= 0 && nc < n) {\n int newDist = Math.max(d, Math.abs(heights[nr][nc] - heights[r][c]));\n if (dist[nr][nc] > newDist) {\n dist[nr][nc] = newDist;\n minHeap.offer(new int[]{dist[nr][nc], nr, nc});\n }\n }\n }\n }\n return 0; // Unreachable code, Java require to return interger value.\n }\n}\n```\n```Python []\nclass Solution(object):\n def minimumEffortPath(self, heights):\n m, n = len(heights), len(heights[0])\n dist = [[math.inf] * n for _ in range(m)]\n dist[0][0] = 0\n minHeap = [(0, 0, 0)] # distance, row, col\n DIR = [0, 1, 0, -1, 0]\n\n while minHeap:\n d, r, c = heappop(minHeap)\n if d > dist[r][c]: continue # this is an outdated version -> skip it\n if r == m - 1 and c == n - 1:\n return d # Reach to bottom right\n \n for i in range(4):\n nr, nc = r + DIR[i], c + DIR[i+1]\n if 0 <= nr < m and 0 <= nc < n:\n newDist = max(d, abs(heights[nr][nc] - heights[r][c]))\n if dist[nr][nc] > newDist:\n dist[nr][nc] = newDist\n heappush(minHeap, (dist[nr][nc], nr, nc))\n```\n\n---\n\n\n# Complexity\n\n- **Time: O(ElogV)** = O(M*N log M*N), where M <= 100 is the number of rows and N <= 100 is the number of columns in the matrix.\n- **Space: O(M*N)**\n\n---\n\n\n\n\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n\n# **\u2714\uFE0F Solution 2: Binary Search + DFS**\n\n- **Using binary search to choose a minimum threadshold so that we can found a route which absolute difference in heights between two consecutive cells of the route always less or equal to threadshold.**\n```C++ []\n#include <vector>\n\nclass Solution {\npublic:\n std::vector<int> DIR = {0, 1, 0, -1, 0};\n \n bool dfs(int r, int c, std::vector<std::vector<bool>>& visited, int threshold, const std::vector<std::vector<int>>& heights) {\n int m = heights.size();\n int n = heights[0].size();\n \n if (r == m - 1 && c == n - 1) return true; // Reach destination\n visited[r][c] = true;\n \n for (int i = 0; i < 4; i++) {\n int nr = r + DIR[i];\n int nc = c + DIR[i + 1];\n \n if (nr < 0 || nr == m || nc < 0 || nc == n || visited[nr][nc]) continue;\n \n if (std::abs(heights[nr][nc] - heights[r][c]) <= threshold && dfs(nr, nc, visited, threshold, heights)) {\n return true;\n }\n }\n return false;\n }\n \n int minimumEffortPath(std::vector<std::vector<int>>& heights) {\n int m = heights.size();\n int n = heights[0].size();\n \n int left = 0;\n int ans = 0;\n int right = 1e6;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false));\n \n if (dfs(0, 0, visited, mid, heights)) {\n right = mid - 1; // Try to find a better result on the left side\n ans = mid;\n } else {\n left = mid + 1;\n }\n }\n \n return ans;\n }\n};\n\n```\n```Java []\nclass Solution {\n private final int[] DIR = {0, 1, 0, -1, 0};\n \n private boolean dfs(int r, int c, boolean[][] visited, int threshold, int[][] heights) {\n int m = heights.length;\n int n = heights[0].length;\n \n if (r == m - 1 && c == n - 1) return true; // Reach destination\n visited[r][c] = true;\n \n for (int i = 0; i < 4; i++) {\n int nr = r + DIR[i];\n int nc = c + DIR[i + 1];\n \n if (nr < 0 || nr == m || nc < 0 || nc == n || visited[nr][nc]) continue;\n \n if (Math.abs(heights[nr][nc] - heights[r][c]) <= threshold && dfs(nr, nc, visited, threshold, heights)) {\n return true;\n }\n }\n return false;\n }\n \n public int minimumEffortPath(int[][] heights) {\n int m = heights.length;\n int n = heights[0].length;\n \n int left = 0;\n int ans = 0;\n int right = 1_000_000;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n boolean[][] visited = new boolean[m][n];\n \n if (dfs(0, 0, visited, mid, heights)) {\n right = mid - 1; // Try to find a better result on the left side\n ans = mid;\n } else {\n left = mid + 1;\n }\n }\n \n return ans;\n }\n}\n\n```\n```Python []\nclass Solution(object):\n def minimumEffortPath(self, heights):\n m, n = len(heights), len(heights[0])\n DIR = [0, 1, 0, -1, 0]\n \n def dfs(r, c, visited, threadshold):\n if r == m-1 and c == n-1: return True # Reach destination\n visited[r][c] = True\n for i in range(4):\n nr, nc = r+DIR[i], c+DIR[i+1]\n if nr < 0 or nr == m or nc < 0 or nc == n or visited[nr][nc]: continue\n if abs(heights[nr][nc]-heights[r][c]) <= threadshold and dfs(nr, nc, visited, threadshold): \n return True\n return False\n \n def canReachDestination(threadshold):\n visited = [[False] * n for _ in range(m)]\n return dfs(0, 0, visited, threadshold)\n \n left = 0\n ans = right = 10**6\n while left <= right:\n mid = left + (right-left) // 2\n if canReachDestination(mid):\n right = mid - 1 # Try to find better result on the left side\n ans = mid\n else:\n left = mid + 1\n return ans\n```\n\n---\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n![upvotememe.png]()\n\n\n | 87,131 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 12,771 | 285 | **TLDR**: Naive BFS doesn\'t work because you only visit the node once, and therefore you **only consider one of many paths.** Secondly, a naive BFS will give you the path with minimal nodes visited and doesn\'t care about the `effort`. In this problem, though, we can clearly see that `optimal path != path with minimal length` (look at **Example 3**), which naive BFS is unable to differentiate.\n\n# Thought Process\n\nWhen a question asks about something related to shortest path, always consider how BFS can help because that\'s what BFS does. However after a few minutes of thinking, I quickly realize that a simple naive BFS would not work.\n\nBefore going further, here is the pseudocode of naive BFS:\n```\nqueue = []\nvisited = set()\nwhile queue:\n\tme = queue.popleft()\n\tfor every neighbor of me:\n\t\tif neighbor not in visited:\n\t\t\tvisited.add(neighbor)\n\t\t\tqueue.append(neighbor)\n```\nConsider the **Example 1**. If you loop the neighbors in the following order: **right,left,bottom,up** then you would find the below path before other possible paths\n![image]()\n\nThat\'s great. Although it is not the optimal path, at least you found a path to the destination and you know the `effort` here is 3. Now, you can look for other better paths right? Unfortunately, in naive BFS, you only visit a node exactly once. This means that unless you reset the `visited` set, you can\'t find other way to the destination. Remember, by now, the destination itself is already marked as visited right? So you will not visit it again.\n\nInterestingly, if you loop your neighbors in the following order: **bottom,right,left,up**, then you will find optimal path.\n![image]()\n\nSo the order of iterating the neighbor clearly matters. But wait a minute! that\'s no longer the scope of BFS!\n\n> In BFS, the order of looping the neighbors should never affect the answer. BFS should find the shortest path regardless of how you iterate your neighbors. \n\nIt is true our BFS has found the path with minimal length (i.e. both of the above paths visit 4 nodes). However, our BFS cannot differentiate the `effort` of the two paths above. In fact, once you introduce any notion of weight to the graph, BFS will fail since BFS doesn\'t really care about weight. And so, naive BFS would not work for this problem. We need to modify our stupid BFS.\n\nFortunately, we\'re close. At this point, I know that the logic for visiting a node is messed up; I cannot just visit a node once and call it a day, I need to visit it more than once. Where in the code that is responsible of whether or not I should visit a node?\n\nThat\'s right. It\'s this dude:\n```\nif neighbor not in visited:\n\t# visit neighbor\n```\nSo we need to change the logic and how we store the BFS\'s visited state. How? Well, ask this question.\n\n> When would I ever bother to visit a node for the second time?\n\nThe answer is \n\n> when we found a better path (i.e. lower cost)\n\nAnd this answer should be sufficient to give me a hint that instead of a visited set, we need to store **a cost in dictionary**. Hence, the modified BFS should look like the following (pseudocode):\n```python\nqueue = []\ncost = {} # dictionary, instead of a set\nwhile queue:\n\tme = queue.popleft()\n\tfor every neighbor of me:\n\t\tnew_cost = compute_cost()\n\t\tif new_cost < cost[neighbor]: # better path!\n\t\t\tcost[neighbor] = new_cost\n\t\t\tqueue.append(neighbor)\n```\n\n**And this modified BFS is actually what Dijkstra does :)**.\n\n## Solution\nFor reference, this is just one way of implementing the Dijkstra\'s algorithm (no priority queue).\n\n```python\nfrom collections import deque\n\nclass Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n H = len(heights)\n W = len(heights[0])\n\n queue = deque([])\n queue.append((0, 0))\n\n cost = { (row, col): float(\'inf\') for col in range(W) for row in range(H) }\n cost[(0, 0)] = 0\n\n directions = [[1,0], [0,1], [-1,0], [0,-1]]\n \n def inside(row, col):\n return 0 <= row < H and 0 <= col < W\n \n while queue:\n row, col = queue.popleft()\n current_height = heights[row][col]\n current_cost = cost[(row, col)]\n\n for d_row, d_col in directions:\n new_row = row + d_row\n new_col = col + d_col\n\n if inside(new_row, new_col):\n neighbor_height = heights[new_row][new_col]\n new_cost = max(current_cost, abs(neighbor_height - current_height))\n if new_cost < cost[(new_row, new_col)]:\n cost[(new_row, new_col)] = new_cost\n queue.append((new_row, new_col))\n \n return cost[(H - 1, W - 1)]\n```\n\n# Analysis\nRight now we have working answer. But it is `O(V^2)`. Where `V` is the number of nodes (H * W). We could optimize the Dijkstra\'s algorithm with minimizing heap (or priority queue, if you will) instead of a simple queue. That will bring the complexity down to `O(ElgV)`. I\'m sure every other posts would have already had this solution.\n | 87,133 |
Path With Minimum Effort | path-with-minimum-effort | You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. | Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix | Medium | Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value. | 2,166 | 16 | # Intuition\r\n- The problem requires finding the minimum effort path from the top-left corner of a 2D grid to the bottom-right corner. \r\n- The effort of a path is defined as the maximum absolute difference in heights between adjacent cells along the path. We need to minimize this maximum effort.\r\n\r\n# Approach\r\n1. We can use a binary search approach to find the minimum effort required for the path. We initialize the lower bound `l` as 0 and the upper bound `r` as a very large value (1e9 + 2) since the effort cannot exceed this upper limit.\r\n\r\n1. In each iteration of the binary search, we calculate the middle value mid between `l` and `r`.\r\n\r\n1. We use depth-first search (DFS) to check if there exists a path from the top-left corner to the bottom-right corner with a maximum effort not exceeding `mid`. The DFS function ok explores the grid and marks cells as visited if they can be reached with an effort less than or equal to `mid`.\r\n\r\n1. **If the bottom-right corner is marked** as visited after the DFS, it means there is a path with an effort not exceeding mid, so we update the upper bound r to mid.\r\n\r\n1. If the bottom-right corner is not marked as visited after the DFS, it means there is no path with an effort less than` mid`, so we update the lower bound `l` to `mid + 1.`\r\n\r\n1. We repeat the binary search until` l` is less than `r`. Finally, `l` will represent the minimum effort required to reach the destination.\r\n\r\n# Complexity\r\n- Time complexity:\r\n- The binary search runs in O(log(1e9 + 2)) time, which is effectively O(1).\r\n- **The DFS function ok explores each cell at most once, so its time complexity is O(N * M)**, where N is the number of rows and M is the number of columns in the grid.\r\n- **The overall time complexity of the solution is O(log(1e9 + 2) * N * M)**, which simplifies to `O(N * M).`\r\n\r\n- Space complexity:\r\n- **The space complexity is dominated by the vis array, which is O(N * M) since it has the same dimensions as the grid.**\r\n- **The recursive DFS stack may require additional space, but in the worst case, it won\'t exceed O(N * M)** since each cell is visited at most once.\r\n`The overall space complexity of the solution is O(N * M).`\r\n\r\n# PLEASE UPVOTE\u2764\uD83D\uDE0D\r\n\r\n\r\n# Code\r\n```\r\nclass Solution {\r\npublic:\r\n \r\n int vis[105][105]; // Declare a 2D array to mark visited cells.\r\n vector<pair<int,int>>dir={{1,0},{-1,0},{0,-1},{0,1}}; // Define 4 possible directions to move: down, up, left, right.\r\n\r\n // Depth-first search function to explore cells with a maximum difference of \'mid\'.\r\n void ok(int x, int y, int mid, vector<vector<int>>& heights) {\r\n if (!vis[x][y]) { // If the cell has not been visited.\r\n vis[x][y] = 1; // Mark the cell as visited.\r\n int n = heights.size(); // Get the number of rows in the \'heights\' matrix.\r\n int m = heights[0].size(); // Get the number of columns in the \'heights\' matrix.\r\n \r\n // Loop through the four possible directions.\r\n for (int i = 0; i < 4; i++) {\r\n int X = x + dir[i].first; // Calculate the new row coordinate.\r\n int Y = y + dir[i].second; // Calculate the new column coordinate.\r\n \r\n // Check if the new coordinates are out of bounds.\r\n if (X < 0 || X >= n || Y < 0 || Y >= m)\r\n continue; // Skip this direction if out of bounds.\r\n \r\n // Check if the absolute difference between the heights is less than or equal to \'mid\'.\r\n if (abs(heights[x][y] - heights[X][Y]) <= mid)\r\n ok(X, Y, mid, heights); // Recursively explore this direction.\r\n }\r\n }\r\n }\r\n \r\n // Function to find the minimum effort path using binary search.\r\n int minimumEffortPath(vector<vector<int>>& heights) {\r\n int l = 0; // Initialize the left bound of the binary search.\r\n int r = 1e9 + 2; // Initialize the right bound of the binary search.\r\n int n = heights.size(); // Get the number of rows in the \'heights\' matrix.\r\n int m = heights[0].size(); // Get the number of columns in the \'heights\' matrix.\r\n \r\n while (l < r) { // Perform binary search until the left bound is less than the right bound.\r\n int mid = (l + r) / 2; // Calculate the middle value.\r\n memset(vis, 0, sizeof(vis)); // Initialize the visited array to 0.\r\n ok(0, 0, mid, heights); // Start the depth-first search with \'mid\' as the maximum difference.\r\n \r\n if (vis[n - 1][m - 1] == 1)\r\n r = mid; // If the destination cell is reachable, update the right bound.\r\n else\r\n l = mid + 1; // If the destination cell is not reachable, update the left bound.\r\n }\r\n \r\n return l; // Return the minimum effort required to reach the destination.\r\n }\r\n};\r\n\r\n```\r\n# JAVA\r\n```\r\nclass Solution {\r\n int[][] vis = new int[105][105];\r\n int[][] dir = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};\r\n\r\n void ok(int x, int y, int mid, int[][] heights) {\r\n if (vis[x][y] == 0) {\r\n vis[x][y] = 1;\r\n int n = heights.length;\r\n int m = heights[0].length;\r\n\r\n for (int i = 0; i < 4; i++) {\r\n int X = x + dir[i][0];\r\n int Y = y + dir[i][1];\r\n\r\n if (X < 0 || X >= n || Y < 0 || Y >= m)\r\n continue;\r\n\r\n if (Math.abs(heights[x][y] - heights[X][Y]) <= mid)\r\n ok(X, Y, mid, heights);\r\n }\r\n }\r\n }\r\n\r\n public int minimumEffortPath(int[][] heights) {\r\n int l = 0;\r\n int r = 1000000002;\r\n int n = heights.length;\r\n int m = heights[0].length;\r\n\r\n while (l < r) {\r\n int mid = (l + r) / 2;\r\n vis = new int[105][105];\r\n ok(0, 0, mid, heights);\r\n\r\n if (vis[n - 1][m - 1] == 1)\r\n r = mid;\r\n else\r\n l = mid + 1;\r\n }\r\n\r\n return l;\r\n }\r\n}\r\n\r\n```\r\n# PYTHON\r\n```\r\nclass Solution:\r\n def __init__(self):\r\n self.vis = [[0] * 105 for _ in range(105)]\r\n self.dir = [(1, 0), (-1, 0), (0, -1), (0, 1)]\r\n\r\n def ok(self, x, y, mid, heights):\r\n if not self.vis[x][y]:\r\n self.vis[x][y] = 1\r\n n = len(heights)\r\n m = len(heights[0])\r\n\r\n for i in range(4):\r\n X = x + self.dir[i][0]\r\n Y = y + self.dir[i][1]\r\n\r\n if X < 0 or X >= n or Y < 0 or Y >= m:\r\n continue\r\n\r\n if abs(heights[x][y] - heights[X][Y]) <= mid:\r\n self.ok(X, Y, mid, heights)\r\n\r\n def minimumEffortPath(self, heights):\r\n l = 0\r\n r = 1000000002\r\n n = len(heights)\r\n m = len(heights[0])\r\n\r\n while l < r:\r\n mid = (l + r) // 2\r\n self.vis = [[0] * 105 for _ in range(105)]\r\n self.ok(0, 0, mid, heights)\r\n\r\n if self.vis[n - 1][m - 1] == 1:\r\n r = mid\r\n else:\r\n l = mid + 1\r\n\r\n return l\r\n\r\n```\r\n# JAVASCRIPT\r\n```\r\nclass Solution {\r\n constructor() {\r\n this.vis = new Array(105).fill(null).map(() => new Array(105).fill(0));\r\n this.dir = [[1, 0], [-1, 0], [0, -1], [0, 1]];\r\n }\r\n\r\n ok(x, y, mid, heights) {\r\n if (!this.vis[x][y]) {\r\n this.vis[x][y] = 1;\r\n const n = heights.length;\r\n const m = heights[0].length;\r\n\r\n for (let i = 0; i < 4; i++) {\r\n const X = x + this.dir[i][0];\r\n const Y = y + this.dir[i][1];\r\n\r\n if (X < 0 || X >= n || Y < 0 || Y >= m)\r\n continue;\r\n\r\n if (Math.abs(heights[x][y] - heights[X][Y]) <= mid)\r\n this.ok(X, Y, mid, heights);\r\n }\r\n }\r\n }\r\n\r\n minimumEffortPath(heights) {\r\n let l = 0;\r\n let r = 1000000002;\r\n const n = heights.length;\r\n const m = heights[0].length;\r\n\r\n while (l < r) {\r\n const mid = Math.floor((l + r) / 2);\r\n this.vis = new Array(105).fill(null).map(() => new Array(105).fill(0));\r\n this.ok(0, 0, mid, heights);\r\n\r\n if (this.vis[n - 1][m - 1] === 1)\r\n r = mid;\r\n else\r\n l = mid + 1;\r\n }\r\n\r\n return l;\r\n }\r\n}\r\n\r\n```\r\n# GO\r\n```\r\npackage main\r\n\r\nimport "math"\r\n\r\ntype Solution struct {\r\n\tvis [105][105]int\r\n\tdir [][2]int\r\n}\r\n\r\nfunc (s *Solution) ok(x, y, mid int, heights [][]int) {\r\n\tif s.vis[x][y] == 0 {\r\n\t\ts.vis[x][y] = 1\r\n\t\tn := len(heights)\r\n\t\tm := len(heights[0])\r\n\r\n\t\tdirections := [][2]int{{1, 0}, {-1, 0}, {0, -1}, {0, 1}}\r\n\r\n\t\tfor i := 0; i < 4; i++ {\r\n\t\t\tX := x + directions[i][0]\r\n\t\t\tY := y + directions[i][1]\r\n\r\n\t\t\tif X < 0 || X >= n || Y < 0 || Y >= m {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tif int(math.Abs(float64(heights[x][y]-heights[X][Y]))) <= mid {\r\n\t\t\t\ts.ok(X, Y, mid, heights)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc (s *Solution) minimumEffortPath(heights [][]int) int {\r\n\tl := 0\r\n\tr := int(1e9 + 2)\r\n\tn := len(heights)\r\n\tm := len(heights[0])\r\n\r\n\tfor l < r {\r\n\t\tmid := (l + r) / 2\r\n\t\ts.vis = [105][105]int{}\r\n\r\n\t\ts.ok(0, 0, int(mid), heights)\r\n\r\n\t\tif s.vis[n-1][m-1] == 1 {\r\n\t\t\tr = int(mid)\r\n\t\t} else {\r\n\t\t\tl = int(mid) + 1\r\n\t\t}\r\n\t}\r\n\r\n\treturn l\r\n}\r\n\r\nfunc main() {\r\n\t// Create an instance of Solution and call minimumEffortPath here with your input data.\r\n}\r\n\r\n```\r\n# PLEASE UPVOTE\u2764\uD83D\uDE0D | 87,137 |
Defuse the Bomb | defuse-the-bomb | You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! | Array | Easy | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. | 2,208 | 20 | Double the ```code``` array so that it\'s easy to iterate.\n```class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k==0: return [0 for i in code]\n temp = code\n code = code*2\n for i in range(len(temp)):\n if k>0:\n temp[i] = sum(code[i+1:i+k+1])\n else:\n temp[i] = sum(code[i+len(temp)+k:i+len(temp)])\n return temp | 87,162 |
Defuse the Bomb | defuse-the-bomb | You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! | Array | Easy | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. | 1,224 | 14 | ```\nclass Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k < 0: return self.decrypt(code[::-1], -k)[::-1]\n \n n = len(code)\n ret = [0] * n\n s = sum(code[:k])\n for i, c in enumerate(code):\n s += code[(i + k) % n] - c\n ret[i] = s\n \n return ret\n```\n\n- for negative k: reverse params and result\n- calculate sum of k element, then iteratively add new element and remove oldest one.\n | 87,172 |
Defuse the Bomb | defuse-the-bomb | You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k. To decrypt the code, you must replace every number. All the numbers are replaced simultaneously. As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1]. Given the circular array code and an integer key k, return the decrypted code to defuse the bomb! | Array | Easy | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. | 920 | 7 | ```\noutput = []\nfor i in range(len(code)):\n\tif k > 0:\n\t\tsum = 0\n\t\tj = i+1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]\n\t\t\tm-=1\n\t\t\tj+=1\n\t\toutput.append(sum)\n\n\telif k == 0:\n\t\toutput.append(0)\n\n\telse:\n\t\tsum = 0\n\t\tj = i-1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]\n\t\t\tm+=1\n\t\t\tj-=1\n\t\toutput.append(sum)\n\nreturn output\n``` | 87,182 |
Minimum Deletions to Make String Balanced | minimum-deletions-to-make-string-balanced | You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. | String,Dynamic Programming,Stack | Medium | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing | 1,319 | 20 | ```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n result = 0\n b_count = 0\n \n for c in s:\n if c == "a":\n result = min(b_count, result + 1)\n else:\n b_count += 1\n \n return result\n```\n\nAt every point in our traversal, if we encounter an "a", we can either delete every "b" up to that point, or we can delete that one "a".\n\n```result``` keeps a running total of the number of deletions we have made so far to keep the string up until the current point balanced.\n\nTime complexity: O(n)\nSpace complexity: O(1) | 87,205 |
Minimum Deletions to Make String Balanced | minimum-deletions-to-make-string-balanced | You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. | String,Dynamic Programming,Stack | Medium | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing | 706 | 9 | **Count the total number of ba pairs**\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n stack, res = [], 0\n for i in range(len(s)):\n if stack and s[i] == "a" and stack[-1] == "b":\n stack.pop()\n res += 1\n else:\n stack.append(s[i])\n return res | 87,229 |
Minimum Deletions to Make String Balanced | minimum-deletions-to-make-string-balanced | You are given a string s consisting only of characters 'a' and 'b'. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'. Return the minimum number of deletions needed to make s balanced. | String,Dynamic Programming,Stack | Medium | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing | 1,629 | 14 | * O(n) for loop each character of the string s\n* Track the minimum number of deletions to make a balanced string till current character, either ending with \'a\' or \'b\'.\n* In the end, find the min of these two numbers\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n # track the minimum number of deletions to make the current string balanced ending with \'a\', \'b\'\n end_a, end_b = 0,0 \n for val in s:\n if val == \'a\':\n # to end with \'a\', nothing to do with previous ending with \'a\'\n # to end with \'b\', need to delete the current \'a\' from previous ending with \'b\'\n end_b += 1\n else:\n # to end with \'a\', need to delete the current \'b\' from previous ending with \'a\'\n # to end with \'b\', nothing to do, so just pick smaller of end_a, end_b\n end_a, end_b = end_a+1, min(end_a, end_b)\n return min(end_a, end_b)\n``` | 87,230 |
Minimum Jumps to Reach Home | minimum-jumps-to-reach-home | A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. | Array,Dynamic Programming,Breadth-First Search | Medium | Think of the line as a graph to handle the no double back jumps condition you can handle it by holding the state of your previous jump | 4,320 | 22 | **UPD:**\n\nI believe I have found the issue: I should be able to go back more if my back step is larger than my forward step. Thanks to @ShidaLei\n for pointing it out.\n\n----------------------------------------------------------------------------------------------------------------\nUpdated, working DFS solution, still not 100% about the "toofar" condition, one possibly could come up with test cases where this still breaks:\n```\ndef minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n\tforbidden = set(forbidden)\n\ttoofar = max(forbidden) + b if a < b else x\n\tminsofar = -1\n\n\tposition_cost = {} # only record the cost when jumping forward\n\tdef minjumps(cur_pos = 0, jumped_back = False, jumpsmade = 0):\n\t\tnonlocal minsofar, toofar\n\t\tif cur_pos < 0 or \\\n\t\t cur_pos in forbidden or \\\n\t\t cur_pos - b > toofar or \\\n\t\t minsofar > -1 and jumpsmade > minsofar: return \n\n\t\tif cur_pos == x:\n\t\t\tminsofar = jumpsmade if minsofar == -1 else min(minsofar, jumpsmade)\n\t\t\treturn\n\n\t\tif jumped_back: # can only jump forward at this point\n\t\t\tminjumps(cur_pos + a, False, jumpsmade + 1)\n\t\t\treturn\n\t\telif cur_pos not in position_cost: position_cost[cur_pos] = jumpsmade\n\t\telif jumpsmade >= position_cost[cur_pos]: return\n\t\telse: position_cost[cur_pos] = jumpsmade\n\n\t\tminjumps(cur_pos + a, False, jumpsmade + 1)\n\t\tminjumps(cur_pos - b, True, jumpsmade + 1)\n\n\tminjumps()\n\treturn minsofar\n```\n\nTest case, for which I used to end up with `-1` instead of `121`:\n```\n[162,118,178,152,167,100,40,74,199,186,26,73,200,127,30,124,193,84,184,36,103,149,153,9,54,154,133,95,45,198,79,157,64,122,59,71,48,177,82,35,14,176,16,108,111,6,168,31,134,164,136,72,98]\n29\n98\n80\n``` | 87,259 |
Minimum Jumps to Reach Home | minimum-jumps-to-reach-home | A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. | Array,Dynamic Programming,Breadth-First Search | Medium | Think of the line as a graph to handle the no double back jumps condition you can handle it by holding the state of your previous jump | 1,935 | 23 | The objective is to find the minimum number of hops. BFS is the ideal candidate for this question since it will provide the shortest path.\n**Solution:**\n1. We start exploring from `0` position. \n2. At each position, we can either go forward by `a` and go backward by `b`. Thing to note here is we cannot go backward twice in a row so we will maintain a flag `isForward` to signal if the previous jump was a `forward` jump.\n3. If the previous jump was `isForward` then we have 2 positions we can go to from current position `pos` -> `pos+a` and `pos-b`\n4. If the previous jump was not `isForward` then we can go to 1 position only from current position `pos` -> `pos+a`\n5. To avoid going to the same `pos` multiple times we will maintain a `visited` data-structure which will keep track of already visited positions. We will also add forbidden positions to this data structure.\n6. The tricky bit is to figure out when the forward limit. Since the question mentions that the max x is 2000. The absolute limit is `2000 + a + b`. As anything beyond this limit will always be greater than x because there is only one backward move allowed. So any position above this limit will not be added to the search queue.\n7. Keep exploring the positions in the `queue` until you reach destination `x` in which case `return hops` or until the `queue` is empty in which case `return -1`\n\nPython\n```\nclass Solution:\n def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n limit = 2000 + a + b\n visited = set(forbidden)\n myque = collections.deque([(0, True)]) # (pos, isForward) \n hops = 0\n while(myque):\n l = len(myque)\n while(l > 0):\n l -= 1\n pos, isForward = myque.popleft()\n if pos == x:\n return hops\n if pos in visited: continue\n visited.add(pos)\n if isForward:\n nxt_jump = pos - b\n if nxt_jump >= 0:\n myque.append((nxt_jump, False))\n nxt_jump = pos + a\n if nxt_jump <= limit:\n myque.append((nxt_jump, True))\n hops += 1\n return -1\n```\n\nC++\n```\nclass Solution {\npublic:\n int minimumJumps(vector<int>& forbidden, int a, int b, int x) {\n int limit = 2000 + a + b;\n std::queue<std::pair<int, int>> cur;\n cur.push({0, 1});\n std::unordered_set<int> visited;\n for (auto& x : forbidden){\n visited.insert(x);\n }\n \n int hops = 0;\n while(!cur.empty()){\n int size = cur.size();\n while(size--){\n auto it = cur.front(); cur.pop();\n int num = it.first;\n int forward = it.second;\n if (num == x) return hops;\n if (visited.count(num) != 0)\n continue;\n visited.insert(num);\n if (forward){\n int nxt = num - b;\n if (nxt >= 0){\n cur.push({nxt, 0});\n }\n }\n int nxt = num + a;\n if (nxt <= limit){\n cur.push({nxt, 1});\n }\n }\n ++hops;\n }\n return -1;\n \n }\n}; | 87,278 |
Minimum Jumps to Reach Home | minimum-jumps-to-reach-home | A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. | Array,Dynamic Programming,Breadth-First Search | Medium | Think of the line as a graph to handle the no double back jumps condition you can handle it by holding the state of your previous jump | 777 | 5 | ```\ndef minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n visited = set()\n q = deque([(0, 0)])\n forbidden = set(forbidden)\n furthest = max(x, max(forbidden)) + a + b\n \n res = 0\n while q:\n n = len(q)\n for _ in range(n):\n p, is_back = q.popleft()\n if p in forbidden or (p, is_back) in visited or p < 0 or p > furthest:\n continue\n if p == x:\n return res \n visited.add((p, is_back))\n q.append((p + a, 0))\n if not is_back:\n q.append((p - b, 1))\n \n res += 1\n return -1\n``` | 87,291 |
Minimum Jumps to Reach Home | minimum-jumps-to-reach-home | A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. | Array,Dynamic Programming,Breadth-First Search | Medium | Think of the line as a graph to handle the no double back jumps condition you can handle it by holding the state of your previous jump | 1,314 | 9 | The basic setup is to do a BFS starting from position 0, and according to the rules, try to move forward or backward till we reach x. However, there are a few catches:\n1. We cannot move backward twice in a row. To handle this, we store the state in the queue as `(0,1)` where the first element is the position and the second element is the direction of the last move. If the previous move was in the forward direction, then we can try the backwards direction.\n2. We may land on the same position (`z`) either by moving forward (`p1 + a = z`) or backward (`p2 - b = z`). To handle this, we will iterate through the queue twice, and process all forward jumps first, then the backward jumps. The reason is because the forward jumps have no restrictions and we land on the same position, so we lose nothing by keeping only the forward jumps.\n3. We need to bound the positions we search, otherwise the code will run forever. For the lower bound, it is given by the question that we cannot visit negative integers. For the upper bound, it is given by `max(x, max(forbidden)) + a + b`. This value is the largest position that we should explore such that it may be possible to backtrack to the bug\'s home. For example, `a = 2, b = 3, forbidden = [7], x = 9`. We will take the path: `2 -> 4 -> 6 -> 8 -> 10 -> 12 -> 9`. Thus, at the very end we may need to go past our destination and then backtrack. We need to take into account both `x` and `max(forbidden)` because `max(forbidden)` can be insignificant or e.g. the following input: `forbidden = [10], a = 20, b = 19, x = 101`.\n\n```\nclass Solution:\n def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n queue = deque([(0,1)])\n jumps = 0\n forbidden = set(forbidden)\n forbidden.add(0)\n MAX_DIST = max(x, max(forbidden)) + a + b\n while queue:\n tmp = deque()\n for elem in queue:\n (pos, direction) = elem\n if pos == x: return jumps\n forward = pos + a\n if forward not in forbidden and forward <= MAX_DIST:\n tmp.append((forward, 1))\n forbidden.add(forward)\n for elem in queue:\n (pos, direction) = elem\n if pos == x: return jumps\n backward = pos - b\n if direction != -1 and backward >= 0 and backward not in forbidden:\n tmp.append((backward, -1))\n forbidden.add(backward)\n queue = tmp\n jumps += 1\n return -1\n``` | 87,293 |
Distribute Repeating Integers | distribute-repeating-integers | You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that: Return true if it is possible to distribute nums according to the above conditions. | Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask | Hard | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number. | 594 | 6 | 1. Sort the `quantity` array in reverse order, since allocating larger quantities first will more quickly reduce the search space.\n2. Get the frequency of each number in `nums`, ignoring the actual numbers.\n3. Then further get the count of each frequency, storing this in `freqCounts`. We do this so that in our backtracking step, we don\'t try allocating a quantity to two different but equal frequencies, as they would have an equivalent result.\n4. In the backtracking, we try allocating each quantity to each unique frequency, simply decrementing and incrementing the frequency counts in each step.\n```\nfrom collections import Counter, defaultdict\n\nclass Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n quantity.sort(reverse=True)\n freqCounts = defaultdict(int, Counter(Counter(nums).values()))\n def backtrack(i: int = 0) -> bool:\n if i == len(quantity):\n return True\n \n for freq, count in list(freqCounts.items()):\n if freq >= quantity[i] and count > 0:\n freqCounts[freq] -= 1\n freqCounts[freq - quantity[i]] += 1\n if backtrack(i + 1):\n return True\n freqCounts[freq] += 1\n freqCounts[freq - quantity[i]] -= 1\n \n return False\n \n return backtrack()\n``` | 87,312 |
Check Array Formation Through Concatenation | check-array-formation-through-concatenation | You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. | Array,Hash Table | Easy | Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively | 1,965 | 29 | * **Simple and easy python3 solution**\n* **The approch is well explained in the below image**\n\n![image]()\n\n\n```\nclass Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n keys, ans = {}, []\n for piece in pieces:\n keys[piece[0]] = piece\n for a in arr:\n if a in keys:\n ans.extend(keys[a])\n return \'\'.join(map(str, arr)) == \'\'.join(map(str, ans))\n``` | 87,358 |
Check Array Formation Through Concatenation | check-array-formation-through-concatenation | You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. | Array,Hash Table | Easy | Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively | 1,564 | 15 | Python O(n) by dictionary\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n \n ## dictionary\n # key: head number of piece\n # value: all number of single piece\n mapping = { piece[0]: piece for piece in pieces }\n \n result = []\n \n # try to make array from pieces\n for number in arr:\n \n result += mapping.get( number, [] )\n \n # check they are the same or not\n return result == arr\n```\n\n---\n\nReference:\n\n[1] [Python official docs about dictionary.get( ..., default value)]()\n | 87,366 |
Check Array Formation Through Concatenation | check-array-formation-through-concatenation | You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false. | Array,Hash Table | Easy | Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively | 1,061 | 11 | Algo\nWe can leverage on the fact that the integers in `pieces` are distinct and define a mapping `mp` to map from the first element of piece to piece. Then, we could linearly scan `arr` and check if what\'s in arr `arr[i:i+len(mp[x])]` is the same as the one in piece `mp[x]`. \n\nImplementation\n```\nclass Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n mp = {x[0]: x for x in pieces}\n i = 0\n while i < len(arr): \n if (x := arr[i]) not in mp or mp[x] != arr[i:i+len(mp[x])]: return False \n i += len(mp[x])\n return True \n```\n\nEdited on 11/01/2020 \nAdding a 2-line implementation \n```\nclass Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n mp = {x[0]: x for x in pieces}\n return sum((mp.get(x, []) for x in arr), []) == arr\n```\n\nAnalysis\nTime complexity `O(N)`\nSpace complexity `O(N)` | 87,373 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 125 | 11 | \n# Code\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n mul=1\n j=1\n for i in range(5,5+n):\n mul=(mul*i)//j\n j+=1\n return mul\n \n``` | 87,402 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 13,207 | 183 | # Intuition\n\n- Here we can observe a pattern to this problem.\n\n```\n\t\t a e i o u\n n=1 1 1 1 1 1 /a, e, i, o, u\n n=2 5 4 3 2 1 /a-> aa,ae,ai,ao,au | e-> ee,ei,eo,eu | i-> ii,io,iu | o-> oo,ou | u-> uu\n n=3 15 10 6 3 1\n```\n\n- If we observe from last there will be only 1 element which will start with u. Every other element will have the count of previous count + next element count. As example\nin n=2, i will be previous i(1) + count of next element, o(2) \u2192 3\nin n=3, e will be previous e(4) + count of next element, i(6) \u2192 10\n\n# Approach 01\n1. Using ***5 variables.***\n1. Initialize variables a, e, i, o, and u to 1, representing the count of strings ending with each vowel.\n2. Iterate from n-1 to 0 using a loop, updating the count for each vowel as follows:\n - Increment the count of strings ending with \'o\' (o += u).\n - Increment the count of strings ending with \'i\' (i += o).\n - Increment the count of strings ending with \'e\' (e += i).\n - Increment the count of strings ending with \'a\' (a += e).\n3. After the loop, the sum of counts for all vowels (a+e+i+o+u) represents the total count of strings of length n that consist only of vowels and are lexicographically sorted.\n\n# Complexity\n- Time complexity: The time complexity of this solution is O(n), where algorithm iterates through the loop n times, and each iteration involves constant time operations.\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity is O(1) since we use a constant amount of space for variables regardless of the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n int a=1, e=1, i=1, o=1, u=1;\n \n while(--n){\n o += u;\n i += o;\n e += i;\n a += e;\n }\n \n return a+e+i+o+u;\n }\n};\n```\n```Java []\nclass Solution {\n public int countVowelStrings(int n) {\n int a = 1, e = 1, i = 1, o = 1, u = 1;\n\n while (--n > 0) {\n o += u;\n i += o;\n e += i;\n a += e;\n }\n\n return a + e + i + o + u;\n }\n}\n```\n```python []\nclass Solution(object):\n def countVowelStrings(self, n):\n a, e, i, o, u = 1, 1, 1, 1, 1\n\n while n > 1:\n o += u\n i += o\n e += i\n a += e\n n -= 1\n\n return a + e + i + o + u\n```\n\n---\n\n\n\n# Approach 02\n\n1. Using ***Dynamic Programing(dp).***\n2. Initialize a vector dp of size 5 (representing the vowels) with all elements set to 1. This vector will store the count of strings ending with each vowel.\n3. Iterate n-1 times (since we already have the count for n=1).\n4. In each iteration, update the count in the dp vector by summing up the counts of strings ending with each vowel from right to left. This step corresponds to extending the strings by adding one more character.\n5. After the iterations, the sum of counts in the dp vector represents the total number of strings of length n that can be formed using vowels.\n6. Return the sum as the result.\n\n\n# Complexity\n- Time complexity: The time complexity of this solution is O(3n) - The algorithm iterates n-1 times, and each iteration involves updating the vector in constant time.\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity is O(1) since we use a constant amount of space for variables regardless of the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int countVowelStrings(int n) {\n vector<int> dp(5, 1);\n int ans = 0;\n \n while(--n){\n for(int i=3; i>=0; i--){\n dp[i] += dp[i+1];\n }\n }\n \n for(auto x:dp) ans += x;\n \n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int countVowelStrings(int n) {\n int[] dp = new int[]{1, 1, 1, 1, 1};\n int ans = 0;\n\n while (--n > 0) {\n for (int i = 3; i >= 0; i--) {\n dp[i] += dp[i + 1];\n }\n }\n\n for (int x : dp) {\n ans += x;\n }\n\n return ans;\n }\n}\n```\n```python []\nclass Solution(object):\n def countVowelStrings(self, n):\n dp = [[0] * 5 for _ in range(n + 1)]\n\n for j in range(5):\n dp[1][j] = 1\n\n for i in range(2, n + 1):\n for j in range(5):\n for k in range(j, 5):\n dp[i][j] += dp[i - 1][k]\n\n result = sum(dp[n])\n return result\n```\n\n---\n\n> **Please upvote this solution**\n> | 87,406 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 4,963 | 50 | 1. ##### DP Tabulation\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int: \n dp = [[0] * 6 for _ in range(n+1)]\n for i in range(1, 6):\n dp[1][i] = i\n \n for i in range(2, n+1):\n dp[i][1]=1\n for j in range(2, 6):\n dp[i][j] = dp[i][j-1] + dp[i-1][j]\n \n return dp[n][5]\n```\n**Time = O(n)**\n**Space = O(n)**\n\n---\n2. ##### O(1) Space\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int: \n dp = [1] * 5\n \n for i in range(2, n+1):\n for j in range(4, -1, -1):\n dp[j] += sum(dp[:j]) \n \n return sum(dp)\n```\n\nAlternative solution shared by [@koacosmos]()\n\n```\nclass Solution:\n def countVowelStrings(self, k: int) -> int: \n dp = [1] * 5\n \n for _ in range(1, k):\n for i in range(1, 5): \n dp[i] = dp[i] + dp[i-1]\n \n return sum(dp)\n```\n**Time = O(n)**\n**Space = O(1)**\n\n---\n\n3. ##### Mathematical equation using [Combinations with repetition]()\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int: \n return (n + 4) * (n + 3) * (n + 2) * (n + 1) // 24;\n```\n\n---\nSolution shared by [@nithinmanne1]() using Python internal library.\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int: \n return math.comb(n + 4, 4)\n```\n\n**Time = O(1)\nSpace = O(1)**\n\n----\n\nOther contributers of this post:\n1. [@nithinmanne1]()\n2. [@koacosmos]()\n\n---\n\n***Please upvote if you find it useful*** | 87,412 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 6,991 | 103 | In this problem, the pattern I observed was prepending \'a\' to all the strings of length n-1 does not affect any order. Similarly, \'e\' can be prepended to strings starting with \'e\' and greater vowels and so on.\n\nSo we have our subproblem.\n\n**How do we fill the DP Table?**\nLets, take an example of n = 3\n\n![image]()\n\nFor n = 1, number of strings starting with u is 1, with o is 2 (including the ones starting with u) and so on.\nFor n = 2, number of strings starting with u is 1, but for o its (number of strings of length 2 starting with u + number of strings of length 1 starting with o) and so on.\ndp[i][j] represents total no. of string of length i , starting with characters of column j and after j. (Thanks @[rkm_coder]() for the correction)\n\nThe recursive expression is : dp[i][j] = dp[i - 1][j] + dp[i][j + 1]\n\nFinally, we will get our answer at dp[n][0]\n\nThe running time of my algorithm is **O(n)**\n\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n dp = [[i for i in range(5,0,-1)] for _ in range(n)] # intialize dp matrix\n \n for i in range(1,n):\n for j in range(3,-1,-1):\n dp[i][j] = dp[i - 1][j] + dp[i][j + 1] # dp expression\n \n return dp[n-1][0]\n```\n\nAlso check out Java implementation here: | 87,417 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 1,051 | 14 | Explanation:\nn = 1 -> 2 -> 3-> 4 ...\n____________________________\na =\t 1 -> 5 -> 15 -> 35 ...\ne =\t 1 -> 4 -> 10 -> 20 ...\ni =\t 1 -> 3 -> 6 -> 10 ...\no =\t 1 -> 2 -> 3 -> 4 ...\nu =\t 1 -> 1 -> 1 -> 1 ...\n____________________________\nsum = 5 -> 15 -> 35 -> 70 ... (that\'s the answer)\n\nCode:\n\n```\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n ## if n == 1: return 5 ##Edited: Actually don\'t need it!\n arr = [1, 1, 1, 1, 1] ## initial \n for i in range(2, n+1): ## for different values of n\n for j in range(5): ## for 5 vowels\n arr[j] = sum(arr[j:])\n return sum(arr) ## return sum of the array\n```\n\nPlease upvote if you like the answer! Happy coding!!\n | 87,445 |
Count Sorted Vowel Strings | count-sorted-vowel-strings | Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. | Dynamic Programming | Medium | For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c). | 2,090 | 30 | \n\n**Backtracking solution:**\n**Time complexity:** `O(n^5)`\nWe try all the possibilities where adding the new vowel doesn\'t break the lexicographic order. For example, if the last character of our actual possibility is \'e\', we can\'t add an \'a\' after it.\n```\ndef count(n, last=\'\'):\n if n == 0:\n return 1\n else:\n nb = 0\n for vowel in [\'a\', \'e\', \'i\', \'o\', \'u\']:\n if last <= vowel:\n nb += count(n-1, vowel)\n return nb\n```\n\n\n**Dynamic programming solution:**\n**Time complexity:** `O(n)`\nWe use a dp matrix of n rows and 5 columns (one column for each vowel) where the number of strings of size k that start with a vowel v is the sum of strings of size k-1 with whom we can add the vowel v from the beginning without breaking the order\nWe can add \'a\' before any vowel string without breaking the order, so the number of strings of size k that start with \'a\' is the number of strings of size k-1 that start with \'a\', \'e\', \'i\', \'o\', or \'u\'\nWe can add \'e\' before strings that start with \'e\', \'i\', \'o\', or \'u\' without breaking the order, so the number of strings of size k that start with \'e\' is the number of strings of size k-1 that start with \'e\', \'i\', \'o\', or \'u\'\nSame logic with remaining vowels (\'i\' -> \'i\', \'o\', or \'u\' / \'o\' -> \'o\' or \'u\' / \'u\' -> \'u\')\nAfter filling the matrix, the last row will contain the numbers of strings of size n with each vowel, we do the sum\n```\ndef count(n):\n NB_VOWELS = 5\n dp = [[0]*NB_VOWELS for i in range(n)]\n dp[0] = [1]*NB_VOWELS\n for i in range(1, len(dp)):\n dp[i][0] = dp[i-1][0] + dp[i-1][1] + dp[i-1][2] + dp[i-1][3] + dp[i-1][4] # a\n dp[i][1] = dp[i-1][1] + dp[i-1][2] + dp[i-1][3] + dp[i-1][4] # e\n dp[i][2] = dp[i-1][2] + dp[i-1][3] + dp[i-1][4] # i\n dp[i][3] = dp[i-1][3] + dp[i-1][4] # o\n dp[i][4] = dp[i-1][4] # u\n return sum(dp[-1])\n```\n\n\n**Math solution:**\n**Time complexity:** `O(1)`\nThe number of possible sorted strings that we can get by taking n vowels from 5 possible vowels is the number of possible combinations with repetition that we can get by taking n elements from 5 possible elements, and we have a mathematical law for that\n\n![image]()\n\n```\ndef count(n):\n return (n+4)*(n+3)*(n+2)*(n+1)//24\n```\n\n\n\n\n\n | 87,447 |
Furthest Building You Can Reach | furthest-building-you-can-reach | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. | Array,Greedy,Heap (Priority Queue) | Medium | Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b. | 6,989 | 120 | \u2714\uFE0F ***Solution - I (Using Min-Heap)***\n\nLadders can be used anywhere even for an infinite jump to next building. We need to realise that bricks limit our jumping capacity if used at wrong jumps. So, **bricks should be used only on the smallest jumps in the path and ladders should be used on the larger ones**.\n\nWe could have sorted the jumps and used ladders on largest *`L`* jumps(where, `L` is number of ladders) and bricks elsewhere. But, we don\'t know how many jumps will be performed or what\'s the order of jump sequence.\n\nFor this, we will **assume that the first *`L`* jumps are the largest ones** and store the jump heights in ascending order. We can use **priority_queue / min-heap** for this purpose (since we would be needing to insert and delete elements from it...explained further).\n\nNow, for any further jumps, we need to use bricks since the first *`L`* jumps have used up all the ladders. Let\'s call the jump height requried from now on as *`curJumpHeight`*. Now, \n\n* If *`curJumpHeight > min-heap top`* : We have the choice to use bricks on the previous jump which had less jump height. So, we will use that many bricks on previous (smaller) jump and use ladder for current (larger) jump.\n\n* If *`curJumpHeight <= min-heap top`* : There\'s no way to minimize usage of bricks for current jump. We need to spend atleast *`curJumpHeight`* number of bricks\n\nSo, using the above strategy, we can find the furthest building we can reach. As soon as the available bricks are all used up, we return the current building index.\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tint i = 0, n = size(H), jumpHeight;\n\t// pq will store the first ladder number of largest jumps\n\tpriority_queue<int, vector<int> ,greater<int> > pq;\n\t// first ladder number of jumps would be assumed to be the largest\n\t// hence, push all these jumps into the queue\n\twhile (i < n - 1 && size(pq) < ladders) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight > 0) \n\t\t\tpq.push(jumpHeight);\n\t\ti++; \n\t}\n\t// From here, we can\'t just use ladder and need to spend bricks from now on...\n\twhile (i < n - 1) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\t// if next building is bigger than current, bricks need to be used\n\t\tif(jumpHeight > 0) {\n\t\t\t// First check if we have a previous jump requiring less number of bricks than currentDiff\n\t\t\tif(!pq.empty() && pq.top() < jumpHeight) { \n\t\t\t\t// if there is, just use bricks for that jump and assign ladder for current one\n\t\t\t\tbricks -= pq.top(); pq.pop(); \n\t\t\t\tpq.push(jumpHeight); \n\t\t\t}\n\t\t\t// jumpHeight is already minimum jump size. So, no choice than spending that many bricks\n\t\t\telse bricks -= jumpHeight; \n\t\t}\n\t\t// if bricks become negative, we can\'t travel any further as all bricks and ladders are used up\n\t\tif(bricks < 0) return i;\n\t\ti++;\n\t}\n\treturn i;\n}\n```\n\n---\n\n**Python**\n\nThe idea is the same as above. Here, I have condensed the solution in single loop\n```\ndef furthestBuilding(self, H: List[int], bricks: int, ladders: int) -> int:\n jumps_pq = []\n for i in range(len(H) - 1):\n jump_height = H[i + 1] - H[i]\n if jump_height <= 0: continue\n heappush(jumps_pq, jump_height)\n if len(jumps_pq) > ladders:\n bricks -= heappop(jumps_pq)\n if(bricks < 0) : return i\n return len(H) - 1\n```\n\n***Time Complexity :*** **`O(NlogL)`**, where *`N`* is the number of buildings and *`L`* is the number of ladders available. A push operation in priority queue takes `O(logn)` time complexity, where *`n`* is size of the queue. Here, we are pushing into the priority queue `N` time and the max size of the queue at anytime would be `L`, so the final time complexity comes out to be `O(NlogL)`.\n***Space Complexity :*** **`O(L)`**\n\n---\n\n\u2714\uFE0F ***Solution - II (Using Max-Heap)***\n\nIn C++, there\'s a clean way to use max-heap (*priorityqueue* is max_heap by default) as a min-heap if you don\'t like the slightly complex syntax required to declare min-heap.\n\nThe process will remaint the same as the above. Here, since we are using max-heap, the only difference is we will push negative of *`jumpHeight`* and add these negative height to bricks every time we pop (instead of direct pushing & subtraction in above solution).\n\n\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tpriority_queue<int> pq;\n\tint n = size(H), i = 0, jumpHeight = 0;\n\tfor(; i < n - 1; i++) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight <= 0) continue;\n\t\tpq.push(-jumpHeight); // notice the \'-\'\n\t\tif(size(pq) > ladders) \n\t\t\tbricks += pq.top(), pq.pop();\n\t\tif(bricks < 0) return i;\n\t}\n\treturn i;\n}\n```\n \n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n \n---\n \n\u2714\uFE0F ***Solution - III (Using multiset)*** \n\nWe can also use multiset to maintain sorted jumps (multiset because there maybe multiple jumps of same height). Although, using multiset in this case will be slightly slower than priority_queue, I am just mentioning this here as well as a possible solution -\n\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\t multiset<int> s;\n int n = size(H), i = 0, jumpHeight = 0;\n for(; i < n - 1; i++) {\n jumpHeight = H[i + 1] - H[i];\n if(jumpHeight <= 0) continue;\n s.insert(jumpHeight);\n if(size(s) > ladders)\n bricks -= *begin(s), s.erase(begin(s));\n if(bricks < 0) return i;\n }\n return i;\n }\n```\n\n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n \n---\n\n\u2714\uFE0F ***Solution IV (Using map)***\n\nAgain, this wouldn\'t perform any better than using `priority_queue` / `heap`, but this one\'s a very commonly used data structure, so I am putting the solution using this as well. Also, this might actually be more space efficient if there are multiple jumps of same height in our path since we wouldn\'t have to store each of them separately & just maintain their count.\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tmap<int, short> mp;\n\tint n = size(H), i = 0, jumpHeight = 0;\n\tfor(; i < n - 1; i++) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight <= 0) continue;\n\t\tmp[jumpHeight]++;\n\t\tif(ladders--<=0){ \n\t\t\tbricks -= begin(mp) -> first;\n\t\t\tif(!--begin(mp) -> second) \n\t\t\t\tmp.erase(begin(mp));\n\t\t}\n\t\tif(bricks < 0) return i;\n\t}\n\treturn i;\n}\n```\n\n---\n\n**Python**\n```\nfrom sortedcontainers import SortedDict\ndef furthestBuilding(self, H: List[int], bricks: int, ladders: int) -> int:\n\tjumps = SortedDict()\n\tfor i in range(len(H) - 1):\n\t\tjump_height = H[i + 1] - H[i]\n\t\tif jump_height <= 0: continue\n\t\tjumps[jump_height], ladders = jumps.get(jump_height, 0) + 1, ladders - 1\n\t\tif ladders < 0:\n\t\t\ttop = jumps.peekitem(0)[0]\n\t\t\tbricks -= top\n\t\t\tjumps[top] -= 1\n\t\t\tif jumps[top] == 0 : jumps.popitem(0)\n\t\tif(bricks < 0) : return i\n\treturn len(H) - 1\n```\n\n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n\n---\n\n*Best Runtime (Using `Solution - I / II`) -*\n\n\n<table><tr><td><img src= /></td></tr></table>\n \n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 87,456 |
Furthest Building You Can Reach | furthest-building-you-can-reach | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. | Array,Greedy,Heap (Priority Queue) | Medium | Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b. | 3,491 | 57 | *(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nThe first realization should be that we always want to use our ladders to their best effect: where they would save us the most amount of bricks. Unfortunately, we can\'t just save the ladders for the largest gaps in the building heights, because we may not be able to reach them by using bricks.\n\nSince we can\'t find out how far we can go until we figure out where to place the ladders, and we can\'t figure out where to put the ladders until we see how far we can go, we\'ll have to move the ladders around as we go in order to maintain their maximum effect.\n\nTo put this in terms of a coding solution, as we iterate through the building heights array (**H**), we\'ll want to continuously make sure that the largest **L** number of positive differences are occupied with ladders, allowing us the best use of our **B** number of bricks.\n\nIn general, this means that we should start iterating through **H**, ignoring any difference (**diff**) that is **0** or less, and place a ladder whenever we have a positive difference. Once we\'ve used up all the ladders, then we can start using bricks. If we come across a **diff** that is larger than the smallest ladder that we\'re currently using, we should replace that ladder with bricks and move the ladder forwad to the current **diff**. Otherwise we should use bricks for the current **diff**.\n\nThe second big realization at this point is that we need a **min-heap** or **min priority queue** in order to keep track of the heights of the ladders in use, so that we can always take the smallest one, thus keeping the ladders always on the largest diff values.\n\nIf at any point we run out bricks, then we can\'t reach the next building and should **return i**. If we\'re able to reach the end of **H** without running out of bricks, we can **return H.length - 1**, signifying that we reached the last building.\n\n - _**Time Complexity: O(N * log N)** where N is the length of H, due to the use of a min-heap_\n - _**Space Complexity: O(L)** to keep track of L number of ladder lengths_\n\n---\n\n#### ***Implementation:***\n\nThe Javascript **MinPriorityQueue()** npm package isn\'t as efficient as a **min-heap**, but it is much more succinct, so I\'ve included both versions of code for comparison.\n\nFor C++, the **priority_queue** defaults to a max order, so we can just invert the sign on the **diff** values before insertion to effectively turn it into a min priority queue instead.\n\n---\n\n#### ***Javascript Code:***\n\n##### ***w/ MinPriorityQueue():***\n\nThe best result for the code below is **148ms / 53.1MB** (beats 48% / 55%).\n```javascript\nvar furthestBuilding = function(H, B, L) {\n let len = H.length - 1,\n pq = new MinPriorityQueue({priority: x => x})\n for (let i = 0; i < len; i++) {\n let diff = H[i+1] - H[i]\n if (diff > 0) {\n if (L > 0) pq.enqueue(diff), L--\n else if (pq.front() && diff > pq.front().element)\n pq.enqueue(diff), B -= pq.dequeue().element\n else B -= diff\n if (B < 0) return i\n }\n }\n return len\n};\n```\n\n##### ***w/ Min-Heap:***\n\nThe best result for the code below is **108ms / 49.7MB** (beats 98% / 91%).\n```javascript\nvar furthestBuilding = function(H, B, L) {\n let len = H.length - 1, heap = [,]\n const heapify = val => {\n let i = heap.length, par = i >> 1, temp\n heap.push(val)\n while (heap[par] > heap[i]) {\n temp = heap[par], heap[par] = heap[i], heap[i] = temp\n i = par, par = i >> 1\n }\n }\n const extract = () => {\n if (heap.length === 1) return null\n let top = heap[1], left, right, temp,\n i = 1, child = heap[3] < heap[2] ? 3 : 2\n if (heap.length > 2) heap[1] = heap.pop()\n else heap.pop()\n while (heap[i] > heap[child]) {\n temp = heap[child], heap[child] = heap[i], heap[i] = temp\n i = child, left = i << 1, right = left + 1\n child = heap[right] < heap[left] ? right : left\n }\n return top\n } \n for (let i = 0; i < len; i++) {\n let diff = H[i+1] - H[i]\n if (diff > 0) {\n if (L > 0) heapify(diff), L--\n else if (heap.length > 1 && diff > heap[1])\n heapify(diff), B -= extract()\n else B -= diff\n if (B < 0) return i\n }\n }\n return len\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **520ms / 28.7MB** (beats 100% / 89%).\n```python\nclass Solution:\n def furthestBuilding(self, H: List[int], B: int, L: int) -> int:\n heap = []\n for i in range(len(H) - 1):\n diff = H[i+1] - H[i]\n if diff > 0:\n if L > 0:\n heappush(heap, diff)\n L -= 1\n elif heap and diff > heap[0]:\n heappush(heap, diff)\n B -= heappop(heap)\n else: B -= diff\n if B < 0: return i\n return len(H) - 1\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **13ms / 48.7MB** (beats 87% / 97%).\n```java\nclass Solution {\n public int furthestBuilding(int[] H, int B, int L) {\n int len = H.length - 1;\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n for (int i = 0; i < len; i++) {\n int diff = H[i+1] - H[i];\n if (diff > 0) {\n if (L > 0) {\n pq.add(diff);\n L--;\n } else if (pq.size() > 0 && diff > pq.peek()) {\n pq.add(diff);\n B -= pq.poll();\n } else B -= diff;\n if (B < 0) return i;\n }\n }\n return len;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **76ms / 53.5MB** (beats 99% / 79%).\n```c++\nclass Solution {\npublic:\n int furthestBuilding(vector<int>& H, int B, int L) {\n int len = H.size() - 1;\n priority_queue<int> pq;\n for (int i = 0; i < len; i++) {\n int diff = H[i+1] - H[i];\n if (diff > 0) {\n if (L) pq.push(-diff), L--;\n else if (!pq.empty() && diff > -pq.top())\n pq.push(-diff), B += pq.top(), pq.pop();\n else B -= diff;\n if (B < 0) return i;\n }\n }\n return len;\n }\n};\n``` | 87,459 |
Furthest Building You Can Reach | furthest-building-you-can-reach | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. | Array,Greedy,Heap (Priority Queue) | Medium | Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b. | 548 | 9 | ##### Please upvote if you find this solution useful and helpful , comment if you have any doubts or any suggestions\nUsing **dp won\'t work out here** as heights array size is 10^5 , bricks size can be as big as 10^9 and we cant store the values for everything, So we have to use **Greedy algorithm** inorder to get the solution.\n**The trick is to use heap in such a way that its size is maintained according to ladders**.\nSo whenever the len(heap) equals ladders, at that we will pop out the least value from heap and we will subtract from no of bricks. So this can be done until bricks are not over or we have reached the end.\nWe will return the index at which the bricks and ladders are over else we will return len(heights)-1.\n\n```\nclass Solution:\n def furthestBuilding(self, h: List[int], bricks: int, ladders: int) -> int:\n heap=[]\n heapify(heap)\n for i in range(len(h)-1):\n d=h[i+1]-h[i]\n if d>0:\n heappush(heap,d)\n if len(heap)>ladders:\n bricks-=heappop(heap)\n if bricks<0:\n return i\n return len(h)-1\n\t\t\n ``` \n \n \n\t\t \n\t\t \n\t\t \n\t\t \n \n | 87,461 |
Furthest Building You Can Reach | furthest-building-you-can-reach | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. | Array,Greedy,Heap (Priority Queue) | Medium | Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b. | 2,648 | 36 | ```\nclass Solution:\n def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:\n # prepare: use a min heap to store each difference(climb) between two contiguous buildings\n # strategy: use the ladders for the longest climbs and the bricks for the shortest climbs\n \n min_heap = []\n n = len(heights)\n \n for i in range(n-1):\n climb = heights[i+1] - heights[i]\n \n if climb <= 0:\n continue\n \n # we need to use a ladder or some bricks, always take the ladder at first\n if climb > 0:\n heapq.heappush(min_heap, climb)\n \n # ladders are all in used, find the current shortest climb to use bricks instead!\n if len(min_heap) > ladders:\n # find the current shortest climb to use bricks\n brick_need = heapq.heappop(min_heap)\n bricks -= brick_need\n \n if bricks < 0:\n return i\n \n return n-1\n```\n\n**Upvote if it is helpful for you, many thanks!**\n | 87,463 |
Furthest Building You Can Reach | furthest-building-you-can-reach | You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders. While moving from building i to building i+1 (0-indexed), Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally. | Array,Greedy,Heap (Priority Queue) | Medium | Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b. | 1,197 | 28 | \u2714\uFE0F ***Solution - I (Using Min-Heap)***\n\nLadders can be used anywhere even for an infinite jump to next building. We need to realise that bricks limit our jumping capacity if used at wrong jumps. So, **bricks should be used only on the smallest jumps in the path and ladders should be used on the larger ones**.\n\nWe could have sorted the jumps and used ladders on largest *`L`* jumps(where, `L` is number of ladders) and bricks elsewhere. But, we don\'t know how many jumps will be performed or what\'s the order of jump sequence.\n\nFor this, we will **assume that the first *`L`* jumps are the largest ones** and store the jump heights in ascending order. We can use **priority_queue / min-heap** for this purpose (since we would be needing to insert and delete elements from it...explained further).\n\nNow, for any further jumps, we need to use bricks since the first *`L`* jumps have used up all the ladders. Let\'s call the jump height requried from now on as *`curJumpHeight`*. Now, \n\n* If *`curJumpHeight > min-heap top`* : We have the choice to use bricks on the previous jump which had less jump height. So, we will use that many bricks on previous (smaller) jump and use ladder for current (larger) jump.\n\n* If *`curJumpHeight <= min-heap top`* : There\'s no way to minimize usage of bricks for current jump. We need to spend atleast *`curJumpHeight`* number of bricks\n\nSo, using the above strategy, we can find the furthest building we can reach. As soon as the available bricks are all used up, we return the current building index.\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tint i = 0, n = size(H), jumpHeight;\n\t// pq will store the first ladder number of largest jumps\n\tpriority_queue<int, vector<int> ,greater<int> > pq;\n\t// first ladder number of jumps would be assumed to be the largest\n\t// hence, push all these jumps into the queue\n\twhile (i < n - 1 && size(pq) < ladders) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight > 0) \n\t\t\tpq.push(jumpHeight);\n\t\ti++; \n\t}\n\t// From here, we can\'t just use ladder and need to spend bricks from now on...\n\twhile (i < n - 1) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\t// if next building is bigger than current, bricks need to be used\n\t\tif(jumpHeight > 0) {\n\t\t\t// First check if we have a previous jump requiring less number of bricks than currentDiff\n\t\t\tif(!pq.empty() && pq.top() < jumpHeight) { \n\t\t\t\t// if there is, just use bricks for that jump and assign ladder for current one\n\t\t\t\tbricks -= pq.top(); pq.pop(); \n\t\t\t\tpq.push(jumpHeight); \n\t\t\t}\n\t\t\t// jumpHeight is already minimum jump size. So, no choice than spending that many bricks\n\t\t\telse bricks -= jumpHeight; \n\t\t}\n\t\t// if bricks become negative, we can\'t travel any further as all bricks and ladders are used up\n\t\tif(bricks < 0) return i;\n\t\ti++;\n\t}\n\treturn i;\n}\n```\n\n---\n\n**Python**\n\nThe idea is the same as above. Here, I have condensed the solution in single loop\n```\ndef furthestBuilding(self, H: List[int], bricks: int, ladders: int) -> int:\n jumps_pq = []\n for i in range(len(H) - 1):\n jump_height = H[i + 1] - H[i]\n if jump_height <= 0: continue\n heappush(jumps_pq, jump_height)\n if len(jumps_pq) > ladders:\n bricks -= heappop(jumps_pq)\n if(bricks < 0) : return i\n return len(H) - 1\n```\n\n***Time Complexity :*** **`O(NlogL)`**, where *`N`* is the number of buildings and *`L`* is the number of ladders available. A push operation in priority queue takes `O(logn)` time complexity, where *`n`* is size of the queue. Here, we are pushing into the priority queue `N` time and the max size of the queue at anytime would be `L`, so the final time complexity comes out to be `O(NlogL)`.\n***Space Complexity :*** **`O(L)`**\n\n---\n\n\u2714\uFE0F ***Solution - II (Using Max-Heap)***\n\nIn C++, there\'s a clean way to use max-heap (*priorityqueue* is max_heap by default) as a min-heap if you don\'t like the slightly complex syntax required to declare min-heap.\n\nThe process will remaint the same as the above. Here, since we are using max-heap, the only difference is we will push negative of *`jumpHeight`* and add these negative height to bricks every time we pop (instead of direct pushing & subtraction in above solution).\n\n\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tpriority_queue<int> pq;\n\tint n = size(H), i = 0, jumpHeight = 0;\n\tfor(; i < n - 1; i++) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight <= 0) continue;\n\t\tpq.push(-jumpHeight); // notice the \'-\'\n\t\tif(size(pq) > ladders) \n\t\t\tbricks += pq.top(), pq.pop();\n\t\tif(bricks < 0) return i;\n\t}\n\treturn i;\n}\n```\n \n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n \n---\n \n\u2714\uFE0F ***Solution - III (Using multiset)*** \n\nWe can also use multiset to maintain sorted jumps (multiset because there maybe multiple jumps of same height). Although, using multiset in this case will be slightly slower than priority_queue, I am just mentioning this here as well as a possible solution -\n\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\t multiset<int> s;\n int n = size(H), i = 0, jumpHeight = 0;\n for(; i < n - 1; i++) {\n jumpHeight = H[i + 1] - H[i];\n if(jumpHeight <= 0) continue;\n s.insert(jumpHeight);\n if(size(s) > ladders)\n bricks -= *begin(s), s.erase(begin(s));\n if(bricks < 0) return i;\n }\n return i;\n }\n```\n\n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n \n---\n\n\u2714\uFE0F ***Solution IV (Using map)***\n\nAgain, this wouldn\'t perform any better than using `priority_queue` / `heap`, but this one\'s a very commonly used data structure, so I am putting the solution using this as well. Also, this might actually be more space efficient if there are multiple jumps of same height in our path since we wouldn\'t have to store each of them separately & just maintain their count.\n\n**C++**\n```\nint furthestBuilding(vector<int>& H, int bricks, int ladders) {\n\tmap<int, short> mp;\n\tint n = size(H), i = 0, jumpHeight = 0;\n\tfor(; i < n - 1; i++) {\n\t\tjumpHeight = H[i + 1] - H[i];\n\t\tif(jumpHeight <= 0) continue;\n\t\tmp[jumpHeight]++;\n\t\tif(ladders--<=0){ \n\t\t\tbricks -= begin(mp) -> first;\n\t\t\tif(!--begin(mp) -> second) \n\t\t\t\tmp.erase(begin(mp));\n\t\t}\n\t\tif(bricks < 0) return i;\n\t}\n\treturn i;\n}\n```\n\n---\n\n**Python**\n```\nfrom sortedcontainers import SortedDict\ndef furthestBuilding(self, H: List[int], bricks: int, ladders: int) -> int:\n\tjumps = SortedDict()\n\tfor i in range(len(H) - 1):\n\t\tjump_height = H[i + 1] - H[i]\n\t\tif jump_height <= 0: continue\n\t\tjumps[jump_height], ladders = jumps.get(jump_height, 0) + 1, ladders - 1\n\t\tif ladders < 0:\n\t\t\ttop = jumps.peekitem(0)[0]\n\t\t\tbricks -= top\n\t\t\tjumps[top] -= 1\n\t\t\tif jumps[top] == 0 : jumps.popitem(0)\n\t\tif(bricks < 0) : return i\n\treturn len(H) - 1\n```\n\n***Time Complexity :*** **`O(NlogL)`**\n***Space Complexity :*** **`O(L)`**\n\n---\n\n*Best Runtime (Using `Solution - I / II`) -*\n\n\n<table><tr><td><img src= /></td></tr></table>\n \n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n--- | 87,470 |
Maximum Repeating Substring | maximum-repeating-substring | For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. | String,String Matching | Easy | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. | 2,825 | 23 | ```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n if word not in sequence:\n return 0\n\n left = 1\n right = len(sequence) // len(word)\n while left <= right:\n mid = (left + right) // 2\n if word * mid in sequence:\n left = mid + 1\n else:\n right = mid - 1 \n \n return left - 1\n``` | 87,514 |
Maximum Repeating Substring | maximum-repeating-substring | For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. | String,String Matching | Easy | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. | 2,407 | 10 | ```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n if len(sequence) < len(word):\n return 0\n ans = 0\n k = 1\n while word*k in sequence:\n ans += 1\n k += 1\n return ans\n``` | 87,522 |
Maximum Repeating Substring | maximum-repeating-substring | For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. | String,String Matching | Easy | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. | 762 | 9 | ```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n count=0\n while True:\n if word*(count+1) not in sequence:\n return count\n count+=1\n```\n\tE.g.:\n\tSequence = "ababa"\n\tword = "ab"\n\t\n\t1. Initially set count to 0, saying that word might not be present in sequence.\n\t2. word * (count+1) = word * (0+1) = word * 1 = word = ab is present in sequence. Increment count by 1, count =1.\n\t3. Now, word * (count+1) = word * (1+1) = word * 2 = abab is also present in sequence. Increment count by 1, count=2.\n\t4. Now, similarly word * (count+1) = ababab in not present in Sequence so return the last successful count (= 2). | 87,530 |
Maximum Repeating Substring | maximum-repeating-substring | For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. Given strings sequence and word, return the maximum k-repeating value of word in sequence. | String,String Matching | Easy | The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating. | 695 | 5 | We multiply the word and check occurence with `in`. \n```\nclass Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n i = 0\n while word*(i+1) in sequence:\n i+=1\n return i\n``` | 87,535 |
Merge In Between Linked Lists | merge-in-between-linked-lists | You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. | Linked List | Medium | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. | 999 | 14 | ```\n\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n head = list1\n for _ in range(a-1):\n head = head.next\n cur = head.next\n for _ in range(b-a):\n cur = cur.next\n head.next = list2\n while head.next:\n head = head.next\n if cur.next:\n head.next = cur.next\n return list1\n```\nPlease upvote if you get it. | 87,591 |
Merge In Between Linked Lists | merge-in-between-linked-lists | You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. | Linked List | Medium | Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1. | 1,415 | 16 | This is my approach to the problem using 2 pointers :\n```\nclass Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n # Define 2 pointers\n\t\tptr1 = list1\n ptr2 = list1\n i, j = 0, 0\n\t\t\n\t\t# Loop for pointer 1 to reach previous node from a\n while i!=a-1:\n ptr1 = ptr1.next\n i += 1 \n\t\t\t\n\t\t# Loop for pointer 2 to reach node b\n while j!=b:\n ptr2 = ptr2.next\n j += 1\n\t\t\t\n\t\t# Connect list2 to the next of pointer1\n ptr1.next = list2\n\t\t\n\t\t# Traverse the list2 till end node\n while list2.next!=None:\n list2 = list2.next\n\t\t\n\t\t# Assign the next of pointer 2 to the next of list2 i.e connect the remaining part of list1 to list2\n list2.next = ptr2.next\n\t\t\n\t\t# return final list\n return list1\n```\n\nFeel free to comment down your solutions as well :) | 87,595 |
Minimum Number of Removals to Make Mountain Array | minimum-number-of-removals-to-make-mountain-array | You may recall that an array arr is a mountain array if and only if: Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array. | Array,Binary Search,Dynamic Programming,Greedy | Hard | Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close | 525 | 10 | The code can be made shorter by combining both inc and dec, but it decreases readibility of the code.\n```\nclass Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n n = len(nums)\n inc = [0] * n\n dec = [0] * n\n \n# Longest Increasing Subsequence\n for i in range(1,n):\n for j in range(0,i):\n if nums[i] > nums[j]:\n inc[i] = max(inc[i], inc[j] + 1)\n \n# Longest Decreasing Subsequence\n for i in range(n-2,-1,-1):\n for j in range(n-1,i,-1):\n if nums[i] > nums[j]:\n dec[i] = max(dec[i], dec[j] + 1)\n \n# Final calculation\n res = 0\n for i in range(0,n):\n if inc[i] > 0 and dec[i] > 0:\n res = max(res, inc[i] + dec[i])\n \n# Final conclusion \n return n - res - 1\n``` | 87,631 |
Get Maximum in Generated Array | get-maximum-in-generated-array | You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums. | Array,Dynamic Programming,Simulation | Easy | Try generating the array. Make sure not to fall in the base case of 0. | 1,171 | 14 | ![image.png]()\n\nPlease UPVOTE if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!\n\n# Python3\n```\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n dp=[0,1]\n for i in range(2,n + 1):\n dp + =[dp[i//2] if i % 2==0 else dp[i//2] + dp[i//2 + 1]]\n return max(dp[:n + 1])\n\n``` | 87,707 |
Get Maximum in Generated Array | get-maximum-in-generated-array | You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums. | Array,Dynamic Programming,Simulation | Easy | Try generating the array. Make sure not to fall in the base case of 0. | 829 | 8 | **Python :**\n\n```\ndef getMaximumGenerated(self, n: int) -> int:\n\tif not n:\n\t\treturn n\n\n\tnums = [0] * (n + 1)\n\tnums[1] = 1\n\n\tfor i in range(2, n + 1): \n\t\tif i % 2:\n\t\t\tnums[i] = nums[i // 2] + nums[i // 2 + 1]\n\n\t\telse:\n\t\t\tnums[i] = nums[i // 2]\n\n\treturn max(nums)\n```\n\n**Like it ? please upvote !** | 87,716 |
Get Maximum in Generated Array | get-maximum-in-generated-array | You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums. | Array,Dynamic Programming,Simulation | Easy | Try generating the array. Make sure not to fall in the base case of 0. | 620 | 12 | Constructive solutions were posted before, but did you know that generators allow you get rid of used array parts, like a space shuttle gets rid of spent fuel tanks?\n\n```\nfrom queue import deque\n\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n \n def arrgen(n):\n yield 0\n q = deque([1])\n while True:\n yield q[0]\n q.append(q[0])\n q.append(q[0]+q[1])\n q.popleft()\n \n g = arrgen(n)\n return max(next(g) for _ in range(n+1)) | 87,730 |
Get Maximum in Generated Array | get-maximum-in-generated-array | You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way: Return the maximum integer in the array nums. | Array,Dynamic Programming,Simulation | Easy | Try generating the array. Make sure not to fall in the base case of 0. | 2,105 | 8 | \tclass Solution:\n\t\tdef getMaximumGenerated(self, n: int) -> int:\n\t\t\tif n==0: return 0\n\t\t\tarr = [0, 1]\n\t\t\tfor i in range(2, n+1):\n\t\t\t\tif i%2==0:\n\t\t\t\t\tarr.append(arr[i//2])\n\t\t\t\telse:\n\t\t\t\t\tarr.append(arr[i//2] + arr[i//2 + 1])\n\t\t\treturn max(arr)\n\t\t\t\nThe Basic Idea is that given our constraints and the Question itself, we can simply just generate the array by simulating what is needed. So, we start with our base array of `[0, 1]` and for any `N > 1` we generate the array as following:\n* If our index is even: we divide the index by 2 and append that result to our base array.\n* If our index is odd: we divide the index by 2 ( and considering only the integer of it, so 7//2 = 3 and not 3.5 ) and use that index and the next of that index.\n\nWe hence generate the entire array from 0 to N, so N+1 elements, and our job now is to only find the maximum of this array. \n\n**Note:** This takes a O(N) time and O(N) space in generating the array. | 87,733 |
Minimum Deletions to Make Character Frequencies Unique | minimum-deletions-to-make-character-frequencies-unique | A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. | String,Greedy,Sorting | Medium | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | 1,086 | 22 | # Python3 | 98.24% | Greedy Approach | Easy to Understand\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n for char, freq in cnt.items():\n while freq > 0 and freq in used_frequencies:\n freq -= 1\n deletions += 1\n used_frequencies.add(freq)\n \n return deletions\n``` | 87,749 |
Minimum Deletions to Make Character Frequencies Unique | minimum-deletions-to-make-character-frequencies-unique | A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. | String,Greedy,Sorting | Medium | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | 2,655 | 33 | # Intuition\nUsing HashMap to count each character and Set to keep unique frequency of chracters.\n\n---\n\n# Solution Video\n\n\n\nMinor update:\nIn the video, I use Set and variable name is "uniq_set". It\'s a little bit weird because values in Set are usually unique, so we should use variable name like "freq_set".\n\nIn the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\nThe next subscriber is exact 2300.\n\u2B50\uFE0F Today is my birthday. Please give me the gift of subscribing to my channel\uFF01\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2299\nThank you for your support!\n\n---\n\n# Approach\n\n```\nInput: s = "aaabbbcc"\n```\n\n## \u25A0 Step 1\nCreate HashMap`chars`. key is character and value is frequency of the character.\n```\nchars = {"a": 3, "b": 3, "c": 2}\n```\n\nInitialize `freq_set` with Set and `count` with 0. `freq_set` is used to keep unique frequency of chracters and `count` is return value.\n\n## \u25A0 Step 2\nStart iteration with `chars`.\n\n##### 2-1\nReagarding `"a": 3` in HashMap, `freq` is now `3`. `freq` doesn\'t meet the condition below\n```\nwhile freq > 0 and freq in freq_set:\n```\nSo, just add `3` to `freq_set`\n```\nNow freq_set = {3}, count = 0\n```\n\n##### 2-2\nReagarding `"b": 3` in HashMap, `freq` is now `3`. `freq` meets the `while condition` above, so we need to add `-1` to `freq`. Now `freq = 2` and add `1` to `count`. Then, check the `while condition` again. `freq` doesn\'t meet the condition, so add `freq = 2` to `freq_set` .\n\n```\nNow freq_set = {2, 3}, count = 1\n```\n\n##### 2-3\nReagarding `"c": 2` in HashMap, `freq` is now `2`. `freq` meets the `while condition` above, so we need to add `-1` to `freq`. Now `freq = 1` and add `1` to `count`. Then check the `while condition` again. `freq` doesn\'t meet the condition, so add `1` to `freq_set`.\n```\nNow freq_set = {1, 2, 3}, count = 2\n```\n\n```\nOutput: 2\n```\n\n# Complexity\n- Time complexity: O(n)\nWe count frequency of each character and store them to HashMap. For example, `Input: s = "aaabbbcc"`, we count them 8 times. `Input: s = "aaabbbccdd"`, we count them 10 times. It depends on length of input string.\n\n- Space complexity: O(1)\nWe will not store more than 26 different frequencies. Because we have constraint saying "s contains only lowercase English letters". It does not grow with length of input string or something. In the worst case O(26) \u2192 O(1)\n\n```python []\nclass Solution:\n def minDeletions(self, s: str) -> int:\n chars = Counter(s)\n\n freq_set = set()\n count = 0\n\n for freq in chars.values():\n while freq > 0 and freq in freq_set:\n freq -= 1\n count += 1\n \n freq_set.add(freq)\n\n return count\n```\n```javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar minDeletions = function(s) {\n const chars = new Map();\n for (const char of s) {\n chars.set(char, (chars.get(char) || 0) + 1);\n }\n\n const freqSet = new Set();\n let count = 0;\n\n for (let freq of chars.values()) {\n while (freq > 0 && freqSet.has(freq)) {\n freq--;\n count++;\n }\n\n freqSet.add(freq);\n }\n\n return count; \n};\n```\n```Java []\nclass Solution {\n public int minDeletions(String s) {\n Map<Character, Integer> chars = new HashMap<>();\n for (char c : s.toCharArray()) {\n chars.put(c, chars.getOrDefault(c, 0) + 1);\n }\n\n Set<Integer> freqSet = new HashSet<>();\n int count = 0;\n\n for (int freq : chars.values()) {\n while (freq > 0 && freqSet.contains(freq)) {\n freq--;\n count++;\n }\n freqSet.add(freq);\n }\n\n return count; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minDeletions(string s) {\n unordered_map<char, int> chars;\n for (char c : s) {\n chars[c]++;\n }\n\n unordered_set<int> freqSet;\n int count = 0;\n\n for (const auto& pair : chars) {\n int freq = pair.second;\n while (freq > 0 && freqSet.count(freq)) {\n freq--;\n count++;\n }\n freqSet.insert(freq);\n }\n\n return count; \n }\n};\n```\n | 87,760 |
Minimum Deletions to Make Character Frequencies Unique | minimum-deletions-to-make-character-frequencies-unique | A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. | String,Greedy,Sorting | Medium | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | 11,965 | 106 | # Comprehensive Guide to Solving "Minimum Deletions to Make Character Frequencies Unique"\n\n## Introduction & Problem Statement\n\nWelcome, code enthusiasts! Today, we\'re tackling an intriguing problem: **Minimum Deletions to Make Character Frequencies Unique**. Given a string `s` , the goal is to delete the minimum number of characters so that no two characters have the same frequency.\n\nFor instance, if the input string is "aaabbbcc", you can delete two \'b\'s to make the string "aaabcc", ensuring that each character has a unique frequency.\n\n## Key Concepts and Constraints\n\n### What Makes this Problem Unique?\n\n1. **Character Frequency**: \n Each character in the string `s` has a frequency, and we need to make sure no two characters share the same frequency after deletions.\n\n2. **Minimum Deletions**:\n The goal is to achieve this with the fewest number of deletions.\n\n3. **Constraints**: \n - The length of the string `s` , `n` , is between `1` and `10^5` .\n - The string `s` contains only lowercase English letters.\n\n---\n\n# Strategies to Tackle the Problem:\n\n## Live Coding & Explain Greedy\n\n\n## Greedy Algorithm 1/3: Minimizing Deletions Step by Step\n\n### What is a Greedy Algorithm?\nA Greedy Algorithm makes choices that seem the best at the moment. In the context of this problem, we\'ll try to make each character frequency unique by making the fewest number of changes to the existing frequencies.\n\n### Detailed Steps\n\n1. **Step 1: Count Frequencies** \n - **Why Count Frequencies?**: \n Before we can decide which characters to delete, we need to know how often each character appears. This is done using a frequency counter, stored in a dictionary `cnt`.\n \n2. **Step 2: Iterate and Minimize**\n - **Why Iterate Through Frequencies?**: \n We need to ensure that all character frequencies are unique. To do this, we iterate through the `cnt` dictionary. If a frequency is already used, we decrement it by 1 until it becomes unique, keeping track of these decrements in a variable `deletions`.\n\n3. **Step 3: Return Deletions**\n - **What is the Output?**: \n The function returns the total number of deletions (`deletions`) required to make all character frequencies unique.\n\n#### Time and Space Complexity\n- **Time Complexity**: $$O(n)$$, as you only iterate through the list once.\n- **Space Complexity**: $$O(n)$$, to store the frequencies in `cnt` and the used frequencies in `used_frequencies`.\n\n## Code Greedy\n``` Python []\n# Greedy Approach\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n for char, freq in cnt.items():\n while freq > 0 and freq in used_frequencies:\n freq -= 1\n deletions += 1\n used_frequencies.add(freq)\n \n return deletions\n```\n``` Go []\nfunc minDeletions(s string) int {\n cnt := make(map[rune]int)\n deletions := 0\n used_frequencies := make(map[int]bool)\n \n for _, c := range s {\n cnt[c]++\n }\n \n for _, freq := range cnt {\n for freq > 0 && used_frequencies[freq] {\n freq--\n deletions++\n }\n used_frequencies[freq] = true\n }\n \n return deletions\n}\n```\n``` Rust []\nuse std::collections::HashMap;\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn min_deletions(s: String) -> i32 {\n let mut cnt = HashMap::new();\n let mut deletions = 0;\n let mut used_frequencies = HashSet::new();\n \n for c in s.chars() {\n *cnt.entry(c).or_insert(0) += 1;\n }\n \n for freq in cnt.values() {\n let mut f = *freq;\n while f > 0 && used_frequencies.contains(&f) {\n f -= 1;\n deletions += 1;\n }\n used_frequencies.insert(f);\n }\n \n deletions\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int minDeletions(std::string s) {\n std::unordered_map<char, int> cnt;\n int deletions = 0;\n std::unordered_set<int> used_frequencies;\n \n for (char c : s) {\n cnt[c]++;\n }\n \n for (auto& kv : cnt) {\n int freq = kv.second;\n while (freq > 0 && used_frequencies.find(freq) != used_frequencies.end()) {\n freq--;\n deletions++;\n }\n used_frequencies.insert(freq);\n }\n \n return deletions;\n }\n};\n```\n``` Java []\npublic class Solution {\n public int minDeletions(String s) {\n HashMap<Character, Integer> cnt = new HashMap<>();\n int deletions = 0;\n HashSet<Integer> used_frequencies = new HashSet<>();\n \n for (char c : s.toCharArray()) {\n cnt.put(c, cnt.getOrDefault(c, 0) + 1);\n }\n \n for (int freq : cnt.values()) {\n while (freq > 0 && used_frequencies.contains(freq)) {\n freq--;\n deletions++;\n }\n used_frequencies.add(freq);\n }\n \n return deletions;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar minDeletions = function(s) {\n const cnt = {};\n let deletions = 0;\n const used_frequencies = new Set();\n \n for (const c of s) {\n cnt[c] = (cnt[c] || 0) + 1;\n }\n \n for (const freq of Object.values(cnt)) {\n let f = freq;\n while (f > 0 && used_frequencies.has(f)) {\n f--;\n deletions++;\n }\n used_frequencies.add(f);\n }\n \n return deletions;\n}\n```\n``` PHP []\nclass Solution {\n\n /**\n * @param String $s\n * @return Integer\n */\n function minDeletions($s) {\n $cnt = [];\n $deletions = 0;\n $used_frequencies = [];\n \n foreach (str_split($s) as $c) {\n $cnt[$c] = ($cnt[$c] ?? 0) + 1;\n }\n \n foreach ($cnt as $freq) {\n while ($freq > 0 && in_array($freq, $used_frequencies)) {\n $freq--;\n $deletions++;\n }\n $used_frequencies[] = $freq;\n }\n \n return $deletions;\n}\n}\n```\n``` C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public int MinDeletions(string s) {\n Dictionary<char, int> cnt = new Dictionary<char, int>();\n int deletions = 0;\n HashSet<int> used_frequencies = new HashSet<int>();\n \n foreach (char c in s) {\n if (cnt.ContainsKey(c)) cnt[c]++;\n else cnt[c] = 1;\n }\n \n foreach (int freqReadOnly in cnt.Values) {\n int freq = freqReadOnly;\n while (freq > 0 && used_frequencies.Contains(freq)) {\n freq--;\n deletions++;\n }\n used_frequencies.Add(freq);\n }\n \n return deletions;\n }\n}\n```\n\n---\n\n## Sorting Algorithm 2/3: Sort and Minimize\n\n### Detailed Steps\n\n#### Step 1: Count and Sort Frequencies\n\n- **Why Sort?**: \n Sorting brings an order to the chaos. When you sort the frequencies in descending order, you can start adjusting from the highest frequency downwards. This is beneficial because higher frequencies have a greater range of potential unique lower frequencies they can be adjusted to. For example, a frequency of 10 can be decreased to any of 9, 8, 7, ... until it becomes unique, giving us more "room" to make adjustments.\n\n#### Step 2: Iterate and Minimize\n\n- **Why Iterate Through Sorted Frequencies?**: \n After sorting, the frequencies are now in an ordered list, `sorted_freqs`. We iterate through this list, and for each frequency, we decrease it until it becomes unique. The advantage of working with sorted frequencies is that we can minimize the number of operations by taking advantage of the "room" lower frequencies offer for adjustment.\n\n#### Step 3: Early Exit Optimization\n\n- **Why Early Exit?**: \n An important optimization is to exit the loop early when you find a frequency that is already unique. In a sorted list, if you encounter a frequency that is unique, then all frequencies that come after it in the list will also be unique. This is because they will all be smaller and we have already confirmed that larger frequencies are unique.\n\n#### Step 4: Return Deletions\n\n- **What is the output?**: \n After iterating through `sorted_freqs` and making the necessary adjustments, we return the total number of deletions required to make the frequencies unique.\n\n### Time and Space Complexity\n\n- **Time Complexity**: $$ O(n \\log n) $$ due to sorting. Sorting the frequencies is the most time-consuming part here.\n- **Space Complexity**: $$ O(n) $$ for storing frequencies and used frequencies.\n\n## Code Sorting\n``` Python []\n# Sorting Approach\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n sorted_freqs = sorted(cnt.values(), reverse=True)\n \n for freq in sorted_freqs:\n if freq not in used_frequencies: # Early exit condition\n used_frequencies.add(freq)\n continue \n\n while freq > 0 and freq in used_frequencies:\n freq -= 1\n deletions += 1\n\n used_frequencies.add(freq)\n \n return deletions\n```\n``` Go []\nfunc minDeletions(s string) int {\n\tcnt := make(map[rune]int)\n\tdeletions := 0\n\tused_frequencies := make(map[int]bool)\n\n\tfor _, c := range s {\n\t\tcnt[c]++\n\t}\n\n\tsortedFreqs := make([]int, 0, len(cnt))\n\tfor _, freq := range cnt {\n\t\tsortedFreqs = append(sortedFreqs, freq)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(sortedFreqs)))\n\n\tfor _, freq := range sortedFreqs {\n\t\tfor freq > 0 && used_frequencies[freq] {\n\t\t\tfreq--\n\t\t\tdeletions++\n\t\t}\n\t\tused_frequencies[freq] = true\n\t}\n\n\treturn deletions\n}\n```\n\n---\n\n## Heap / Priority Queue 3/3: Prioritize Frequencies to Adjust\n\n### Detailed Steps\n\n#### Step 1: Count Frequencies and Build Heap\n\n- **Why Use a Heap?**: \n A min-heap is a specialized tree-based data structure that keeps the smallest element at the top. In the context of this problem, the smallest frequency will always be at the top of the heap. This allows us to focus on making the smallest frequencies unique first, which is generally easier and requires fewer adjustments.\n\n#### Step 2: Iterate and Minimize Using Heap\n\n- **Why Heap?**: \n The heap automatically "tells" us which frequency should be adjusted next (it will be the smallest one). We pop this smallest frequency and make it unique by decrementing it until it no longer matches any other frequency. The advantage here is that the heap dynamically updates, so after each adjustment, the next smallest frequency is ready for us to examine.\n\n### Time and Space Complexity\n\n- **Time Complexity**: $$ O(n \\log n) $$ due to heap operations. Each insertion and removal from the heap takes $$ \\log n $$ time, and we may need to do this $$ n $$ times.\n- **Space Complexity**: $$ O(n) $$ for storing the frequencies in `cnt` and the used frequencies in `used_frequencies`.\n\n\n## Code Heap\n``` Python []\n# Heap / Priority Queue Approach\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n heap = list(cnt.values())\n heapq.heapify(heap)\n \n while heap:\n freq = heapq.heappop(heap)\n while freq > 0 and freq in used_frequencies:\n freq -= 1\n deletions += 1\n used_frequencies.add(freq)\n \n return deletions\n```\n``` Go []\nimport (\n\t"container/heap"\n\t"fmt"\n)\n\ntype IntHeap []int\n\nfunc (h IntHeap) Len() int { return len(h) }\nfunc (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }\nfunc (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *IntHeap) Push(x interface{}) {\n\t*h = append(*h, x.(int))\n}\n\nfunc (h *IntHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\nfunc minDeletions(s string) int {\n\tcnt := make(map[rune]int)\n\tdeletions := 0\n\tused_frequencies := make(map[int]bool)\n\n\tfor _, c := range s {\n\t\tcnt[c]++\n\t}\n\n\th := &IntHeap{}\n\theap.Init(h)\n\n\tfor _, freq := range cnt {\n\t\theap.Push(h, freq)\n\t}\n\n\tfor h.Len() > 0 {\n\t\tfreq := heap.Pop(h).(int)\n\t\tfor freq > 0 && used_frequencies[freq] {\n\t\t\tfreq--\n\t\t\tdeletions++\n\t\t}\n\t\tused_frequencies[freq] = true\n\t}\n\n\treturn deletions\n}\n```\n\n---\n\n## Performance\n\n| Language | Approach | Execution Time (ms) | Memory Usage (MB) |\n|------------|-----------|---------------------|-------------------|\n| Rust | Greedy | 31 | 2.5 |\n| Go | Heap | 51 | 6.8 |\n| Java | Greedy | 50 | 45 |\n| C++ | Greedy | 75 | 17.5 |\n| Go | Greedy | 62 | 6.6 |\n| PHP | Greedy | 95 | 26.2 |\n| Python3 | Heap | 99 | 17.1 |\n| Python3 | Greedy | 105 | 17.2 |\n| C# | Greedy | 105 | 42.8 |\n| Python3 | Sorting | 106 | 17.1 |\n| JavaScript | Greedy | 125 | 48.4 |\n\n![b12.png]()\n\n\n## Live Coding & Explain Heap & Sort\n\n\n## Code Highlights and Best Practices\n\n- The Greedy Algorithm is simple and efficient, making it a go-to approach for this problem.\n- The Sorting Algorithm provides another effective way to tackle this problem but with a slight overhead due to sorting.\n- The Heap / Priority Queue approach adds a layer of optimization by prioritizing which frequencies to adjust first.\n\nBy mastering these approaches, you\'ll be well-equipped to tackle other frequency-based or deletion-minimizing problems, which are common in coding interviews and competitive programming. So, are you ready to make some string frequencies unique? Let\'s get coding!\n\n\n | 87,764 |
Minimum Deletions to Make Character Frequencies Unique | minimum-deletions-to-make-character-frequencies-unique | A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. | String,Greedy,Sorting | Medium | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | 199 | 5 | \n\n# Code\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n d = Counter(s)\n ans = 0\n seen = set()\n for k, v in d.items():\n while v and v in seen:\n ans += 1\n v -= 1\n seen.add(v)\n return ans\n``` | 87,765 |
Minimum Deletions to Make Character Frequencies Unique | minimum-deletions-to-make-character-frequencies-unique | A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. | String,Greedy,Sorting | Medium | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | 12,380 | 189 | # Problem Understanding\nThe given problem **asks you to find the minimum number of characters you need to delete from a string s to make it "good."** A string is **considered "good" if there are no two different characters in it that have the same frequency.**\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this approach is that by **sorting the frequencies in non-decreasing order**, you can start from the highest frequency characters **and gradually decrease their frequencies by deleting characters until they become unique.** This ensures that you delete the minimum number of characters necessary to satisfy the condition of having no two different characters with the same frequency.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialize a vector freq of size 26** (for the lowercase English letters) to store the frequency of each character in the input string s. Initialize all elements of freq to 0.\n\n2. **Iterate through the characters of the string s and update the frequency of each character in the freq vector**.\n\n3. **Sort the freq vector** in ascending order. This will arrange the frequencies in non-decreasing order.\n\n4. Initialize a **variable del to keep track of the minimum deletions** required and set it to 0.\n\n5. Iterate through the sorted freq vector in reverse order, starting **from index 24 (since there are 26 lowercase English letters).**\n\n6. Inside the loop, check **if the current frequency freq[i] is greater than or equal to the next frequency freq[i+1]**. If it is, then you need to delete some characters to make them unique.\n\n7. Calculate the number of characters to delete to make freq[i] less than freq[i+1]. **This is done by subtracting freq[i+1] - 1 from freq[i] and setting freq[i] to this new value**. Update the del variable by adding this difference.\n\n8. Continue this process until you have iterated through all frequencies, or until you encounter a frequency of 0, indicating that there are no more characters of that frequency.\n\n9. **Finally, return the value of del**, which represents the minimum number of deletions required to make the string "good."\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(k), where k=26\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n# Code(Greedy Approach)\n```C++ []\nclass Solution {\npublic:\n int minDeletions(string s) {\n // Create a vector to store the frequency of each lowercase English letter (fixed size of 26).\n vector<int> freq(26, 0);\n\n // Iterate through the characters of the input string s to count their frequencies.\n for (char c : s) {\n freq[c - \'a\']++; // Increment the corresponding frequency counter.\n }\n\n // Sort the frequency vector in non-decreasing order.\n sort(freq.begin(), freq.end());\n\n // Initialize a variable to keep track of the minimum number of deletions needed.\n int del = 0;\n\n // Iterate through the sorted frequency vector in reverse order.\n for (int i = 24; i >= 0; i--) {\n // If the current frequency is 0, break the loop (no more characters with this frequency).\n if (freq[i] == 0) {\n break;\n }\n \n // Check if the current frequency is greater than or equal to the next frequency.\n if (freq[i] >= freq[i + 1]) {\n int prev = freq[i];\n // Reduce the current frequency to make it one less than the next frequency.\n freq[i] = max(0, freq[i + 1] - 1);\n // Update the deletion count by the difference between previous and current frequency.\n del += prev - freq[i];\n }\n }\n\n // Return the minimum number of deletions required to make the string "good."\n return del;\n }\n};\n```\n```Java []\nimport java.util.Arrays;\n\npublic class Solution {\n public int minDeletions(String s) {\n int[] freq = new int[26]; // Create an array to store character frequencies\n \n for (char c : s.toCharArray()) {\n freq[c - \'a\']++; // Count the frequency of each character\n }\n \n Arrays.sort(freq); // Sort frequencies in ascending order\n \n int del = 0; // Initialize the deletion count\n \n for (int i = 24; i >= 0; i--) {\n if (freq[i] == 0) {\n break; // No more characters with this frequency\n }\n \n if (freq[i] >= freq[i + 1]) {\n int prev = freq[i];\n freq[i] = Math.max(0, freq[i + 1] - 1);\n del += prev - freq[i]; // Update the deletion count\n }\n }\n \n return del; // Return the minimum deletions required\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def minDeletions(self, s: str) -> int:\n freq = [0] * 26 # Create a list to store character frequencies\n \n for c in s:\n freq[ord(c) - ord(\'a\')] += 1 # Count the frequency of each character\n \n freq.sort() # Sort frequencies in ascending order\n \n del_count = 0 # Initialize the deletion count\n \n for i in range(24, -1, -1):\n if freq[i] == 0:\n break # No more characters with this frequency\n \n if freq[i] >= freq[i + 1]:\n prev = freq[i]\n freq[i] = max(0, freq[i + 1] - 1)\n del_count += prev - freq[i] # Update the deletion count\n \n return del_count # Return the minimum deletions required\n\n```\n```Javascript []\nvar minDeletions = function(s) {\n let freq = new Array(26).fill(0); // Create an array to store character frequencies\n \n for (let i = 0; i < s.length; i++) {\n freq[s.charCodeAt(i) - \'a\'.charCodeAt(0)]++; // Count the frequency of each character\n }\n \n freq.sort((a, b) => a - b); // Sort frequencies in ascending order\n \n let del = 0; // Initialize the deletion count\n \n for (let i = 24; i >= 0; i--) {\n if (freq[i] === 0) {\n break; // No more characters with this frequency\n }\n \n if (freq[i] >= freq[i + 1]) {\n let prev = freq[i];\n freq[i] = Math.max(0, freq[i + 1] - 1);\n del += prev - freq[i]; // Update the deletion count\n }\n }\n \n return del; // Return the minimum deletions required\n};\n\n```\n# Code using Heap Method\n```C++ []\nclass Solution {\npublic:\n int minDeletions(string s) {\n // Create an unordered map to count the frequency of each character.\n unordered_map<char, int> mp;\n\n // Iterate through the characters in the input string \'s\'.\n for (auto &it : s) {\n mp[it]++; // Increment the character\'s frequency in the map.\n }\n\n // Create a max-heap (priority queue) to store character frequencies in decreasing order.\n priority_queue<int> pq;\n\n // Populate the max-heap with character frequencies from the map.\n for (auto &it : mp) {\n pq.push(it.second);\n }\n\n // Initialize a variable to keep track of the minimum number of deletions needed.\n int count = 0;\n\n // Continue as long as there are at least two frequencies in the max-heap.\n while (pq.size() != 1) {\n int top = pq.top(); // Get the character frequency with the highest count.\n pq.pop(); // Remove it from the max-heap.\n\n // Check if the next character in the max-heap has the same frequency as \'top\' (and it\'s not zero).\n if (pq.top() == top && top != 0) {\n count++; // Increment the deletion count.\n pq.push(top - 1); // Decrease \'top\' frequency by 1 and push it back into the max-heap.\n }\n }\n\n // Return the minimum number of deletions required to make the string "good."\n return count;\n }\n};\n\n```\n```java []\nimport java.util.HashMap;\nimport java.util.PriorityQueue;\nimport java.util.Map;\n\npublic class Solution {\n public int minDeletions(String s) {\n // Create a HashMap to count the frequency of each character.\n Map<Character, Integer> frequencyMap = new HashMap<>();\n\n // Iterate through the characters in the input string \'s\'.\n for (char c : s.toCharArray()) {\n frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);\n }\n\n // Create a max-heap (PriorityQueue) to store character frequencies in decreasing order.\n PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);\n\n // Populate the max-heap with character frequencies from the map.\n maxHeap.addAll(frequencyMap.values());\n\n // Initialize a variable to keep track of the minimum number of deletions needed.\n int count = 0;\n\n // Continue as long as there are at least two frequencies in the max-heap.\n while (maxHeap.size() > 1) {\n int top = maxHeap.poll(); // Get the character frequency with the highest count.\n\n // Check if the next character in the max-heap has the same frequency as \'top\' (and it\'s not zero).\n if (maxHeap.peek() != null && maxHeap.peek() == top && top != 0) {\n count++; // Increment the deletion count.\n maxHeap.add(top - 1); // Decrease \'top\' frequency by 1 and push it back into the max-heap.\n }\n }\n\n // Return the minimum number of deletions required to make the string "good."\n return count;\n }\n}\n\n```\n---\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n![upvotememe.png]()\n\n\n | 87,767 |
Sell Diminishing-Valued Colored Balls | sell-diminishing-valued-colored-balls | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. | Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue) | Medium | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. | 5,972 | 36 | Algo \nFirst, it should be clear that we want to sell from the most abundant balls as much as possible as it is valued more than less abundant balls. In the spirit of this, we propose the below algo \n1) sort inventory in reverse order and append 0 at the end (for termination); \n2) scan through the inventory, and add the difference between adjacent categories to answer. \n\nAssume `inventory = [2,8,4,10,6]`. Then, we traverse inventory following 10->8->6->4->2->0. The evolution of inventory becomes \n```\n10 | 8 | 6 | 4 | 2\n 8 | 8 | 6 | 4 | 2\n 6 | 6 | 6 | 4 | 2\n 4 | 4 | 4 | 4 | 2\n 2 | 2 | 2 | 2 | 2 \n 0 | 0 | 0 | 0 | 0 \n```\nOf course, if in any step, we have enough order, return the answer. \n\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True) # inventory high to low \n inventory += [0]\n ans = 0\n k = 1\n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i] - inventory[i+1]) < orders: \n ans += k*(inventory[i] + inventory[i+1] + 1)*(inventory[i] - inventory[i+1])//2 # arithmic sum \n orders -= k*(inventory[i] - inventory[i+1])\n else: \n q, r = divmod(orders, k)\n ans += k*(2*inventory[i] - q + 1) * q//2 + r*(inventory[i] - q)\n return ans % 1_000_000_007\n k += 1\n```\n\nEdited on 10/08/2020\nAdding binary serach solution \n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n fn = lambda x: sum(max(0, xx - x) for xx in inventory) # balls sold \n \n # last true binary search \n lo, hi = 0, 10**9\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if fn(mid) >= orders: lo = mid\n else: hi = mid - 1\n \n ans = sum((x + lo + 1)*(x - lo)//2 for x in inventory if x > lo)\n return (ans - (fn(lo) - orders) * (lo + 1)) % 1_000_000_007\n``` | 87,809 |
Sell Diminishing-Valued Colored Balls | sell-diminishing-valued-colored-balls | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. | Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue) | Medium | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. | 4,099 | 31 | To preface, this answer was heavily inspired by this post \nCheck out that post if you want an explanation for what\'s going on.\n\n\nI thought it was more intuitive to create a sumRange helper function to compute the profit.\nThis function is essentially a modification of the gaussian sum equation. \nEx. sumRange(3, 6) -> 3 + 4 + 5 + 6 = 18\n\n```\ndef maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True)\n inventory.append(0)\n profit = 0\n width = 1\n for i in range(len(inventory)-1):\n if inventory[i] > inventory[i+1]:\n if width * (inventory[i] - inventory[i+1]) < orders:\n profit += width * self.sumRange(inventory[i+1]+1, inventory[i])\n orders -= width * (inventory[i] - inventory[i+1])\n else:\n whole, remaining = divmod(orders, width)\n profit += width * self.sumRange(inventory[i]-whole+1, inventory[i])\n profit += remaining * (inventory[i]-whole)\n break\n width += 1\n return profit % (10**9 + 7)\n \n \ndef sumRange(self, lo, hi):\n\t# inclusive lo and hi\n\treturn (hi * (hi+1)) // 2 - (lo * (lo-1)) // 2\n``` | 87,811 |
Sell Diminishing-Valued Colored Balls | sell-diminishing-valued-colored-balls | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. | Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue) | Medium | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. | 3,008 | 12 | Video with clear visualization and explanation:\n\n\n\nIntuition: Greedy/Math\nKey equation: Arithmetic series sum:\nn+(n-1)+\u2026+(n-d)=(n+(n-d))x(d+1)/2\n\n**Code**\nInspired by \n\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True) \n inventory += [0]\n res = 0\n k = 1\n \n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i]-inventory[i+1]) < orders:\n diff = inventory[i]-inventory[i+1]\n res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2\n orders -= k*diff\n else: \n q, r = divmod(orders, k)\n res += k*(inventory[i]+(inventory[i]-q+1))*q//2\n res += r*(inventory[i]-q)\n return res%(10**9+7)\n k += 1\n```\n\n\nTime: O(nlogn)\nSpace: O(1)\n\nFeel free to subscribe to my channel. More LeetCoding videos coming up! | 87,819 |
Sell Diminishing-Valued Colored Balls | sell-diminishing-valued-colored-balls | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. | Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue) | Medium | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. | 1,644 | 14 | ```\nclass Solution:\n def maxProfit(self, inventory, orders: int) -> int:\n left = 0\n right = max(inventory)\n while right - left > 1:\n middle = (left + right) // 2\n sold_balls = sum(i - middle for i in inventory if i > middle)\n if sold_balls > orders:\n left = middle\n else:\n right = middle\n sold_balls = 0\n total_value = 0\n for i in inventory:\n if i > right:\n sold_balls += i - right\n total_value += (i + right + 1) * (i - right) // 2\n if sold_balls < orders:\n total_value += (orders - sold_balls) * right\n return total_value % 1_000_000_007\n``` | 87,821 |
Sell Diminishing-Valued Colored Balls | sell-diminishing-valued-colored-balls | You have an inventory of different colored balls, and there is a customer that wants orders balls of any color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order. Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7. | Array,Math,Binary Search,Greedy,Sorting,Heap (Priority Queue) | Medium | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. | 1,336 | 8 | We solve this problem using a heap and a Counter (or a hashmap, if you like). The max heap picks the maximum element available and helps us calculate the differences between the maximum and the next possible maximum element. The counter just neatly keeps a track of the frequency of balls at its respective ball count. \n\n![image]()\n\nHere: \n* `Height h` = Difference between current highest frequency and the next highest frequency. \n* `Width w` = Count of balls having the given frequency (or above).\n* `order` = Amount of balls ordered.\n\nConsidering pass #1:\nThe `order` amount exceeds the `h * w` product, so we just deduct it from the order amount. Since `w` amount of balls are also present in the next highest frequency, we add `w` to the next highest frequency in the counter. \n\nConsidering pass#2 in both the cases:\n* **Balls in currently considered group>order amount** - Case 1: Balls remaining in order = 5\n\t* `Width w` (count of balls at frequency) = 3; `Height h` (difference between current frequency and the next highest frequency) = 2. Does this exceed the remaining order amount? Yes. \n\t* Hence, we take `(h - k) * w` amount of balls, followed by a remainder amount `r`. Since the initial `h * w` exceeded the `order` amount, we can safely say that the `(h - k) * w + remainder` would cover the order amount, and we can break out of the loop. \n\t* What height of balls would we take? `h = order//w`, and the remainder `r = order%w`\n\t* We wouldn\'t have to make any modifications to the heap or the counter after this condition. \n\t\n* **Balls in currently considered group<=order amount**Case 2: Balls remaining in order = 6:\n\t* This matches pass #1. We deduct `h * w` from the `order` amount.\n\n**Getting the amount**\n* In a certain pass, we see that <code>(\u03A3 (w * h<sub>i</sub>)) + (r * (h - k))</code> is added to the amount. \n* <code>h<sub>i</sub></code> = <code>curV - i</code>, where <code>i</code> lies in the range <code>0 to h (h excluded)</code>and an amount `r * (curV - h)` is also added (the cost for the remaining balls).\n\nAdditionally, we\'re considering a `[0]` in the heap, because it would help if ~all the items are considered. \n\nRuntime: 664ms (90.40%); \nMemory: 32.8mb (16.73%)\n\n```\ndef maxProfit(self, inventory: List[int], orders: int) -> int:\n\n ctr = collections.Counter(inventory)\n ls = sorted([-k for k in ctr.keys()] + [0])\n\n maxEarn = 0\n ordersRemaining = True\n while orders and ls and ordersRemaining:\n curV = -heapq.heappop(ls)\n nxV = -ls[0]\n height = curV - nxV\n divM = 0\n width = ctr[curV]\n if (width * height) > orders:\n ordersRemaining = False\n height, divM = map(int, divmod(orders, width))\n maxEarn = (\n maxEarn\n + (width * ((height * curV) - ((height * (height - 1)) // 2)))\n + (divM * (curV - height))\n )\n maxEarn = int(maxEarn % ((10 ** 9) + 7))\n orders = orders - (height * width) - divM\n if ordersRemaining:\n del ctr[curV]\n ctr[nxV] = ctr[nxV] + width\n orders = orders - (width * height)\n return int(maxEarn % (1e9 + 7))\n```\n\n(Typecasting, since there was an unknown conversion to float.)\n\nInitially, we were going down by 1 from the maxValue and not considering the previous max, which gave a TLE. \n\nAny additions or improvements are welcome. Happy coding. :) | 87,824 |
Create Sorted Array through Instructions | create-sorted-array-through-instructions | Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7 | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it | 772 | 6 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def createSortedArray(self, ins: List[int]) -> int:\n mod = 10**9+7\n dicti = defaultdict(int)\n s1 = SortedList()\n sum_ = 0\n \n for i in range(len(ins)):\n dicti[ins[i]] += 1\n s1.add(ins[i])\n if i == 0:\n sum_ = (sum_+0)%mod\n else:\n leftIndex = s1.bisect_left(ins[i])\n small = leftIndex - 0\n big = len(s1) - leftIndex\n if dicti[ins[i]]>0:\n big -= dicti[ins[i]]\n sum_ = (sum_+min(small,big))%mod\n return sum_ | 87,873 |
Create Sorted Array through Instructions | create-sorted-array-through-instructions | Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following: For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5]. Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7 | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it | 884 | 6 | Build a Fenwick Tree of size `m = 1e5` and query the number of elements in the range `[0,x)` in `O(log m)` time.\n* \n\n**Python**\n```python\nclass Solution:\n def createSortedArray(self, instructions):\n t = [0] * 100001\n \n def incr(i):\n while i < 100001:\n t[i] += 1\n i += i & -i\n \n def query(i):\n ret = 0\n while i > 0:\n ret += t[i]\n i -= i & -i\n return ret\n \n ans = 0\n for i, x in enumerate(instructions):\n ans += min(query(x - 1), i - query(x))\n ans %= 1000000007\n incr(x)\n\n return ans\n```\n**C++**\n```c++\nclass Solution {\npublic:\n static const int m = 100001;\n static const int mod = 1e9 + 7;\n int t[m];\n\n void incr(int i) {\n for (; i < m; i += i & -i) {\n t[i] += 1;\n }\n }\n \n int query(int i) {\n int sum = 0;\n for (; i > 0; i -= i & -i) {\n sum += t[i];\n }\n return sum;\n }\n \n int createSortedArray(vector<int>& A) {\n int ans = 0;\n for (int i = 0; i < A.size(); i++) {\n ans += min(query(A[i] - 1), i - query(A[i]));\n ans %= mod;\n incr(A[i]);\n }\n return ans;\n }\n};\n``` | 87,874 |
Design an Ordered Stream | design-an-ordered-stream | There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example: Constraints: | Array,Hash Table,Design,Data Stream | Easy | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. | 11,928 | 55 | \n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n self.data = [None]*n\n self.ptr = 0 # 0-indexed \n\n def insert(self, id: int, value: str) -> List[str]:\n id -= 1 # 0-indexed \n self.data[id] = value \n if id > self.ptr: return [] # not reaching ptr \n \n while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 # update self.ptr \n return self.data[id:self.ptr]\n``` | 87,955 |
Design an Ordered Stream | design-an-ordered-stream | There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example: Constraints: | Array,Hash Table,Design,Data Stream | Easy | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. | 3,622 | 29 | The idea behind this problem is simple but the description is confusing.\nSo let me explain a bit.\n\nBasically , we need to store every incoming value at the given index. And \nwith every incoming index, we have to check\n\n* If the current index is less than the incoming index, the we have to return\n an empty list\n\n* Else , we have to return an sliced list from the incoming index to the first index\n where there is no insertion till yet.\n\nSolution:\n* Initialize a list of size n with None\n* Maintain the current index with self.ptr\n* For every insert call, with idKey, value \n * Assign the list[idKey-1] to the value # Since array is 0-index reduce 1\n * Check if the current index is less than incoming index(idKey-1) and return []\n * Else return sliced list from incoming index(idKey-1) till we do not encounter None.\n\n\n```\nclass OrderedStream:\n\n def __init__(self, n):\n self.stream = [None]*n\n self.ptr = 0\n\n def insert(self, idKey, value):\n idKey -= 1\n self.stream[idKey] = value\n if self.ptr < idKey:\n return []\n else:\n while self.ptr < len(self.stream) and self.stream[self.ptr] is not None:\n self.ptr += 1\n return self.stream[idKey:self.ptr]\n\n\n# Your OrderedStream object will be instantiated and called as such:\n# obj = OrderedStream(n)\n# param_1 = obj.insert(idKey,value)\n``` | 87,960 |
Design an Ordered Stream | design-an-ordered-stream | There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example: Constraints: | Array,Hash Table,Design,Data Stream | Easy | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. | 1,111 | 11 | The description as of June 13th, 2022 mentions nothing a ptr. There is a ptr that should be initialized at 1. If an item is inserted with an idKey above the ptr, return nothing. If an item is inserted that matches the ptr, return the largest chunk of contiguous values above the ptr. The ptr should update to the index immediately after the returned chunk. \n\n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n self.ptr = 1\n self.hashmap = dict()\n \n\n def insert(self, idKey: int, value: str) -> List[str]:\n self.hashmap[idKey] = value\n output = []\n if idKey > self.ptr:\n return output\n \n while idKey in self.hashmap:\n output.append(self.hashmap[idKey])\n idKey += 1\n self.ptr = idKey\n \n return output\n``` | 87,972 |
Design an Ordered Stream | design-an-ordered-stream | There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values. Implement the OrderedStream class: Example: Constraints: | Array,Hash Table,Design,Data Stream | Easy | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. | 1,924 | 16 | ```\nclass OrderedStream:\n\n def __init__(self, n: int):\n self.seen = {}\n self.ptr = 1\n\n def insert(self, id: int, value: str) -> List[str]:\n seen, ptr = self.seen, self.ptr\n \n seen[id] = value\n result = []\n while ptr in seen:\n result.append(seen[ptr])\n del seen[ptr]\n ptr += 1\n \n self.ptr = ptr\n return result\n\n\n# Your OrderedStream object will be instantiated and called as such:\n# obj = OrderedStream(n)\n# param_1 = obj.insert(id,value)\n``` | 87,978 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 21,957 | 140 | # Comprehensive Guide to Solving "Minimum Operations to Reduce X to Zero"\n\n## Introduction & Problem Statement\n\nGiven an integer array `nums` and an integer `x`, the task is to find the minimum number of operations to reduce `x` to exactly 0 by removing either the leftmost or rightmost element from the array `nums` in each operation. What makes this problem intriguing is that it\'s not a straightforward minimization problem; it involves searching for subarrays, working with prefix sums, and applying two-pointer techniques.\n\n## Key Concepts and Constraints\n\n### What Makes This Problem Unique?\n\n1. **Array Constraints**: \n - $$1 \\leq \\text{nums.length} \\leq 10^5$$\n - $$1 \\leq \\text{nums}[i] \\leq 10^4$$\n \n2. **Target Number `x`**:\n - $$1 \\leq x \\leq 10^9$$\n\n3. **Operations**: \n You can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from $$ x $$.\n\n4. **Minimization Objective**: \n The goal is to minimize the number of operations to reduce $$ x $$ to zero.\n\n---\n\n## One Primary Strategy to Solve the Problem:\n\n## Live Coding & Explain\n\n\n# Approach: Sliding Window with Prefix Sum\n\nTo solve this problem, we apply the Sliding Window technique with a twist involving Prefix Sum. We use two pointers, `left` and `right`, to traverse the array `nums` and find the longest subarray whose sum equals the total sum of elements in `nums` minus `x`.\n\n## Key Data Structures:\n\n- **max_len**: An integer to store the length of the longest subarray that can be excluded to make the sum equal to `x`.\n- **cur_sum**: An integer to store the sum of elements in the current subarray.\n\n## Enhanced Breakdown:\n\n1. **Initialize and Calculate the Target**:\n - Compute `target = sum(nums) - x`, as we\'re interested in finding a subarray with this sum.\n - Initialize `max_len`, `cur_sum`, and `left` to 0.\n \n2. **Check for Edge Cases**:\n - If `target` is zero, it means we need to remove all elements to make the sum equal to `x`. In this case, return the total number of elements, `n`.\n\n3. **Traverse the Array with Two Pointers**:\n - Iterate through `nums` using a `right` pointer.\n - Update `cur_sum` by adding the current element `nums[right]`.\n \n4. **Sliding Window Adjustment**:\n - If `cur_sum` exceeds `target`, slide the `left` pointer to the right by one position and decrease `cur_sum` by `nums[left]`.\n\n5. **Update Max Length**:\n - If `cur_sum` matches `target`, update `max_len` with the length of the current subarray, which is `right - left + 1`.\n\n6. **Conclude and Return**:\n - After the loop, if `max_len` is non-zero, return `n - max_len`. Otherwise, return -1, indicating it\'s not possible to reduce `x` to zero.\n\n## Complexity Analysis:\n\n**Time Complexity**: \n- Since we traverse the array only once, the time complexity is $$ O(n) $$.\n\n**Space Complexity**: \n- The algorithm uses only a constant amount of extra space, thus having a space complexity of $$ O(1) $$.\n\n---\n\n# Code\n``` Python []\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n target, n = sum(nums) - x, len(nums)\n \n if target == 0:\n return n\n \n max_len = cur_sum = left = 0\n \n for right, val in enumerate(nums):\n cur_sum += val\n while left <= right and cur_sum > target:\n cur_sum -= nums[left]\n left += 1\n if cur_sum == target:\n max_len = max(max_len, right - left + 1)\n \n return n - max_len if max_len else -1\n```\n``` Go []\nfunc minOperations(nums []int, x int) int {\n target, n := -x, len(nums)\n for _, num := range nums {\n target += num\n }\n \n if target == 0 {\n return n\n }\n \n maxLen, curSum, left := 0, 0, 0\n \n for right, val := range nums {\n curSum += val\n for left <= right && curSum > target {\n curSum -= nums[left]\n left++\n }\n if curSum == target {\n if right - left + 1 > maxLen {\n maxLen = right - left + 1\n }\n }\n }\n \n if maxLen != 0 {\n return n - maxLen\n }\n return -1\n}\n```\n``` Rust []\nimpl Solution {\n pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {\n let mut target: i32 = -x;\n let n = nums.len() as i32;\n \n for &num in &nums {\n target += num;\n }\n \n if target == 0 {\n return n;\n }\n \n let (mut max_len, mut cur_sum, mut left) = (0, 0, 0);\n \n for right in 0..n as usize {\n cur_sum += nums[right];\n while left <= right as i32 && cur_sum > target {\n cur_sum -= nums[left as usize];\n left += 1;\n }\n if cur_sum == target {\n max_len = std::cmp::max(max_len, right as i32 - left + 1);\n }\n }\n \n if max_len != 0 { n - max_len } else { -1 }\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums, int x) {\n int target = 0, n = nums.size();\n for (int num : nums) target += num;\n target -= x;\n \n if (target == 0) return n;\n \n int max_len = 0, cur_sum = 0, left = 0;\n \n for (int right = 0; right < n; ++right) {\n cur_sum += nums[right];\n while (left <= right && cur_sum > target) {\n cur_sum -= nums[left];\n left++;\n }\n if (cur_sum == target) {\n max_len = max(max_len, right - left + 1);\n }\n }\n \n return max_len ? n - max_len : -1;\n }\n};\n```\n``` Java []\npublic class Solution {\n public int minOperations(int[] nums, int x) {\n int target = -x, n = nums.length;\n for (int num : nums) target += num;\n \n if (target == 0) return n;\n \n int maxLen = 0, curSum = 0, left = 0;\n \n for (int right = 0; right < n; ++right) {\n curSum += nums[right];\n while (left <= right && curSum > target) {\n curSum -= nums[left];\n left++;\n }\n if (curSum == target) {\n maxLen = Math.max(maxLen, right - left + 1);\n }\n }\n \n return maxLen != 0 ? n - maxLen : -1;\n }\n}\n```\n``` PHP []\nclass Solution {\n function minOperations($nums, $x) {\n $target = 0;\n $n = count($nums);\n foreach ($nums as $num) $target += $num;\n $target -= $x;\n \n if ($target === 0) return $n;\n \n $maxLen = $curSum = $left = 0;\n \n for ($right = 0; $right < $n; ++$right) {\n $curSum += $nums[$right];\n while ($left <= $right && $curSum > $target) {\n $curSum -= $nums[$left];\n $left++;\n }\n if ($curSum === $target) {\n $maxLen = max($maxLen, $right - $left + 1);\n }\n }\n \n return $maxLen ? $n - $maxLen : -1;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} x\n * @return {number}\n */\nvar minOperations = function(nums, x) {\n let target = -x, n = nums.length;\n for (let num of nums) target += num;\n \n if (target === 0) return n;\n \n let maxLen = 0, curSum = 0, left = 0;\n \n for (let right = 0; right < n; ++right) {\n curSum += nums[right];\n while (left <= right && curSum > target) {\n curSum -= nums[left];\n left++;\n }\n if (curSum === target) {\n maxLen = Math.max(maxLen, right - left + 1);\n }\n }\n \n return maxLen ? n - maxLen : -1;\n};\n```\n``` C# []\npublic class Solution {\n public int MinOperations(int[] nums, int x) {\n int target = -x, n = nums.Length;\n foreach (int num in nums) target += num;\n \n if (target == 0) return n;\n \n int maxLen = 0, curSum = 0, left = 0;\n \n for (int right = 0; right < n; ++right) {\n curSum += nums[right];\n while (left <= right && curSum > target) {\n curSum -= nums[left];\n left++;\n }\n if (curSum == target) {\n maxLen = Math.Max(maxLen, right - left + 1);\n }\n }\n \n return maxLen != 0 ? n - maxLen : -1;\n }\n}\n```\n\n## Performance\n\n| Language | Fastest Runtime (ms) | Memory Usage (MB) |\n|-----------|----------------------|-------------------|\n| Java | 4 | 56 |\n| Rust | 15 | 3 |\n| JavaScript| 76 | 52.8 |\n| C++ | 110 | 99 |\n| Go | 137 | 8.6 |\n| C# | 236 | 54.6 |\n| PHP | 340 | 31.8 |\n| Python3 | 913 | 30.2 |\n\n![v3.png]()\n\n\n## Live Coding in Rust\n\n\n## Conclusion\n\nThe problem "Minimum Operations to Reduce X to Zero" may look complicated initially due to its minimization objective. However, understanding the underlying logic of subarray sums and applying a sliding window approach can simplify it. This not only solves the problem efficiently but also enhances one\'s understanding of array manipulation techniques. Happy coding! | 87,999 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 6,853 | 60 | # Porblem Description\nGiven an array of integers, `nums`, and an integer `x`. Each element in `nums` can be subtracted from x. The **goal** is to reduce `x` to exactly `0` using a **minimum** number of operations.\n\nIn each **operation**, you can choose to **remove** either the `leftmost` or the `rightmost` element from the array `nums` and subtract its value from `x`.\n\n- **Constraints:**\n- `1 <= nums.length <= 10e5`\n- `1 <= nums[i] <= 10e4`\n- `1 <= x <= 10e9`\n\n---\n\n\n\n# Intuition\nHello There\uD83D\uDE00\nLet\'s take a look on our today\'s interesting problem\uD83D\uDE80\n\nToday we have **two things**, **array** of intergers and **number** `x`.\nWe can do **one** operation **each** time select `rightmost` or `leftmost` item from the array and **subtract** it from `x`.\nThe goal is to make `x` equal to `zero`.\n\nLook interesting \uD83E\uDD2F\nLet\'s **simplify** our problem a little ?\nWe only need to know **sum** of numbers from `right` and `left` that equal to `x`.\nBut how we get this number ?\uD83E\uDD14\nLet\'s see this example:\n```\nnums = (3, 4, 7, 1, 3, 8, 2, 4), x = 9\n```\nwe can see here that the answer of minimum elements from `left` and `right` (operations) is `3` which are `(3, 2, 4)`\nThere is also something interesting.\uD83E\uDD29\nWe can see that there is a subarray that we **didn\'t touch** which is `(4, 7, 1, 3, 8)`\n\nLet\'s make a **relation** between them\uD83D\uDE80\n```\nsum(3, 4, 7, 1, 3, 8, 2, 4) = sum(4, 7, 1, 3, 8) + sum(3, 2, 4)\nsum(3, 4, 7, 1, 3, 8, 2, 4) = sum(4, 7, 1, 3, 8) + x\nsum(3, 4, 7, 1, 3, 8, 2, 4) - x = sum(4, 7, 1, 3, 8) \n23 = sum(4, 7, 1, 3, 8) \n```\nWe can see something here.\uD83D\uDE00\nThat the `sum subarray` that I talked about before is the `sum of the whole array - x`\n\nOk we made a **relation** between them but **why** I walked through all of this ?\n\nThe reason is that we can **utilize** an efficient technique that is called **Two Pointers**.\uD83D\uDE80\uD83D\uDE80\n\nThats it, instead of finding the **minimum** number of operations from `leftmost` and `rightmost` elements. We can find the **continous subarray** that **anyother** element in the array is the **answer** to our **minimum** operations.\n\nAnd this is the solution for our today problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n---\n\n\n\n# Approach\n1. Calculate the total sum of elements.\n2. Compute the target value as the difference between the total sum and the provided target `x`.\n3. Check if the target value is `negative`; if so, return `-1` as the target sum is not achievable.\n4. Check if the target value is `zero`; if so, **return** the **size** of nums since we need to subtract **all** of the elements from x.\n5. Initialize pointers `leftIndex` and `rightIndex` to track a sliding window.\n6. Within the loop, check if `currentSum` exceeds the target value. If it does, increment `leftIndex` and update `currentSum`.\n7. Whenever `currentSum` equals the target value, calculate the **minimum** number of operations required and update `minOperations`.\n8. **Return** the **minimum** number of operations.\n\n---\n\n\n\n# Complexity\n- **Time complexity:**$$O(N)$$\nIn this method we have two pointers, each of them can iterate over the array at most once. So the complexity is `2 * N` which is `O(N)`.\n- **Space complexity:**$$O(1)$$\nWe are storing couple of variables and not storing arrays or other data structure so the complexity is `O(1)`.\n\n\n---\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums, int targetSum) {\n int totalSum = accumulate(nums.begin(), nums.end(), 0);\n int target = totalSum - targetSum; // Calculate the target sum difference\n\n if (target < 0)\n return -1; // Return -1 if target sum is not achievable\n\n if (target == 0)\n return nums.size(); // Return the number of elements if target sum is 0\n\n int n = nums.size(); // Number of elements in the vector\n int minOperations = INT_MAX; // Minimum operations to achieve the target sum\n int currentSum = 0; // Current sum of elements\n int leftIndex = 0, rightIndex = 0; // Pointers for the sliding window\n\n while (rightIndex < n) {\n currentSum += nums[rightIndex];\n rightIndex++;\n\n while (currentSum > target && leftIndex < n) {\n currentSum -= nums[leftIndex];\n leftIndex++;\n }\n\n if (currentSum == target)\n minOperations = min(minOperations, n - (rightIndex - leftIndex));\n }\n\n return (minOperations == INT_MAX) ? -1 : minOperations; // Return the minimum operations or -1 if not possible\n }\n};\n```\n```Java []\nclass Solution {\n public int minOperations(int[] nums, int targetSum) {\n int totalSum = Arrays.stream(nums).sum();\n int target = totalSum - targetSum; // Calculate the target sum difference\n\n if (target < 0)\n return -1; // Return -1 if target sum is not achievable\n\n if (target == 0)\n return nums.length; // Return the number of elements if target sum is 0\n\n int n = nums.length; // Number of elements in the array\n int minOperations = Integer.MAX_VALUE; // Minimum operations to achieve the target sum\n int currentSum = 0; // Current sum of elements\n int leftIndex = 0, rightIndex = 0; // Pointers for the sliding window\n\n while (rightIndex < n) {\n currentSum += nums[rightIndex];\n rightIndex++;\n\n while (currentSum > target && leftIndex < n) {\n currentSum -= nums[leftIndex];\n leftIndex++;\n }\n\n if (currentSum == target)\n minOperations = Math.min(minOperations, n - (rightIndex - leftIndex));\n }\n\n return (minOperations == Integer.MAX_VALUE) ? -1 : minOperations; // Return the minimum operations or -1 if not possible\n }\n}\n```\n```Python []\nclass Solution:\n def minOperations(self, nums, targetSum) -> int:\n totalSum = sum(nums)\n target = totalSum - targetSum # Calculate the target sum difference\n\n if target < 0:\n return -1 # Return -1 if target sum is not achievable\n\n if target == 0:\n return len(nums) # Return the number of elements if target sum is 0\n\n n = len(nums) # Number of elements in the list\n minOperations = float(\'inf\') # Minimum operations to achieve the target sum\n currentSum = 0 # Current sum of elements\n leftIndex = 0\n rightIndex = 0 # Pointers for the sliding window\n\n while rightIndex < n:\n currentSum += nums[rightIndex]\n rightIndex += 1\n\n while currentSum > target and leftIndex < n:\n currentSum -= nums[leftIndex]\n leftIndex += 1\n\n if currentSum == target:\n minOperations = min(minOperations, n - (rightIndex - leftIndex))\n\n return -1 if minOperations == float(\'inf\') else minOperations # Return the minimum operations or -1 if not possible\n```\n\n![leet_sol.jpg]()\n\n | 88,000 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 2,555 | 39 | Welcome to my article. Before starting the article, why do I have to get multiple downvotes for a miniute every day? That is obviously deliberate downvotes. I can tell who is doing it. Please show your respect to others! Thanks.\n\n# Intuition\nTry to find target number with sum(nums) - x which is `unnecessary numbers`\n\n---\n\n# Solution Video\n\nIn the video, the steps of approach below are visualized using diagrams and drawings. I\'m sure you understand the solution easily!\n\n\n\n\u25A0 Timeline of the video\n`0:00` Read the question of Minimum Operations to Reduce X to Zero \n`1:13` How we think about a solution\n`3:47` Explain how to solve Minimum Operations to Reduce X to Zero\n`13:00` Coding\n`15:26` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2,382\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\nWe have two choices to take numbers from left or right side. But problem is we don\'t know what numbers are coming next, next next or next next next...so it\'s tough to manage left and right numbers at the same time.\n\nThat\'s why I changed my idea to this. We have to subtract some numbers from `x`. In other words, If we can calculate numbers which don\'t need for `x` and subtract the `unnecessary numbers` from `total number` of input array, we can get `x`. That formula is\n\n```\ntotal numbers in array - unnecessary numbers = x\n```\n\nAnd an important point is that as I told you, we have two choices to take numbers from left side or right side. That\'s why `position of unnecessary numbers` is around middle of input array for the most cases and `it is consecutive places`.\n\nLet\'s see concrete expamle.\n```\nInput: nums = [3,2,20,1,1,3], x = 10\n```\n\ncalculation of `unnecessary numbers` is\n```\ntotal numbers in array - unnecessary numbers = x\n\u2193\ntotal numbers in array - x = unnecessary numbers\n\n30 - 10 = 20\n\n30: total number of input array\n10: x\n20: unnecessary numbers \n```\n\n\nAt first, we have to find `20` from `input array`. Let\'s break the numbers into small pieces.\n\n```\n[3,2] = 5\n[20] = 20\n[1,1,3] = 5\n\n[3,2] is an case where we take 3 and 2 from left side.\n[1,1,3] is an case where we take 3, 1 and 1 from right side.\nThe total of [3,2] and [1,1,3] is 10 (3+2+1+1+3) which is x.\n```\nIn this case, if we can find `[20]`, all we have to do is to calculate this.\n```\n6 - 1 = 5\n\n6: total length of input array\n1: length of [20]\n5: length of [3,2] + [1,1,3]\n```\n```\nOutput : 5 (minimum number of operations to make x zero)\n```\n\n`position of unnecessary numbers` is around middle of input array and it is `consective places`, so looks like we can use `sliding window` technique to find `length of array for unnecessary numbers`.\n\n\n### Overview Algorithm\n1. Calculate the target sum as the sum of `nums` minus `x`.\n2. Check if the target sum is negative, return -1 if it is.\n3. Initialize variables `left`, `cur_sum`, and `max_sub_length`.\n4. Iterate through the `nums` array using a sliding window approach to find the longest subarray with the sum equal to the target.\n\n### Detailed Explanation\n1. Calculate the target sum:\n - Calculate the `target` as the sum of `nums` minus `x`. This is the sum we want to achieve by finding a subarray in the given array.\n\n2. Check if the target sum is negative:\n - If `target` is less than 0, it means it\'s not possible to achieve the target sum by removing elements from the array. Return -1.\n\n3. Initialize variables:\n - `left`: Initialize a pointer to the left end of the window.\n - `cur_sum`: Initialize a variable to keep track of the current sum in the window.\n - `max_sub_length`: Initialize a variable to keep track of the maximum subarray length with the sum equal to the target.\n\n4. Iterate through the array using a sliding window:\n - Start a loop over the array using the right pointer.\n - Update the current sum by adding the current element at the right pointer.\n - Check if the current sum is greater than the target:\n - If the current sum exceeds the target, move the left pointer to the right until the current sum is less than or equal to the target.\n - Check if the current sum is equal to the target:\n - If the current sum equals the target, update the maximum subarray length if needed.\n - At each iteration, keep track of the maximum subarray length found so far.\n\n5. Return the result:\n - After the loop, return -1 if no valid subarray was found (max_sub_length remains as initialized), or return the difference between the total length of the array and the maximum subarray length.\n\nThis algorithm efficiently finds the longest subarray with a sum equal to the target sum using a sliding window approach.\n\n# How it works\nLet\'s think about this input.\n```\nInput: nums = [3,2,20,1,1,3], x = 10\n\ntarget(unnecessary numbers) = 20 (fixed)\ncur_sum = 0\nleft = 0\nright = 0\nmax_sub_length = 0\nn = 6 (fixed)\n```\niteration thorugh input array one by one\n```\nwhen right = 0, add 3 to cur_sum\n\ncur_sum = 3\nleft = 0\nmax_sub_length = 0\n```\n\n```\nwhen right = 1, add 2 to cur_sum\n\ncur_sum = 5\nleft = 0\nmax_sub_length = 0\n```\n\n```\nwhen right = 2, add 20 to cur_sum\n\ncur_sum = 25 \u2192 20(while loop, 25 - 3 - 2)\nleft = 0 \u2192 2 (while loop, 0 + 1 + 1)\nmax_sub_length = 1 (if statement, max(-inf, 2 - 2 + 1))\n```\n\n```\nwhen right = 3, add 1 to cur_sum\n\ncur_sum = 21 \u2192 1(while loop, 21 - 20)\nleft = 2 \u2192 3 (while loop, 2 + 1)\nmax_sub_length = 1\n```\n\n```\nwhen right = 4, add 1 to cur_sum\n\ncur_sum = 2\nleft = 3\nmax_sub_length = 1\n```\n\n```\nwhen right = 5, add 3 to cur_sum\n\ncur_sum = 5\nleft = 3\nmax_sub_length = 1\n```\n\n```\nreturn 6(n) - 1(max_sub_length)\n```\n\n```\nOutput: 5 (operations)\n```\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n`n` is the length of the input nums array. This is because there is a single loop that iterates through the elements of the array once.\n\n\n- Space complexity: O(1)\nbecause the code uses a constant amount of additional memory regardless of the size of the input nums array. The space used for variables like `target`, `left`, `cur_sum`, `max_sub_length`, and `n` does not depend on the size of the input array and remains constant.\n\n\n```python []\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n target = sum(nums) - x\n \n if target < 0:\n return -1\n \n left = 0\n cur_sum = 0\n max_sub_length = float(\'-inf\')\n n = len(nums)\n \n for right in range(n):\n cur_sum += nums[right]\n \n while cur_sum > target:\n cur_sum -= nums[left]\n left += 1\n \n if cur_sum == target:\n max_sub_length = max(max_sub_length, right - left + 1)\n \n return -1 if max_sub_length == float(\'-inf\') else n - max_sub_length\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} x\n * @return {number}\n */\nvar minOperations = function(nums, x) {\n const target = nums.reduce((acc, num) => acc + num, 0) - x;\n \n if (target < 0) {\n return -1;\n }\n \n let left = 0;\n let curSum = 0;\n let maxSubLength = Number.NEGATIVE_INFINITY;\n const n = nums.length;\n \n for (let right = 0; right < n; right++) {\n curSum += nums[right];\n \n while (curSum > target) {\n curSum -= nums[left];\n left++;\n }\n \n if (curSum === target) {\n maxSubLength = Math.max(maxSubLength, right - left + 1);\n }\n }\n \n return maxSubLength === Number.NEGATIVE_INFINITY ? -1 : n - maxSubLength; \n};\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums, int x) {\n int target = 0;\n for (int num : nums) {\n target += num;\n }\n target -= x;\n\n if (target < 0) {\n return -1;\n }\n\n int left = 0;\n int curSum = 0;\n int maxSubLength = Integer.MIN_VALUE;\n int n = nums.length;\n\n for (int right = 0; right < n; right++) {\n curSum += nums[right];\n\n while (curSum > target) {\n curSum -= nums[left];\n left++;\n }\n\n if (curSum == target) {\n maxSubLength = Math.max(maxSubLength, right - left + 1);\n }\n }\n\n return maxSubLength == Integer.MIN_VALUE ? -1 : n - maxSubLength; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums, int x) {\n int target = 0;\n for (int i : nums) {\n target += i;\n }\n target -= x;\n\n if (target < 0) {\n return -1;\n }\n\n int left = 0;\n int curSum = 0;\n int maxSubLength = INT_MIN;\n int n = nums.size();\n\n for (int right = 0; right < n; right++) {\n curSum += nums[right];\n\n while (curSum > target) {\n curSum -= nums[left];\n left++;\n }\n\n if (curSum == target) {\n maxSubLength = std::max(maxSubLength, right - left + 1);\n }\n }\n\n return maxSubLength == INT_MIN ? -1 : n - maxSubLength; \n }\n};\n```\n\n\n---\n\nThank you for reading such a long article. \n\n\u2B50\uFE0F Please upvote it if you understand how we think about a solution and don\'t forget to subscribe to my youtube channel!\n\n\nMy next post for daily coding challenge on Sep 21, 2023\n\n\nHave a nice day!\n\n\n | 88,025 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 1,029 | 12 | Read Whole article : \n\nExplanation of Problem with Example (HandWritten).\nTime Complexity:\n\n**Prefix Sum + Hashmap (Longest Subarry )Approach : O(N)**\n\nPython :\nJava:\nc++:\nJavaScript:\n\nRead Whole article :\n\n![image]()\n | 88,026 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 2,235 | 11 | # Problem\n\n### This problem involves finding the minimum number of operations to reduce the sum of elements in the array nums to exactly zero, given that you can perform operations to remove elements from either the left or right end of the array.\n---\n# Solution\n\n##### **1.** Calculate the total sum of all elements in the nums array and store it in the variable total.\n\n##### **2.** Calculate the target value that we want to reach, which is target = total - x. Essentially, we want to find a subarray whose sum is equal to target.\n\n##### **3.** Initialize two pointers, left and right, both starting at index 0, and a variable running_sum to keep track of the sum of elements within the sliding window.\n\n##### **4.** Initialize a variable max_length to -1. This variable will be used to keep track of the maximum length of a subarray with a sum equal to target.\n\n#### **5.** Iterate through the nums array using the right pointer. At each step, add the value at nums[right] to running_sum.\n\n#### **6.** Check if running_sum is greater than target. If it is, this means the current subarray sum is too large. In this case, we need to shrink the sliding window by incrementing the left pointer and subtracting the value at nums[left] from running_sum until running_sum is less than or equal to target.\n\n#### **7.** Once the sliding window is valid (i.e., running_sum is equal to target), calculate its length (right - left + 1) and update max_length if this length is greater than the current maximum length.\n\n#### **8.** Continue this process until you\'ve iterated through the entire nums array.\n\n#### **9.** After the loop, check if max_length has been updated. If it has, it means we found a subarray with the sum equal to target. The minimum number of operations required to reduce x to zero is equal to n - max_length, where n is the length of the original array nums. If max_length is still -1, return -1 to indicate that it\'s not possible to reduce x to zero.\n---\n# Summary\n\n#### In summary, the algorithm uses a sliding window approach to find the subarray with the sum equal to the target, and then calculates the minimum number of operations required based on the length of that subarray. If no such subarray exists, it returns -1.\n\n---\n# Code\n```Python3 []\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n total = sum(nums)\n target = total - x\n left = 0\n n = len(nums)\n max_length = -1\n running_sum = 0\n\n for right in range(n):\n running_sum += nums[right]\n\n #shrink sliding window to make sure running_sum is not greater than target\n while running_sum > target and left <= right:\n running_sum -= nums[left]\n left += 1\n\n #now we have a avalid sliding window\n if running_sum == target:\n max_length = max(max_length, right - left + 1)\n \n return n - max_length if max_length != -1 else -1\n```\n```python []\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n total = sum(nums)\n target = total - x\n left = 0\n n = len(nums)\n max_length = -1\n running_sum = 0\n\n for right in range(n):\n running_sum += nums[right]\n\n #shrink sliding window to make sure running_sum is not greater than target\n while running_sum > target and left <= right:\n running_sum -= nums[left]\n left += 1\n\n #now we have a avalid sliding window\n if running_sum == target:\n max_length = max(max_length, right - left + 1)\n \n return n - max_length if max_length != -1 else -1\n```\n```C# []\npublic class Solution {\n public int MinOperations(int[] nums, int x) {\n int total = nums.Sum();\n int target = total - x;\n int left = 0;\n int n = nums.Length;\n int maxLength = -1;\n int runningSum = 0;\n\n for (int right = 0; right < n; right++) {\n runningSum += nums[right];\n\n while (runningSum > target && left <= right) {\n runningSum -= nums[left];\n left++;\n }\n\n if (runningSum == target) {\n maxLength = Math.Max(maxLength, right - left + 1);\n }\n }\n\n return maxLength != -1 ? n - maxLength : -1;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(std::vector<int>& nums, int x) {\n int total = std::accumulate(nums.begin(), nums.end(), 0);\n int target = total - x;\n int left = 0;\n int n = nums.size();\n int maxLength = -1;\n int runningSum = 0;\n\n for (int right = 0; right < n; right++) {\n runningSum += nums[right];\n\n while (runningSum > target && left <= right) {\n runningSum -= nums[left];\n left++;\n }\n\n if (runningSum == target) {\n maxLength = std::max(maxLength, right - left + 1);\n }\n }\n\n return maxLength != -1 ? n - maxLength : -1;\n }\n};\n\n```\n```C []\nint minOperations(int* nums, int numsSize, int x) {\n int total = 0;\n for (int i = 0; i < numsSize; i++) {\n total += nums[i];\n }\n\n int target = total - x;\n int left = 0;\n int maxLength = -1;\n int runningSum = 0;\n\n for (int right = 0; right < numsSize; right++) {\n runningSum += nums[right];\n\n while (runningSum > target && left <= right) {\n runningSum -= nums[left];\n left++;\n }\n\n if (runningSum == target) {\n int currentLength = right - left + 1;\n maxLength = (maxLength == -1) ? currentLength : (currentLength > maxLength ? currentLength : maxLength);\n }\n }\n\n return (maxLength != -1) ? numsSize - maxLength : -1;\n}\n\n```\n```Java []\npublic class Solution {\n public int minOperations(int[] nums, int x) {\n int total = 0;\n for (int num : nums) {\n total += num;\n }\n\n int target = total - x;\n int left = 0;\n int n = nums.length;\n int maxLength = -1;\n int runningSum = 0;\n\n for (int right = 0; right < n; right++) {\n runningSum += nums[right];\n\n while (runningSum > target && left <= right) {\n runningSum -= nums[left];\n left++;\n }\n\n if (runningSum == target) {\n maxLength = Math.max(maxLength, right - left + 1);\n }\n }\n\n return maxLength != -1 ? n - maxLength : -1;\n }\n}\n\n```\n```Go []\nfunc minOperations(nums []int, x int) int {\n total := 0\n for _, num := range nums {\n total += num\n }\n\n target := total - x\n left := 0\n n := len(nums)\n maxLength := -1\n runningSum := 0\n\n for right := 0; right < n; right++ {\n runningSum += nums[right]\n\n for runningSum > target && left <= right {\n runningSum -= nums[left]\n left++\n }\n\n if runningSum == target {\n currentLength := right - left + 1\n if maxLength == -1 || currentLength > maxLength {\n maxLength = currentLength\n }\n }\n }\n\n if maxLength != -1 {\n return n - maxLength\n }\n\n return -1\n}\n\n```\n\n\n | 88,028 |
Minimum Operations to Reduce X to Zero | minimum-operations-to-reduce-x-to-zero | You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1. | Array,Hash Table,Binary Search,Sliding Window,Prefix Sum | Medium | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. | 14,287 | 203 | Sometimes, converting a problem into some other familiar one helps a lot. This question is one of them.\nLet me state a different problem, and your task is to relate how solving this problem will help in solving the actual one.\n> Given an array containing integers, your task is to find the length of the longest subarray with a given sum.\n\nIf you were able to relate, congratulations! \uD83C\uDF89\nAnd if not, don\'t worry; it happens with all of us (or maybe use hints \uD83D\uDE09).\nContinue reading below to find the solution.\n___\n___\n\u2705 **Solution I - Sliding Window [Accepted]**\n\nWe need to make `prefix_sum + suffix_sum = x`. But instead of this, finding a subarray whose sum is `sum(nums) - x` will do the job. Now we only need to maximize the length of this subarray to minimize the length of `prefix + suffix`, which can be done greedily. By doing this, we can get the minimum length, i.e., the minimum number of operations to reduce `x` to exactly `0` (if possible).\n\nIf you haven\'t heard the term "sliding window" before, visit [this link]().\n\n1. Let us take a sliding window whose ends are defined by `start_idx` and `end_idx`.\n2. If the sum of this sliding window (subarray) exceeds the target, keep reducing the window size (by increasing `start_idx`) until its sum becomes `<= target`.\n3. If the sum becomes equal to the target, compare the length, and store if it exceeds the previous length.\n4. Return `-1` if the sum of the sliding window never becomes equal to `target`.\n\n<iframe src="" frameBorder="0" width="1080" height="450"></iframe>\n\n- **Time Complexity:** `O(n)`\n- **Space Complexity:** `O(1)`\n\n___\n___\nIf you like the solution, please **upvote**! \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 88,031 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 1,320 | 7 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nString concatenation vs pointers\n# Approach\n<!-- Describe your approach to solving the problem. -->\nC code is also provided which is rare. No string copy is used for this solution.\n\nPython code is 1-line code.\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\n# Code\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {\n int n1=word1.size(), n2=word2.size();\n for(int i=1; i<n1; i++)\n word1[0]+=word1[i];\n for(int i=1; i<n2; i++)\n word2[0]+=word2[i];\n return word1[0]==word2[0]; \n }\n};\n```\n# C code\n```\n#pragma GCC optimize("O3", "unroll-loops")\n\nbool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Size) {\n int j1=strlen(word1[0]), j2=strlen(word2[0]);\n int len1= j1, len2=j2, count=0, k1=0, k2=0;\n \n for (register int i1=0, i2=0; i1<word1Size && i2<word2Size; count++) {\n if (word1[i1][k1]!=word2[i2][k2]) return 0;\n k1++, k2++;\n if (k1==j1){\n k1=0, i1++;\n j1=(i1<word1Size) ? strlen(word1[i1]) : 0;\n len1+=j1;\n }\n \n if( k2==j2){\n k2=0, i2++;\n j2=(i2<word2Size) ? strlen(word2[i2]) : 0;\n len2+=j2;\n }\n \n }\n// printf("count=%d len1=%d len2=%d \\n", count, len1, len2);\n return count == len1 && count == len2;\n}\n\n```\n#python 1 line\n```\nclass Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return "".join(word1)=="".join(word2)\n \n``` | 88,150 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 10,976 | 46 | ![Screenshot 2023-12-01 055053.png]()\n\n# YouTube Channel:\n\n[]()\n<!-- **If you want a video for this question please write in the comments** -->\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Current Subscribers: 515*\n*Subscribe Goal: 600 Subscribers*\n\n---\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo determine if two string arrays represent the same string, we need to concatenate the elements of each array and compare the resulting strings. The order of concatenation is crucial.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize two `StringBuilder` objects, `str1` and `str2`, to build the concatenated strings for `word1` and `word2` respectively.\n2. Iterate through each word in `word1`, appending it to `str1`.\n3. Iterate through each word in `word2`, appending it to `str2`.\n4. Convert both `StringBuilder` objects to strings, `s1` and `s2`.\n5. Compare `s1` and `s2`. If they are equal, return `true`; otherwise, return `false`.\n\n# Complexity\n- Let `m` be the total number of characters in `word1` and `n` be the total number of characters in `word2`.\n- Building `str1` and `str2` takes O(m + n) time.\n- Converting `str1` and `str2` to strings takes O(m + n) time.\n- The overall `time complexity` is `O(m + n)`.\n- The `space complexity` is `O(m + n)` due to the `StringBuilder` objects and the resulting strings.\n\n# Code\n```java []\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n StringBuilder str1 = new StringBuilder();\n StringBuilder str2 = new StringBuilder();\n\n for(String word : word1){\n str1.append(word);\n }\n for(String word : word2){\n str2.append(word);\n }\n String s1 = str1.toString();\n String s2 = str2.toString();\n\n if(s1.equals(s2)){\n return true;\n }\n else{\n return false;\n }\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {\n string s1 = "";\n string s2 = "";\n\n for(const string& s : word1)\n s1 += s;\n for(const string& s : word2)\n s2 += s;\n\n return s1==s2;\n }\n};\n```\n```Python []\nclass Solution(object):\n def arrayStringsAreEqual(self, word1, word2):\n str1 = \'\'.join(word1)\n str2 = \'\'.join(word2)\n return str1 == str2 \n```\n```JavaScript []\n/**\n * @param {string[]} word1\n * @param {string[]} word2\n * @return {boolean}\n */\nvar arrayStringsAreEqual = function(word1, word2) {\n const str1 = word1.join(\'\');\n const str2 = word2.join(\'\');\n return str1 === str2;\n};\n```\n![upvote.png]()\n | 88,153 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 1,691 | 35 | # Intuition\nUse two pointers for each input array\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:05` Simple way to solve this question\n`1:07` Demonstrate how it works\n`4:55` Coding\n`8:00` Time Complexity and Space Complexity\n`8:26` Step by step algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,273\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nSimply, we can solve this question like this.\n```\nclass Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return \'\'.join(word1) == \'\'.join(word2)\n```\nBut LeetCode is coding/algorithm platform, so I will take anoter away.\n\nLooking at the given examples, in the cases where the result is True, the order of characters from the first to the last is the same.\n\nThe difference lies in the positions of the word boundaries.\n\nSo my stragegy is\n\n---\n\n\u2B50\uFE0F Points\n\nUse two pointers for each input array. One is for index of words in the input array and the other is for characters of each word.\n\nIterate through from the beginning. Every time we check if we reach end of word. If so, update both indices for the next word.\n\n---\n\nLet\'s see one by one.\n\n```\nInput: word1 = ["ab", "c"], word2 = ["a", "bc"]\n```\n`pointer1` and `pointer2` are index for each word. `idx1` and `idx` are index of character of each word.\n```\npointer1: 0\nidx1: 0\npointer2: 0\nidx2: 0\n\narray1\n["ab", "c"]\n \u2191\n\narray2\n["a", "bc"]\n \u2191\n\n"a" == "a" \u2192 OK\n```\nThe first characters are the same. so update `idx1` and `idx2`.\n```\nidx1: 1\nidx2: 1\n```\nIn array2, we reach end of the word, so \n```\nupdate `pointer2` to `1`\nupdate `idx2` to `0`\n```\nSo now\n```\npointer1: 0\nidx1: 1\npointer2: 1\nidx2: 0\n\narray1\n["ab", "c"]\n \u2191\n\narray2\n["a", "bc"]\n \u2191\n\n"b" == "b" \u2192 OK\n```\nSo now we reach end of word in array1.\n```\npointer1: 1\nidx1: 0\npointer2: 1\nidx2: 1\n\narray1\n["ab", "c"]\n \u2191\n\narray2\n["a", "bc"]\n \u2191\n\n"c" == "c" \u2192 OK\n```\nNow we reach end of the word in both `array1` and `array2`. update indices.\n\n```\npointer1: 2\nidx1: 0\npointer2: 2\nidx2: 0\n```\nFinish iteration.\n\nAt last, if `pointer1` and `pointer2` are the same as length of input `array1` and `array2`, we should return `true`, if not, return `false`.\n\n```\nOutput: true\n```\n\n---\n\n\nAlgorithm Step by Step:\n\n1. **Initialization:** Initialize pointers and indices for both words (`pointer1`, `idx1`, `pointer2`, `idx2`) to 0.\n\n```\npointer1, idx1, pointer2, idx2 = 0, 0, 0, 0\n```\n\n2. **Iteration:** Use a while loop to iterate as long as both pointers are within the bounds of their respective word arrays (`word1` and `word2`).\n\n```\nwhile pointer1 < len(word1) and pointer2 < len(word2):\n```\n\n3. **Character Comparison:**\n - Retrieve the current characters (`char1` and `char2`) from the words using the pointers and indices.\n - Compare the characters. If they are not equal, return `False` as the words are not equivalent.\n\n```\nif char1 != char2:\n return False\n```\n\n4. **Move to Next Character:**\n - Move to the next character in the current word by incrementing `idx1` and `idx2`.\n\n```\nidx1 += 1\nidx2 += 1\n```\n\n5. **Move to Next Word:**\n - Check if the end of the current word is reached for either word.\n - If the end of `word1` is reached, reset `idx1` to 0 and increment `pointer1` to move to the next word in `word1`.\n - If the end of `word2` is reached, reset `idx2` to 0 and increment `pointer2` to move to the next word in `word2`.\n\n```\nif idx1 == len(word1[pointer1]):\n idx1, pointer1 = 0, pointer1 + 1\n\nif idx2 == len(word2[pointer2]):\n idx2, pointer2 = 0, pointer2 + 1\n```\n\n\n6. **Check End of Arrays:**\n - After the loop, check if both pointers have reached the end of their respective arrays (`len(word1)` and `len(word2)`).\n - If yes, return `True`; otherwise, return `False`.\n\n```\nreturn pointer1 == len(word1) and pointer2 == len(word2)\n```\n\n---\n\n\n# Complexity\n- Time complexity: $$O(N)$$\nN is the total number of characters across both words. This is because each character is visited exactly once during the while loop.\n\n- Space complexity: $$O(1)$$\n\n```python []\nclass Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n pointer1, idx1, pointer2, idx2 = 0, 0, 0, 0 # Pointers and indices for both words\n\n while pointer1 < len(word1) and pointer2 < len(word2):\n # Get the current characters from both words\n char1, char2 = word1[pointer1][idx1], word2[pointer2][idx2]\n\n # Compare characters\n if char1 != char2:\n return False\n\n # Move to the next character in the current word\n idx1 += 1\n idx2 += 1\n\n # Move to the next word if the end of the current word is reached\n if idx1 == len(word1[pointer1]):\n idx1, pointer1 = 0, pointer1 + 1 # Move to the next word in word1\n\n if idx2 == len(word2[pointer2]):\n idx2, pointer2 = 0, pointer2 + 1 # Move to the next word in word2\n\n # Check if both pointers have reached the end of their respective arrays\n return pointer1 == len(word1) and pointer2 == len(word2) \n```\n```javascript []\n/**\n * @param {string[]} word1\n * @param {string[]} word2\n * @return {boolean}\n */\nvar arrayStringsAreEqual = function(word1, word2) {\n let pointer1 = 0; // Pointer for word1\n let pointer2 = 0; // Pointer for word2 \n let idx1 = 0; // Index for the current word in word1\n let idx2 = 0; // Index for the current word in word2\n\n while (pointer1 < word1.length && pointer2 < word2.length) {\n // Get the current characters from both words\n const char1 = word1[pointer1][idx1];\n const char2 = word2[pointer2][idx2];\n\n // Compare characters\n if (char1 !== char2) {\n return false;\n }\n\n // Move to the next character in the current word\n idx1++;\n idx2++;\n\n // Move to the next word if the end of the current word is reached\n if (idx1 === word1[pointer1].length) {\n idx1 = 0; // Move to the next word in word1\n pointer1++;\n }\n\n if (idx2 === word2[pointer2].length) {\n idx2 = 0; // Move to the next word in word2\n pointer2++;\n }\n }\n\n // Check if both pointers have reached the end of their respective arrays\n return pointer1 === word1.length && pointer2 === word2.length; \n};\n```\n```java []\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n int pointer1 = 0; // Pointer for word1\n int pointer2 = 0; // Pointer for word2 \n int idx1 = 0; // Index for the current word in word1\n int idx2 = 0; // Index for the current word in word2\n\n while (pointer1 < word1.length && pointer2 < word2.length) {\n // Get the current characters from both words\n char char1 = word1[pointer1].charAt(idx1);\n char char2 = word2[pointer2].charAt(idx2);\n\n // Compare characters\n if (char1 != char2) {\n return false;\n }\n\n // Move to the next character in the current word\n idx1++;\n idx2++;\n\n // Move to the next word if the end of the current word is reached\n if (idx1 == word1[pointer1].length()) {\n idx1 = 0; // Move to the next word in word1\n pointer1++;\n }\n\n if (idx2 == word2[pointer2].length()) {\n idx2 = 0; // Move to the next word in word2\n pointer2++;\n }\n }\n\n // Check if both pointers have reached the end of their respective arrays\n return pointer1 == word1.length && pointer2 == word2.length; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {\n int pointer1 = 0; // Pointer for word1\n int pointer2 = 0; // Pointer for word2 \n int idx1 = 0; // Index for the current word in word1\n int idx2 = 0; // Index for the current word in word2\n\n while (pointer1 < word1.size() && pointer2 < word2.size()) {\n // Get the current characters from both words\n char char1 = word1[pointer1][idx1];\n char char2 = word2[pointer2][idx2];\n\n // Compare characters\n if (char1 != char2) {\n return false;\n }\n\n // Move to the next character in the current word\n idx1++;\n idx2++;\n\n // Move to the next word if the end of the current word is reached\n if (idx1 == word1[pointer1].size()) {\n idx1 = 0; // Move to the next word in word1\n pointer1++;\n }\n\n if (idx2 == word2[pointer2].size()) {\n idx2 = 0; // Move to the next word in word2\n pointer2++;\n }\n }\n\n // Check if both pointers have reached the end of their respective arrays\n return pointer1 == word1.size() && pointer2 == word2.size(); \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:05` How we can solve "Find Words That Can Be Formed by Characters"\n`3:48` What if we have extra character when specific character was already 0 in HashMap?\n`4:17` Coding\n`7:45` Time Complexity and Space Complexity\n`8:17` Step by step algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:03` Right shift\n`1:36` Bitwise AND\n`3:09` Demonstrate how it works\n`6:03` Coding\n`6:38` Time Complexity and Space Complexity | 88,154 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 2,307 | 15 | ## **Approach**\nAll three solutions share a common approach of concatenating strings and then checking for equality.\n# **CODE**\n\n### **C++**\n\u2705C++ solution with 4ms runtime\n\n```\n\nclass Solution {\npublic:\n bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {\n string a, b;\n \n // Reserve space to avoid frequent reallocations\n for(const auto& x : word1)\n a += x;\n a.reserve(a.size());\n \n for(const auto& x : word2)\n b += x;\n b.reserve(b.size());\n\n return a == b;\n }\n};\n```\n\n### Java\n\u2705JAVA || Single line Solution || 90% Faster Code || Easy Solution\n\n```\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n if(word1.length == 0 || word2.length == 0) return false;\n return String.join("", word1).equals(String.join("", word2));\n }\n}\n```\n\n### Python\n\u2705Python || Single line Solution \n\n```\ndef arrayStringsAreEqual(self, word1, word2):\t\n\treturn \'\'.join(word1) == \'\'.join(word2)\n```\n\n![image]()\n\n | 88,156 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 3,543 | 33 | # Description\n\n## Intuition\nThe problem seems to be about comparing two lists of strings and checking if the concatenation of strings in each list results in equal strings. The provided code uses the `join` method to concatenate the strings in both lists and then compares the resulting strings.\n\n## Approach\nThe approach taken in the code is straightforward. It joins the strings in both lists and checks if the resulting strings are equal. If they are equal, the function returns `True`; otherwise, it returns `False`.\n\n## Complexity\n- **Time complexity:** The time complexity is dominated by the `join` operation, which is linear in the total length of the strings in the input lists. Let\'s denote the total length of all strings in `word1` as \\(m\\) and in `word2` as \\(n\\). Therefore, the time complexity is \\(O(m + n)\\).\n- **Space complexity:** The space complexity is also \\(O(m + n)\\) as the `join` method creates new strings that are the concatenation of the input strings.\n\n## Performance\n| Language | Execution Time (ms) | Memory Usage (MB) |\n| :--- | :---:| :---: | \nJava | 1 | 40.6 |\nPython3 | 43 | 16.3 |\nC# | 87 | 40.9 |\nRust | 1 | 2.1 |\nRuby | 55 | 210.9 |\n\n## Code\n```python []\nclass Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return "".join(word1) == "".join(word2)\n```\n```Java []\nclass Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2) {\n return String.join("", word1).equals(String.join("", word2));\n }\n}\n```\n``` C# []\npublic class Solution {\n public bool ArrayStringsAreEqual(string[] word1, string[] word2) {\n return string.Concat(word1) == string.Concat(word2);\n }\n}\n```\n``` Ruby []\ndef array_strings_are_equal(word1, word2)\n word1.join == word2.join\nend\n```\n``` Rust []\nimpl Solution {\n pub fn array_strings_are_equal(word1: Vec<String>, word2: Vec<String>) -> bool {\n word1.concat() == word2.concat()\n }\n}\n```\n![image name]()\n\n- Please upvote me !!!\n | 88,165 |
Check If Two String Arrays are Equivalent | check-if-two-string-arrays-are-equivalent | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string. | Array,String | Easy | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. | 264 | 6 | # Intuition\n\nThe focus of this problem is on developing a solution with $$O(1)$$ space usage. In most languages, this requires maintaining pointers manually, but not in Python (#blessed). \n\n# Approach\n\nThe following solution is my favorite:\n```py\nclass Solution:\n def arrayStringsAreEqual(self, word1: list[str], word2: list[str]) -> bool:\n return all(starmap(eq, zip_longest(chain.from_iterable(word1), chain.from_iterable(word2))))\n```\n\nA couple of side notes:\n- `x == y for x, y in zip_longest(...)` also works and some may find it easier to read;\n- `zip` instead of `zip_longest` doesn\'t work if one wordlist is a (strict) prefix of another;\n- `zip(..., strict=True)` is a reasonable alternative that produces an exception instead of a sentinel value;\n- `chain(*words)` results in a correct answer but uses $$O(N)$$ space.\n\n# Complexity\n\nHere $$N$$ is the number of strings in the list and $$K$$ is the maximum length of a string in it.\n\n- Time complexity: $$O(N \\cdot K)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n\n```py\nclass Solution:\n def arrayStringsAreEqual(self, word1: list[str], word2: list[str]) -> bool:\n return all(starmap(eq, zip_longest(chain.from_iterable(word1), chain.from_iterable(word2))))\n``` | 88,171 |
Smallest String With A Given Numeric Value | smallest-string-with-a-given-numeric-value | The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. | String,Greedy | Medium | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. | 3,871 | 64 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nSince we are forming the lexicographically smallest string, we just simply fill our result with `a`s ( o\u02D8\u25E1\u02D8o). But hold on, that result will not necessarily have the required score c(\uFF9F.\uFF9F*) Ummm\u2026 Ok, then we can add some `z`s to the back of the result until the score reaches the required value, so be it (\uFFE2_\uFFE2;). Ofc if we are missing less than 26 to the required score, we add something that is less than `z`.\n\nTime: **O(n)** - iterations\nSpace: **O(n)** - for list of chars\n\nRuntime: 393 ms, faster than **73.27%** of Python3 online submissions for Smallest String With A Given Numeric Value.\nMemory Usage: 15.4 MB, less than **68.20%** of Python3 online submissions for Smallest String With A Given Numeric Value.\n\n```\nclass Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n res, k, i = [\'a\'] * n, k - n, n - 1\n while k:\n k += 1\n if k/26 >= 1:\n res[i], k, i = \'z\', k - 26, i - 1\n else:\n res[i], k = chr(k + 96), 0\n\n return \'\'.join(res)\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 88,202 |
Smallest String With A Given Numeric Value | smallest-string-with-a-given-numeric-value | The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. | String,Greedy | Medium | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. | 4,283 | 63 | **Mehtod 1: Greedily reversely place values**\n\n1. Make sure each value of the n characters is at least `1`: initialized all as `\'a\'`;\n2. Put as more value at the end of the String as possible.\n```java\n public String getSmallestString(int n, int k) {\n k -= n;\n char[] ans = new char[n];\n Arrays.fill(ans, \'a\');\n while (k > 0) {\n ans[--n] += Math.min(k, 25);\n k -= Math.min(k, 25);\n }\n return String.valueOf(ans);\n }\n```\n```python\n def getSmallestString(self, n: int, k: int) -> str:\n ans = [\'a\'] * n\n k -= n\n while k > 0:\n n -= 1 \n ans[n] = chr(ord(\'a\') + min(25, k))\n k -= min(25, k)\n return \'\'.join(ans)\n```\n\n**Analysis:**\nTime & space: O(n)\n\n----\n**Method 2: Math**\nCompute the total number of `z` at the end, and the number of not `a` characters right before those `z`: `r`; The remaining are `a`\'s .\n```java\n public String getSmallestString(int n, int k) {\n int z = (k - n) / 25, r = (k - n) % 25;\n return (z == n ? "" : "a".repeat(n - z - 1) + (char)(\'a\' + r)) + "z".repeat(z);\n }\n```\n```python\n def getSmallestString(self, n: int, k: int) -> str:\n z, r = divmod(k - n, 25)\n return (\'\' if z == n else \'a\' * (n - z - 1) + chr(ord(\'a\') + r)) + \'z\' * z\n```\nThe above codes can be further simplified as follows:\n\n```java\n public String getSmallestString(int n, int k) {\n int z = (k - n - 1) / 25, r = (k - n - 1) % 25;\n return "a".repeat(n - z - 1) + (char)(\'a\' + r + 1) + "z".repeat(z);\n }\n```\n```python\n def getSmallestString(self, n: int, k: int) -> str:\n z, r = divmod(k - n, 25)\n return \'a\' * (n - z - 1) + chr(ord(\'a\') + r) * (n > z) + \'z\' * z\n```\n**Analysis:**\nTime & space: O(n)\n | 88,212 |
Smallest String With A Given Numeric Value | smallest-string-with-a-given-numeric-value | The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. | String,Greedy | Medium | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. | 1,124 | 12 | ```\nclass Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n z, alp = divmod(k-n-1, 25)\n return (n-z-1)*\'a\'+chr(ord(\'a\')+alp+1)+z*\'z\'\n``` | 88,213 |
Smallest String With A Given Numeric Value | smallest-string-with-a-given-numeric-value | The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on. The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8. You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k. Note that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order. | String,Greedy | Medium | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. | 1,326 | 17 | The lexicographically smallest string of length n could be \'aaa\'.. of length n\nThe constraint is that the numeric value must be k.\nTo satisfy this constraint, we will greedily add either \'z\' or character form of (k - value) to the string.\n\nFor eg. \nn = 3, k = 32\nInitially, ans = \'aaa\', val = 3, i =2\nSince val!=k\nans = \'aaz\', val = 28, i = 1\nSince, val!=k\nk - val = 4\nans = \'adz\', val = 0 \nSince, val == k\nbreak\n\nFinal answer = \'adz\'\n\nRunning time: O(N)\nMemory: O(1)\n\n```\nclass Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n ans = [\'a\']*n # Initialize the answer to be \'aaa\'.. length n\n val = n #Value would be length as all are \'a\'\n \n for i in range(n-1, -1, -1): \n if val == k: # if value has reached k, we have created our lexicographically smallest string\n break\n val -= 1 # reduce value by one as we are removing \'a\' and replacing by a suitable character\n ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or \'z\'\n val += ord(ans[i]) - 96 # add the value of newly appended character to value\n \n return \'\'.join(ans) # return the ans string in the by concatenating the list\n``` | 88,219 |