question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-number-of-taps-to-open-to-water-a-garden | Just DP. Explained Line By Line. | just-dp-explained-line-by-line-by-tr1nit-0yfc | \n// TC: O(n * m) where \n// - n is given and \n// - m is ranges[i] for inner loop (<= 100)\n// SC: O(n)\nclass Solution {\npublic:\n int minTaps(int n, vect | __wkw__ | NORMAL | 2023-08-31T04:07:23.005987+00:00 | 2023-08-31T04:08:57.834736+00:00 | 984 | false | ```\n// TC: O(n * m) where \n// - n is given and \n// - m is ranges[i] for inner loop (<= 100)\n// SC: O(n)\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n // dp[i]: min number of taps that should be open to water garden [0 .. i]\n // init with some max values\n vector<int> dp(n + 1, n + 1);\n // no tap is needed to water no garden\n dp[0] = 0;\n for (int i = 0; i <= n; i++) {\n // we can water garden [i - ranges[i] .. i + ranges[i]] with tap i\n // rmb to handle the boundary ...\n int l = max(0, i - ranges[i]), r = min(i + ranges[i], n);\n for (int j = l; j <= r; j++) {\n // check we can use less number of taps from [l .. r]\n // i.e. can i water [0 .. j] just using dp[j] taps\n // or I need to water dp[0 .. l] `dp[l]` times \n // and use one more tap to water [l + 1 .. j]\n dp[j] = min(dp[j], dp[l] + 1);\n }\n }\n // if min number of taps not found, return -1, else return dp[n]\n return dp[n] == n + 1 ? -1 : dp[n];\n }\n};\n```\n\n**p.s. Join us on the LeetCode The Hard Way Discord Study Group for timely discussion! Link in bio.** | 13 | 0 | ['Dynamic Programming', 'C++'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Java 4ms | java-4ms-by-asif_hasnain-p0ev | \nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int count = 0;\n int lastTap = 0;\n int min = 0;\n int max = 0;\ | asif_hasnain | NORMAL | 2020-06-13T06:12:53.526639+00:00 | 2020-06-13T06:12:53.526687+00:00 | 387 | false | ```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int count = 0;\n int lastTap = 0;\n int min = 0;\n int max = 0;\n while(max<n){\n\t\t//Start checking from last open tap, look for the tap whose lowest range is less than or equal to \n\t\t//highest range of previous tap and select the one whose highest range is maximum.\n for(int i = lastTap ; i<=n ; i++){\n if(i - ranges[i]<=min && i + ranges[i]>max){\n lastTap = i;\n max = i + ranges[i];\n }\n }\n if(max==min) return -1;\n count++;\n min = max;\n }\n return count;\n }\n}\n``` | 13 | 0 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | Video Stitching | video-stitching-by-votrubac-8f1b | Reused the solution from 1024. Video Stitching.\nCPP\nint minTaps(int n, vector<int>& rs) {\n vector<vector<int>> clips;\n for (auto i = 0; i < rs.size(); ++i | votrubac | NORMAL | 2020-01-19T10:01:28.204633+00:00 | 2020-01-19T10:03:56.676444+00:00 | 1,316 | false | Reused the solution from [1024. Video Stitching](https://leetcode.com/problems/video-stitching/discuss/269988/C%2B%2BJava-6-lines-O(n-log-n)).\n```CPP\nint minTaps(int n, vector<int>& rs) {\n vector<vector<int>> clips;\n for (auto i = 0; i < rs.size(); ++i) {\n clips.push_back({i - rs[i], i + rs[i]});\n }\n return videoStitching(clips, n);\n}\nint videoStitching(vector<vector<int>>& clips, int T, int res = 0) {\n sort(begin(clips), end(clips));\n for (auto i = 0, st = 0, end = 0; st < T; st = end, ++res) {\n while (i < clips.size() && clips[i][0] <= st) \n end = max(end, clips[i++][1]);\n if (st == end) return -1;\n }\n return res;\n}\n```\n**Complexity Analysis**\n- Runtime: O(n log n); we sort all taps by the starting point, and then process each tab once.\n- Memory: O(n) to tranform taps into start/end points, O(1) for the algorithm itself. | 13 | 1 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Similar to Jump Game II | similar-to-jump-game-ii-by-xzj104-qdon | I feel like this is similar to the Jump Game category question with only one change.\n\nWe first need to generate the jump gamp array. To do this, for each tap | xzj104 | NORMAL | 2020-01-19T04:01:20.827019+00:00 | 2020-01-19T04:01:51.128254+00:00 | 1,022 | false | I feel like this is similar to the Jump Game category question with only one change.\n\nWe first need to generate the jump gamp array. To do this, for each tap pos, we get the interval it can cover, and mark the left as start and the right and end. \n\nWhen checking how far one start could go, we should not stop at the furthest point, we should include next point too. \nfor example:\n[0,2][3,6][7,7]\nin Jump Game we just stop at [0,2] because it can only reach 2. but in this question, we should also include 3. \n\nclass Solution {\n\npublic:\n\n int minTaps(int n, vector<int>& ranges) {\n //generate the array like the jump game\n //value arr[i] means how far from this position we can jump to\n vector<int> arr(n+1);\n \n for(int i = 0; i <= n; ++i) {\n int start = max(0, i - ranges[i]);\n int end = i + ranges[i];\n if(end > arr[start])\n arr[start] = end;\n }\n \n //first time always starts from pos 0\n //pre, cur, is the scope we want to check\n int pre = 0, cur = arr[0];\n int step =1;\n while(cur < n) {\n int next = -1;\n for(int i = pre + 1; i <= cur; ++i) {\n next = max(next, arr[i]);\n }\n \n //if we can\'t get any further, we are stuck...\n if(next <= cur) return -1;\n pre = cur;\n cur = next;\n ++step;\n }\n return step;\n }\n \n\n}; | 12 | 1 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Not understanding the problem | not-understanding-the-problem-by-fultonm-nvah | Input: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n\nIt seems that there is a | fultonm | NORMAL | 2021-12-15T20:30:12.900478+00:00 | 2021-12-15T20:33:44.642368+00:00 | 270 | false | Input: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n\nIt seems that there is a tap for each space in the garden. Why can\'t it be watered?\n```\n[0, 1, 2, 3]\n x x x x\n```\n\n\n 1 <= n <= 104\n ranges.length == n + 1\n 0 <= ranges[i] <= 100\nGiven these constraints (there will always be a tap with range at least 0 for each space in the garden.) So the garden will always be watered.\n\nWhat am I missing?\n | 11 | 0 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | Logic Explanation, 100% Efficient | logic-explanation-100-efficient-by-salon-74mq | So, the question is basically asking for the minimum taps, that can cover the whole garden.\nAlgorithm: \n1. Update ranges[i] to maxReach of the respective tap. | salonix__ | NORMAL | 2021-07-10T03:31:24.551491+00:00 | 2021-07-10T03:32:15.507115+00:00 | 877 | false | So, the question is basically asking for the minimum taps, that can cover the whole garden.\nAlgorithm: \n1. Update ranges[i] to maxReach of the respective tap.\n2. Now, iterate through it in O(n)\n3. Take positon variable, update it, when the iterator becomes equal to position, also, increase your jump, i.e., number of tap here.\n\n```\n class Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n for(int i=1; i<ranges.size(); i++){\n if(ranges[i]==0){\n ranges[i] = i;\n } else {\n int range = max(0, i-ranges[i]);\n ranges[range] = max(i+ranges[i], ranges[range]);\n }\n }\n \n int maxIndex = 0;\n int jump = 0;\n int pos = 0;\n for(int i=0; i<n; i++){\n if(maxIndex<i){\n return -1;\n }\n \n maxIndex = max(maxIndex, ranges[i]);\n \n if(i==pos){\n jump++;\n pos = maxIndex;\n }\n }\n \n return maxIndex>=n? jump: -1;\n }\n};\n```\n | 11 | 0 | ['C'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ sort & Greedy vs Dijkstra's algorithm | c-sort-greedy-vs-dijkstras-algorithm-by-fm00s | Intuition\n Describe your first thoughts on how to solve this problem. \nConstruct the intervals, denoted by pair (a,b), to form an array, say I. And sort I w.r | anwendeng | NORMAL | 2023-08-31T02:48:01.760148+00:00 | 2023-08-31T15:17:48.034799+00:00 | 1,620 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConstruct the intervals, denoted by pair (a,b), to form an array, say I. And sort I w.r.t. a.\nThen find the initial interval that covers 0 the most.\nOpen the tap with the right most range whose range has intersection with the ones already opened; if there is no such tap which means there is a gap and return -1;\n# Approach\n<!-- Describe your approach to solving the problem. -->\n2nd approach uses Dijkstra\'s algorithm in Graph Theory, slow but accepted and revisited by constucting the path with distance info instead of adjacent lists to reduce the time complexity. \n\nThe easiest way to solve this problem is to convert this problem into the pattern in [Leetcode 45. Jump Game II](https://leetcode.com/problems/jump-game-ii/). \n\nSome testcases\n```\n35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]\n11\n[2,1,2,1,2,4,3,0,1,0,5,2]\n6\n[1,1,0,1,0,0,1]\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n \\log n)$ vs $O(n+n\\log n)=O(n \\log n)$ \n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code runtime 11ms Beats 90.50%\n```\nclass Solution {\npublic:\n using int2 = pair<int, int>;\n\n int minTaps(int n, vector<int>& ranges) {\n vector<int2> I(n+1);\n for (int i=0; i<=n; i++) {\n int d = ranges[i];\n I[i] = {i-d, i+d};\n }\n sort(I.begin(), I.end());//Sort with left end\n\n int taps=1;\n int i0=0, a =INT_MIN, b= 0;\n \n // Find the initial interval that covers 0 the most\n while (a <= 0 && i0 <= n) {\n a = I[i0].first;\n if (a <= 0) b = max(b, I[i0].second);\n i0++;\n }\n\n if (b >= n) return taps; // Garden is already covered\n \n for (int i=i0; b<n; ) {\n int bMax = b;\n while (i <= n && I[i].first <= b) {\n bMax = max(bMax, I[i].second);\n i++;\n }\n \n if (bMax==b) \n return -1; // A gap\n \n b = bMax; // Update b\n taps++; // open a tap\n }\n\n return taps;\n }\n};\n\n\n```\n[https://youtu.be/ZpOJIlD4qU0](https://youtu.be/ZpOJIlD4qU0)\n# Code using Dijkstra\'s algorithm by a priority queue wrt custom order\n```\nclass Solution {\npublic:\n using int2 = pair<int, int>;\n\n struct cmp {\n bool operator()(int2& x, int2& y) {\n if (x.first != y.first) return x.first > y.first;\n return x.second < y.second;\n }\n };\n\n int minTaps(int n, vector<int>& ranges) {\n // Build the path with distance\n vector<vector<int2>> path(n + 1, vector<int2>());\n for (int i = 0; i <= n; i++) {\n int d=ranges[i];\n int l=max(0, i - d);\n int r=min(n, i + d);\n if (r != l) {\n path[l].push_back({1, r}); // (distance, endpoint)\n }\n }\n\n //Adding path with distance 0 makes l reaching all i with i<=r\n for (int i = 1; i <= n; i++) {\n path[i].push_back({0, i-1}); // (distance, endpoint)\n }\n\n // Dijkstra\'s algorithm\n vector<int> dist(n+1, INT_MAX);\n dist[0] = 0;\n priority_queue<int2, vector<int2>, cmp> pq;\n pq.push({0, 0});\n\n while (!pq.empty()) {\n auto [d, i] = pq.top();\n pq.pop();\n\n if (d>dist[i]) continue;\n\n for (auto [w, j] : path[i]) {\n if (dist[i]+w < dist[j]) {\n dist[j] = dist[i] + w;\n pq.push({dist[j], j});\n }\n }\n }\n\n return (dist[n] == INT_MAX) ? -1 : dist[n];\n }\n};\n\n\n``` | 10 | 0 | ['Greedy', 'Breadth-First Search', 'Graph', 'Sorting', 'Heap (Priority Queue)', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | O(1) Space, O(n) | o1-space-on-by-bhavesh17-lcab | Same problem as Jump II.\nWe will update i-ranges[i] index to max( i +ranges[i], ranges[i-ranges[i]] ) , so as we traverse from left to right , we have max rea | bhavesh17 | NORMAL | 2020-11-07T17:27:37.919737+00:00 | 2020-11-07T17:27:37.919785+00:00 | 1,211 | false | Same problem as Jump II.\nWe will update i-ranges[i] index to max( i +ranges[i], ranges[i-ranges[i]] ) , so as we traverse from left to right , we have max reachable index.\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n \n for(int i=1;i<ranges.size();i++){\n if(ranges[i] == 0) ranges[i]=i;\n else{\n int range = max(0, i-ranges[i]);\n ranges[range] = max(i+ranges[i],ranges[range]);\n }\n }\n \n int maxIdx = 0;\n int pos = 0;\n int jump = 0;\n \n for(int i=0;i<n;i++){\n if(maxIdx<i) return -1;\n \n maxIdx = max(maxIdx, ranges[i]);\n \n if(i==pos){\n jump++;\n pos = maxIdx;\n }\n }\n \n return maxIdx>=n ? jump : -1;\n \n }\n};\n``` | 10 | 0 | ['Greedy', 'C'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Greedy O(n) solution, python | greedy-on-solution-python-by-liketheflow-se8p | This problem is an almost identical problem of an OA interview problem. See reference 1\nFor each tap, record the maximum left reach point and maximum right rea | liketheflower | NORMAL | 2020-01-21T14:52:52.521355+00:00 | 2020-01-21T15:47:34.327304+00:00 | 1,579 | false | This problem is an almost identical problem of an OA interview problem. See reference 1\nFor each tap, record the maximum left reach point and maximum right reach point.\nBased on this, we can get a list contains for each left point, what is the maximum right reaching point.\nThen using a greedy algorithm to solve this problem.\nCode is here with comments.\n```python\nclass Solution:\n def minTaps(self, n: int, A: List[int]) -> int:\n # For all location of taps, store the largest right reach point\n max_right_end = list(range(n+1))\n for i, a in enumerate(A):\n left, right = max(i - a, 0), min(i + a, n)\n max_right_end[left] = max(max_right_end[left], right)\n\n res, l, r = 0, 0, max_right_end[0]\n while True:\n res += 1\n # if r can reach to the end of the whole garden, return res\n if r>=n:return res\n new_r = max(max_right_end[l:r+1])\n # if next r is same as current r, it means we can not move forward, return -1\n if new_r == r:return -1\n l, r = r, new_r\n```\n\nRuntime of above code\n```\nRuntime: 140 ms, faster than 89.58% of Python3 online submissions for Minimum Number of Taps to Open to Water a Garden.\nMemory Usage: 13 MB, less than 100.00% of Python3 online submissions for Minimum Number of Taps to Open to Water a Garden.\n```\nActually, for max_right_end, we can update it directly without compare with the old value, as we are looking from left to right, the second time that we reach a same left position will always have a wider coverage than the first one. So the code of this part can be writen more concisely.\n\n```python\nclass Solution:\n def minTaps(self, n: int, A: List[int]) -> int:\n if not A: return 0\n N = len(A)\n # For all location of taps, store the largest right reach point\n max_right_end = list(range(N))\n for i, a in enumerate(A):\n max_right_end[max(i - a, 0)] = min(i + a, N-1)\n\n res, l, r = 0, 0, max_right_end[0]\n while True:\n res += 1\n # if r can reach to the end of the whole garden, return res\n if r>=N-1:return res\n new_r = max(max_right_end[l:r+1])\n # if next r is same as current r, it means we can not move forward, return -1\n if new_r == r:return -1\n l, r = r, new_r\n```\nrun time of this updated version\n```\nRuntime: 136 ms, faster than 93.01% of Python3 online submissions for Minimum Number of Taps to Open to Water a Garden.\nMemory Usage: 13.2 MB, less than 100.00% of Python3 online submissions for Minimum Number of Taps to Open to Water a Garden.\n```\nReference \nhttps://leetcode.com/discuss/interview-question/363036/walmart-oa-2019-activate-fountains\nhttps://medium.com/@jim.morris.shen/two-points-fcb8ef6861e4?source=friends_link&sk=353cf1fa8b35aef6edba803aecdc38a2 | 10 | 0 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | JAVA, O(n), use bucket sort, 2ms, well commented | java-on-use-bucket-sort-2ms-well-comment-3csb | In this given problem we need to sort all the ranges that the taps provide by their start and end. Given how the problem is nicely bounded, we can use a bucket | devincisimpson | NORMAL | 2021-08-14T19:16:02.894678+00:00 | 2021-08-14T19:16:02.894705+00:00 | 864 | false | In this given problem we need to sort all the ranges that the taps provide by their start and end. Given how the problem is nicely bounded, we can use a bucket sort to achieve an O(n) runtime and a fairly small amount of code to solve this problem. \n\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n \n // create an array where startToEnd[i] points to the max\n // possible range of a tap starting at position i.\n int[] startToEnd = new int[n + 1];\n \n // in the first loop, set the start and end ranges \n // within the startToEnd array, we can exit early here\n // if we come across a range that covers all the way \n // from 0 to n (there is only 1 tap needed in this case).\n for(int i = 0; i <= n; i++){\n \n int start = Math.max(0, i - ranges[i]);\n int end = Math.min(n, i + ranges[i]);\n \n if(start == 0 && end == n)\n return 1;\n \n startToEnd[start] = Math.max(startToEnd[start], end); \n }\n \n // Now the general case of this problem is to do 2 things:\n //\n // 1) validate that we can cover the entire garden with taps.\n // 2) provide the minimum number of taps to provide full coverage.\n //\n // both of these cases can be achieved by starting at position 0\n // in the garden, and moving forward till the end of the max position\n // at the start, all the while gathering a potential next endpoint\n // (the largest in the current range we are iterating through)\n // We will do this until there are no more next endpoints to reach\n // if the final endpoint we reach is n, return the total number \n // of times we have changed endpoints (this is garunteed to be the \n // minimum number of taps to fill the garden). If the final endpoint \n // we reached was not n, then return -1 as we have proven that it is \n // impossible to cover the entire garden with the given taps.\n int currentEnd = startToEnd[0];\n int count = 0;\n int nextEnd = currentEnd;\n int index = 0;\n \n while(index <= currentEnd){\n \n nextEnd = Math.max(nextEnd, startToEnd[index]);\n \n if(index == currentEnd){\n currentEnd = nextEnd;\n count++;\n }\n index++;\n }\n \n return currentEnd == n ? count : -1;\n }\n}\n```\n\nRuntime Complexity: O(n)\nSpace Complexity: O(n) | 9 | 0 | ['Greedy', 'Bucket Sort', 'Java'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Java DP Greedy | java-dp-greedy-by-hobiter-2hta | dp is simple:\n1, for each position, find the most right pos that can be coverred with the same tap.\n2, from pos 0, find a route to end. if not possible, retur | hobiter | NORMAL | 2020-01-19T04:07:18.918272+00:00 | 2020-03-28T05:21:20.673831+00:00 | 4,633 | false | dp is simple:\n1, for each position, find the most right pos that can be coverred with the same tap.\n2, from pos 0, find a route to end. if not possible, return -1;\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n Map<Integer, Set<Integer>> m = new HashMap<>();\n int[] dp = new int[n+2];\n for (int i = 0; i < ranges.length; i++){\n if (ranges[i] == 0) continue;\n int mn = i - ranges[i];\n int mx = i + ranges[i];\n for (int j = Math.max(mn, 0); j < Math.min(ranges.length, mx); j++){\n dp[j] = Math.max(dp[j], mx);\n }\n }\n int curr = 0;\n int res = 0;\n while (curr < ranges.length){\n if (curr == ranges.length - 1) return res;\n if (dp[curr] == 0) return -1;\n curr = dp[curr];\n res++;\n }\n if (curr < ranges.length) return -1;\n return res;\n }\n}\n```\n\nAnother version:\n```\n public int minTaps(int n, int[] ranges) {\n int[] dp = new int[n + 1];\n Arrays.fill(dp, n + 2);\n dp[0] = 0;\n for (int i = 0; i <= n; i++) {\n int fr = Math.max(i - ranges[i], 0), to = Math.min(i + ranges[i], n);\n for (int j = fr; j <= to; j++) {\n dp[j] = Math.min(dp[j], dp[fr] + 1);\n }\n }\n return dp[n] < n + 2 ? dp[n] : -1;\n }\n``` | 9 | 0 | [] | 4 |
minimum-number-of-taps-to-open-to-water-a-garden | Python 3 || 11 lines, heap || T/S: 73% / 32% | python-3-11-lines-heap-ts-73-32-by-spaul-gitr | \nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n\n pos, ans = 0, 0\n heap = [(i-r,i+r) for i, r in enumerate(ranges)] | Spaulding_ | NORMAL | 2023-08-31T16:55:59.372097+00:00 | 2024-06-04T15:49:07.666635+00:00 | 108 | false | ```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n\n pos, ans = 0, 0\n heap = [(i-r,i+r) for i, r in enumerate(ranges)]\n heapify(heap)\n \n while pos < n:\n mx = 0\n while heap and heap[0][0] <= pos:\n mx = max(mx,heappop(heap)[1])\n \n if mx == 0: return -1\n pos = mx\n ans+= 1\n \n return ans\n```\n[https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/submissions/1036967454/](https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/submissions/1036967454/)\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*), in which *N* ~ `len(nums)`. | 8 | 0 | ['Python3'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Simple and easy to understand. | simple-and-easy-to-understand-by-avanish-w9cu | \nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n start, end = 0, 0\n taps = 0\n \n while end< n:\n | avanishtiwari | NORMAL | 2021-03-15T10:01:24.352277+00:00 | 2021-03-15T10:01:58.314507+00:00 | 1,429 | false | ```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n start, end = 0, 0\n taps = 0\n \n while end< n:\n for i in range(len(ranges)):\n if i-ranges[i] <= start and i+ ranges[i]>end:\n end = i + ranges[i]\n if start == end:\n return -1\n taps +=1\n start = end\n return taps\n \n``` | 8 | 0 | ['Dynamic Programming', 'Python', 'Python3'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | [Java] BAD DESCRIPTION Recursion + Memoization fails on some test cases which seem wrong | java-bad-description-recursion-memoizati-gcya | 35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]\nExpected: 6\nMy Answer: 5\n```\nclass Solution {\n public static int func(int[ | manrajsingh007 | NORMAL | 2020-01-19T04:13:05.395614+00:00 | 2020-01-19T04:17:16.309072+00:00 | 905 | false | 35\n[1,0,4,0,**4**,1,4,3,1,1,1,2,1,**4**,0,3,0,3,0,3,0,**5**,3,0,0,1,2,1,2,**4**,3,0,1,0,**5**,2]\nExpected: 6\nMy Answer: 5\n```\nclass Solution {\n public static int func(int[] ranges, int n, int i, int prev, int[][] dp) {\n if(prev >= n) return 0;\n if(i == n) return n + 1;\n if(dp[i][prev] != -1) return dp[i][prev];\n int next = prev;\n if(ranges[i] != 0) {\n if(i - ranges[i] <= prev) next = Math.max(next, i + ranges[i] + 1);\n }\n int m1 = func(ranges, n, i + 1, prev, dp);\n int m2 = func(ranges, n, i + 1, next, dp);\n if(m2 != n + 1) m2++;\n return dp[i][prev] = Math.min(m1, m2);\n }\n public int minTaps(int n, int[] ranges) {\n n++;\n int[][] dp = new int[n][n];\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < n; j++) dp[i][j] = - 1;\n }\n int ans = func(ranges, n, 0, 0, dp);\n return ans == n + 1 ? -1 : ans;\n }\n} | 8 | 0 | [] | 3 |
minimum-number-of-taps-to-open-to-water-a-garden | Beats 98% | With Similar Problems 🏆 | beats-98-with-similar-problems-by-hridoy-6at6 | This problem is a variation of the 1024. Video Stitching and the 45. Jump Game II\n problem.\n\nThis problem was asked Big Tech companies like Amazon, Twitter, | hridoy100 | NORMAL | 2023-08-31T09:23:22.314488+00:00 | 2023-08-31T09:28:56.320624+00:00 | 549 | false | This problem is a variation of the [1024. Video Stitching](https://leetcode.com/problems/video-stitching/) and the [45. Jump Game II\n](https://leetcode.com/problems/jump-game-ii/) problem.\n\nThis problem was asked Big Tech companies like Amazon, Twitter, Salesforce etc.\n\nBefore we dive in to the actual solution let\'s first see the solution of Jump Game II and try if you can come out with a solution.\n\n### 45. Jump Game II Solution:\n``` java []\nclass Solution {\n public int jump(int[] nums) {\n int l, r, res;\n l = r = res = 0;\n while(r < nums.length-1){\n int farthest = 0;\n for(int i=l; i<=r; i++){\n farthest = Math.max(farthest, i+nums[i]);\n }\n l = r+1;\n r = farthest;\n res++;\n }\n return res;\n }\n}\n```\n\n### 1024. Video Stitching Solution:\n``` java []\nclass Solution {\n public int videoStitching(int[][] clips, int time) {\n Arrays.sort(clips, (a,b)->a[0]-b[0]);\n int n = clips.length;\n int curEnd = 0, farthest = 0, total = 0;\n int i=0;\n while(curEnd < time) {\n total++;\n while(i<n && curEnd >= clips[i][0]) {\n farthest = Math.max(farthest, clips[i++][1]);\n }\n if(farthest == curEnd) {\n return -1;\n }\n curEnd = farthest;\n }\n return total;\n }\n}\n```\n\n# Code:\n\nIn the above problems you were given how far you can go. But in this problem, you have to calculate it from the ranges.\n\n``` java []\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] tap = new int[n+1];\n for(int i=0; i<=n; i++) {\n if(ranges[i] == 0) {\n continue;\n }\n int left = Math.max(0, i-ranges[i]);\n tap[left] = Math.max(tap[left], i+ranges[i]);\n }\n\n int curEnd=0, farthest=0, total=0;\n for(int i=0; i<n+1 && curEnd<n; curEnd=farthest) {\n total++;\n while(i<n+1 && i<=curEnd) {\n farthest = Math.max(farthest, tap[i++]);\n }\n if(curEnd == farthest) {\n return -1;\n }\n }\n return total;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> tap(n + 1);\n for (int i = 0; i <= n; i++) {\n if (ranges[i] == 0) {\n continue;\n }\n int left = max(0, i - ranges[i]);\n tap[left] = max(tap[left], i + ranges[i]);\n }\n\n int curEnd = 0, farthest = 0, total = 0;\n for (int i = 0; i < n + 1 && curEnd < n; curEnd = farthest) {\n total++;\n while (i < n + 1 && i <= curEnd) {\n farthest = max(farthest, tap[i++]);\n }\n if (curEnd == farthest) {\n return -1;\n }\n }\n return total;\n }\n};\n```\n\n\n | 7 | 0 | ['Array', 'Greedy', 'Sorting', 'C++', 'Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | ✅ C++ | Recursive 🚀🚀 DP🔥 Solution | Memoization | c-recursive-dp-solution-memoization-by-p-28k6 | Code\n\nclass Solution {\npublic:\n int n, dp[10005];\n int solve(int i, vector<pair<int, int>> &v)\n {\n if(i != -1 && v[i].second >= n)\n | pkacb | NORMAL | 2023-08-31T07:52:29.295793+00:00 | 2023-08-31T07:52:29.295843+00:00 | 1,163 | false | # Code\n```\nclass Solution {\npublic:\n int n, dp[10005];\n int solve(int i, vector<pair<int, int>> &v)\n {\n if(i != -1 && v[i].second >= n)\n return 0;\n\n if(dp[i + 1] != -1)\n return dp[i + 1];\n\n int ans = 1e9;\n for(int j = i + 1; j < v.size(); j++)\n {\n if((i == -1 && v[j].first <= 0) || (i != -1 && v[j].first <= v[i].second))\n ans = min(ans, 1 + solve(j, v));\n else \n break;\n }\n\n return dp[i + 1] = ans;\n }\n\n int minTaps(int n, vector<int>& ranges) {\n this -> n = n;\n vector<pair<int, int>> v;\n for(int i = 0; i < n + 1; i++)\n v.push_back({i - ranges[i], i + ranges[i]});\n \n sort(v.begin(), v.end());\n memset(dp, -1, sizeof(dp));\n return solve(-1, v) == 1e9 ? -1 : solve(-1, v);\n }\n};\n``` | 7 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C++'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Beats 100%! With proper explanation ! Greedy || DP | beats-100-with-proper-explanation-greedy-rhg5 | \n# Approach\nThe approach we follow over here is, for every tap we find the maximum range it can go. To store this range we create an array dp to store immedia | parthdharmale008 | NORMAL | 2023-08-31T05:50:03.963164+00:00 | 2023-08-31T06:08:25.175000+00:00 | 1,235 | false | \n# Approach\nThe approach we follow over here is, for every tap we find the maximum range it can go. To store this range we create an array ```dp``` to store immediate results.\n\nNow, iterate over ```ranges``` from ```0 to n```, if we encounter 0 then continue, i.e we don\'t need to update range for this index, if its not 0, then we store the left most range possible in ```left```, we use the max function to make sure our left is atleast 0 as our array starts from 0th index. ```dp[left]``` gives us the maximum range to right that a tap can cover from index left.\n\nInitialise three variables ```last```, ```maxDistance``` and ```taps``` to store the last index reachable, the maximum range current index can travel and number of taps opened respectively.\n\nWhat we\'ll be doing below is, we will check if we can reach the end of the garden, if we can\'t we\'ll take help of another tap and increase the number of ```taps```.\n\nIterate over the ```dp``` vector, and check if the current index > last, if it is check if ```maxDistance <= last```, if it is so return -1, this means that we can\'t cover the whole garden since our maxDistance should be more than our last.\nElse make our last equal to maxDistance and increase the number of ```taps``` by 1.\nUpdate the maxDistance.\n\nAt last if our ```last < n``` return taps+1 else return ```taps```.\n\nI\'ve solved the first test case below.\n\n\n\n\n# Upvote if you liked even a bit!\n\n# Code\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> dp(n + 1, 0);\n\n for(int i = 0; i <= n ; i++){\n if(ranges[i]== 0) continue;\n int left = max(0 , i - ranges[i]);\n dp[left] = max(dp[left], i + ranges[i]);\n }\n\n int last = 0;\n int maxDistance = 0;\n int taps = 0;\n\n for(int j = 0; j <= n; ++j){\n if(j > last){\n if(maxDistance <= last) return -1;\n\n last = maxDistance;\n ++taps;\n }\n maxDistance = max(maxDistance, dp[j]);\n }\n\n if(last < n){\n return taps + 1;\n }\n return taps;\n }\n};\n``` | 7 | 1 | ['Dynamic Programming', 'Greedy', 'C++'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Simple DP Approach 🔥 | C++ (Sorting + DP) | (Recursion+Memoization) | simple-dp-approach-c-sorting-dp-recursio-bpyg | \nclass Solution {\npublic:\n map<int,map<int,int>> dp;\n int helper(int idx,int prev,vector<vector<int>> &intervals){\n if(prev>=intervals.size()- | _maityamit | NORMAL | 2023-08-31T03:03:36.122459+00:00 | 2023-08-31T03:04:50.084682+00:00 | 746 | false | ```\nclass Solution {\npublic:\n map<int,map<int,int>> dp;\n int helper(int idx,int prev,vector<vector<int>> &intervals){\n if(prev>=intervals.size()-1) return 0;\n if(idx==intervals.size()) return 1e9;\n if(dp.count(idx) && dp[idx].count(prev)) return dp[idx][prev];\n if(intervals[idx][0]<=prev){\n int pick = 1+helper(idx+1,intervals[idx][1],intervals);\n int npic = helper(idx+1,prev,intervals);\n return dp[idx][prev]=min(pick,npic);\n }else{\n return dp[idx][prev]=1e9;\n }\n }\n int minTaps(int n, vector<int>& ranges) {\n vector<vector<int>> intervals;\n for(int i=0;i<ranges.size();i++) intervals.push_back({(i-ranges[i]),(i+ranges[i])});\n sort(intervals.begin(),intervals.end());\n int val = helper(0,0,intervals);\n if(val==1e9) return -1;\n else return val;\n }\n};\n``` | 7 | 0 | ['Dynamic Programming', 'C'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ | GREEDY | WITH EXPLANATION | c-greedy-with-explanation-by-tanyaaa24-b2gf | Complexity\n- Time complexity: O(N * Min taps)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. | tanyaaa24 | NORMAL | 2022-12-11T17:30:11.289342+00:00 | 2022-12-11T17:30:11.289381+00:00 | 1,990 | false | # Complexity\n- Time complexity: O(N * Min taps)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> \n\n# Code\n```\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) \n {\n int taps = 0;\n int maxi = 0, mini = 0; // initially both are zero\n int lastTap = 0;\n\n while(maxi < n)\n {\n for(int i = lastTap; i <= n; i++)\n {\n if(i - ranges[i] <= mini && i + ranges[i] > maxi)\n {\n lastTap = i;\n maxi = i + ranges[i];\n }\n }\n // if garden cannot be watered\n if(maxi == mini)\n return -1;\n\n taps++;\n mini = maxi;\n }\n return taps;\n }\n};\n\n\n/*\n index = 0 1 2 3 4 5\n range = 3 4 1 1 0 0\n ------------------------- (-3, 3)\n --------------------------------------- (-3, 5)\n --------------- (1, 3)\n --------------- (2, 4)\n - (4, 4)\n - (5, 5)\n\n \n Now I want min number of taps \n so, mai left side se dekhungi ki 0 se start ho and right mein max tak cover kare\n jahan par tap over hoga wo mera new min bann jayega aur phir wahan se dekhungi jo tap max rightmost cover kare \n and so on...\n As soon as, mai last index ko cover karlungi, I need to come out of my loop\n*/\n``` | 7 | 0 | ['Greedy', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | [Python3/Java] Greedy O(n) | Explanation | python3java-greedy-on-explanation-by-mar-g7w6 | One great simplification for this is to skew the taps to the left. For example, say you have a tap at position 4, with range 2. This means this tap covers posit | mardlucca | NORMAL | 2021-11-24T03:39:08.989770+00:00 | 2021-11-29T23:03:09.869857+00:00 | 1,082 | false | One great simplification for this is to skew the taps to the left. For example, say you have a tap at position 4, with range 2. This means this tap covers positions [2, 6]. What we want to do is to transform the problem and suppose taps can only shoot water to the right. So, in order to cover the same area (i.e [2, 6]), we will want to place a tap at position 2 that can shoot water all the way to position 6. Now, after skewing, if two taps ocupy the same initial position, we want to keep the one that can shoot water the furthest.\n\nNow, in the end all you want to do is do a pass in the new skewed version of the taps list, and greedly see how far you can go. First you take the first tap and see where that reaches. Now, as you walk to that position, you want to keep looking which tap you should take next, you will want to take the one that leads you the furthest. And so on....\n\nJava:\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] taps = new int[ranges.length];\n for (int i = 0; i < ranges.length; i++) {\n int left = Math.max(0, i - ranges[i]);\n taps[left] = Math.max(taps[left], i + ranges[i]);\n }\n \n int total = 0;\n int reach = 0;\n int nextReach = 0;\n \n for (int i = 0; i < taps.length; i++) {\n nextReach = Math.max(nextReach, taps[i]);\n \n if (i == reach) {\n if (nextReach == reach) { return -1; }\n total++;\n reach = nextReach;\n if (nextReach >= n) { break; }\n }\n }\n \n return total;\n }\n}\n```\n\nPython:\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n taps = [0] * len(ranges) \n for i,r in enumerate(ranges):\n left = max(0, i - r)\n taps[left] = max(taps[left], i + r)\n\n total = reach = nextReach = 0\n for i, r in enumerate(taps):\n nextReach = max(nextReach, r)\n \n if i == reach:\n if nextReach == reach: return -1\n \n total += 1\n reach = nextReach\n if (nextReach >= n): break\n \n return total\n```\n \n | 7 | 0 | ['Greedy', 'Java', 'Python3'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ with Explanation | O(n) Time and Space | Greedy | c-with-explanation-on-time-and-space-gre-87y3 | Approach-1 (Greedy)\nThe Greedy strategy here is to always choose the interval with the largest space that is yet to be watered. Now we could have done this by | mercuryVapor | NORMAL | 2021-06-18T13:38:31.579378+00:00 | 2021-06-18T14:05:09.033676+00:00 | 575 | false | **Approach-1** (Greedy)\nThe Greedy strategy here is to always choose the interval with the largest space that is yet to be watered. Now we could have done this by storing all the inytervals for each tap and then selecting the largest uncovered interval each time. But this choosing interval method cannot be done in O(1) time as each time we choose an interval, the unused space in the other intervals also changes.\n\nSo what we do is that since we know we have to cover each interval atleast once in our optimal solution, we start from the origin. \n\nFor each tap, we store the farthest coordinate to the right that can be civered by the same tap in an array. Then, while traversing the array, we also store the max right coordinate that has been covered by the all the coordinates we have visited till now. We also store the max right fot the current tap. Once we cross the max right for the current tap, we set the new value as the next rightmost tap. This way , by maintaining two variables current farthest and next farthest, even if we see a coordinate greater than the max coordinate covered by the current tap, we dont have to find whether we have to include it or not in out answer. We just update the distance in our next farthest variable. This way, if we find a better interval in the future, we can include that when we fnd the uncovered coordinate in the future. This works because through this, we only open a tap when we need to open it and and by then we already have the best further distance we need.\nTime Complexity->O(n)\nSpace Complexity->O(n)\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n \n vector<int>maxRightUsingSameTap(n+1);\n for(int i=0;i<=n;i++)\n {\n int leftRange=max(0,i-ranges[i]);\n int rightRange=min(n,i+ranges[i]);\n maxRightUsingSameTap[leftRange]=max(maxRightUsingSameTap[leftRange],rightRange);\n }\n \n int curr_reachable=maxRightUsingSameTap[0];\n int next_reachable=maxRightUsingSameTap[0];\n int taps=1;\n for(int i=1;i<=n;i++)\n {\n if(i>next_reachable)\n {\n return -1;\n }\n if(i>curr_reachable)\n {\n taps++;\n curr_reachable=next_reachable;\n }\n next_reachable=max(next_reachable,maxRightUsingSameTap[i]);\n }\n return taps;\n }\n};\n```\n\n**Approach-2** (Typical DP)\nHere, for each tap, we check the left and the right range. Then for each tap in this range, we check if adding an extra tap to the taps required till the left border is less than or equal to the number currently there. If yes, then we update the answer.\nHere dp[i] is the minimum number of taps to water from 0 to i.\nTime Complexity->O(NR) where R is the avg. range for each tap.\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n \n vector<int>dp(n+1, n+2);\n dp[0]=0;\n for(int i=0;i<=n;i++)\n {\n int leftRange=max(0,i-ranges[i]);\n int rightRange=min(n,i+ranges[i]);\n for(int j=leftRange+1;j<=rightRange;j++)\n {\n dp[j]=min(dp[j],dp[leftRange]+1);\n }\n }\n return dp[n]>n+1?-1:dp[n];\n }\n};\n```\n | 7 | 0 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | ⏰3 Minutes To Realise \\\ Greedy Approach \\\ Beats 99% | 3-minutes-to-realise-greedy-approach-bea-qhix | Make sure that the following works\nSimple algorithm O(n) space, time.\n\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr | mchlkrpch | NORMAL | 2023-08-31T10:00:39.950008+00:00 | 2023-08-31T16:11:13.843237+00:00 | 450 | false | # Make sure that the following works\n**Simple algorithm O(n) space, time.**\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for idx, cur_radius in enumerate(ranges):\n if cur_radius == 0:\n continue\n \n left_border_idx = max(0, idx - cur_radius)\n arr[left_border_idx] = max(arr[left_border_idx], idx + cur_radius)\n\n right_border_of_watered_points = 0\n ans, watered_on_cur_step = 0, 0\n\n for idx, right_border in enumerate(arr):\n if idx > watered_on_cur_step:\n if right_border_of_watered_points <= watered_on_cur_step:\n return -1\n ans += 1\n watered_on_cur_step = right_border_of_watered_points\n\n right_border_of_watered_points = max(right_border_of_watered_points, right_border)\n\n return ans + (watered_on_cur_step < n)\n\n```\n\n# Approach\n1. It\'s necessary to realise that we should water segment but not dots only, so the example\n> n = 2, arr = [1, 0, 0, 1]\n\nshould return -1\n\n2. Let\'s make an `arr = [0] * (n + 1)` to store there the most remote right spot in line which can be covered with current spot with one fountain.\nSo we begin and fill the array:\n```\narr = [0] * (n + 1)\nfor idx, cur_radius in enumerate(ranges):\n if cur_radius == 0:\n continue\n # To write to arr[i] most remote right spot\n # we should return on current step to the most\n # remote left spot and write to \'there idx + cur_radius\'\n left_border_idx = max(0, idx - cur_radius)\n arr[left_border_idx] = max(arr[left_border_idx], idx + cur_radius)\n```\n3. After that we just count taps. `i` is i-th step on cycle.\n - **IDEA 1**: We will maintain `right_border_of_watered_points` variable which indicates the most right remote spot which can be watered by all meeted fountains on $$\\{0, 1, \\dots, i - 1\\}$$ steps.\n - **IDEA2**: We will increment number of needed taps \n - former right border of group less than `i`. Because we include the whole segment [0, i-1] and according to **2.** i-1 was the most right remote spot for previous group.\n```\nfor idx, right_border in enumerate(arr):\n if idx > right_border_of_group:\n ans += 1\n right_border_of_group = right_border_of_watered_points\n\n right_border_of_watered_points = max(right_border_of_watered_points, right_border)\n```\n4. When should we return -1?\nWhen on steps $$\\{0, \\dots, i-1\\}$$ we didn\'t meet fountain that was cover `i-th` dot. So we should upgrade or piece of code that was written in **3.**!\n```\nfor idx, right_border in enumerate(arr):\n if idx > right_border_of_group:\n # We didn\'t meet on steps 0, ... i-1 tap\n # that it\'s radius + (it\'s index) > i - 1.\n if right_border_of_watered_points <= right_border_of_group:\n return -1\n ans += 1\n right_border_of_group = right_border_of_watered_points\n\n right_border_of_watered_points = max(right_border_of_watered_points, right_border)\n```\n\n5. The last step is not to miss last increment of `answer\'s` variable: So just add 1 if `right_border_of_group` < `n`.\n\n.\n.\n.\n## Upvote if you quickly understood :) | 6 | 0 | ['Array', 'Dynamic Programming', 'Greedy', 'Python', 'Python3'] | 3 |
minimum-number-of-taps-to-open-to-water-a-garden | BRUTE FORCE DP || C++ | brute-force-dp-c-by-ganeshkumawat8740-e4w4 | Code\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int i,j;\n vector<int> dp(n+1,n+10);\n dp[0] = 0;\n | ganeshkumawat8740 | NORMAL | 2023-06-06T04:18:25.633694+00:00 | 2023-06-06T04:18:38.891900+00:00 | 1,295 | false | # Code\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int i,j;\n vector<int> dp(n+1,n+10);\n dp[0] = 0;\n for(int i = 0; i <= n; i++){\n for(j = max(0,i-ranges[i]+1); j<=min(n,i+ranges[i]); j++){\n dp[j] = min(dp[j],dp[max(i-ranges[i],0)]+1);\n }\n }\n return dp[n]>=n+2?-1:dp[n];\n }\n};\n``` | 6 | 0 | ['Array', 'Dynamic Programming', 'Greedy', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Simple Python | Explained | Comments | Greedy | simple-python-explained-comments-greedy-sjbtb | Prerequisites:\n- https://leetcode.com/problems/jump-game\n- https://leetcode.com/problems/jump-game-ii\n\nMore tips:\n- https://www.notion.so/paulonteri/Greedy | paulonteri | NORMAL | 2021-10-20T18:38:59.606859+00:00 | 2021-10-20T18:38:59.606906+00:00 | 1,271 | false | Prerequisites:\n- https://leetcode.com/problems/jump-game\n- https://leetcode.com/problems/jump-game-ii\n\nMore tips:\n- https://www.notion.so/paulonteri/Greedy-Algorithms-b9b0a6dd66c94e7db2cbbd9f2d6b50af#d7578cbb76c7423d9c819179fc749be5\n- https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/506853/Java-A-general-greedy-solution-to-process-similar-problems\n```\n\nclass Solution:\n def minTaps(self, n, ranges):\n taps = 0\n\n # # Save the right-most possible jump for each left most index\n jumps = [-1]*(n)\n for idx, num in enumerate(ranges):\n if num == 0:\n continue\n left_most = max(0, idx-num)\n right_most = min(n, idx+num)\n\n jumps[left_most] = max(jumps[left_most], right_most)\n\n # # Jump Game II\n current_jump_end = 0\n furthest_can_reach = -1 # furthest jump we made/could have made\n for idx, right_most in enumerate(jumps):\n\n # we continuously find the how far we can reach in the current jump\n # record the futhest point accessible in our current jump\n furthest_can_reach = max(right_most, furthest_can_reach)\n\n # if we have come to the end of the current jump, we need to make another jump\n # the new jump should start immediately after the old jump\n if idx == current_jump_end:\n # if we cannot make a jump and we need to make a jump to increase the furthest_can_reach\n if right_most == -1 and furthest_can_reach <= idx:\n return -1\n # move to the furthest possible point\n current_jump_end = furthest_can_reach\n taps += 1\n\n if furthest_can_reach == n:\n return taps\n return -1\n\n``` | 6 | 0 | ['Greedy', 'Python', 'Python3'] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ solution (Sorting and Two Pointers) || Full explanation and appropriately commented | c-solution-sorting-and-two-pointers-full-r5u2 | Define a structure "Interval" to hold the left and right extremes of each tap (clipped at 0 and n)\n Convert the ranges array into a vector of Intervals\n Sort | Selachimorpha | NORMAL | 2021-09-21T13:11:47.474244+00:00 | 2021-09-21T13:12:29.437046+00:00 | 534 | false | * Define a structure "Interval" to hold the left and right extremes of each tap (clipped at 0 and n)\n* Convert the ranges array into a vector of Intervals\n* Sort the vector of Intervals in the increasing order of starting points. If two intervals have the same starting points give preference to the one with a higher ending Point\n* Take the first Interval. If the starting point of this interval is more than 0 then return -1 (No taps will be able to water the garden). If the starting point == 0 and ending point >=n return 1. (This tap is sufficient).\n* Use two pointers namely j and i. j keeps track of last tap used and i is used to iterate and find the next best tap.\n* Keep a variable watered to check how far you can water the garden while maintaining continuity with the previously watered portion.\n* If the current tap can water a larger area then update watered \n* If the current tap waters less than watered then ignore\n* Take care to not create disjoint intervals by seeing that the current tap starting point<= the last tap ending point.\n* Maintain and update the cnt variable to return the minimum number of taps\n```\n// Interval to define the boundaries of a tap\nstruct Interval {\n int start;\n int end;\n Interval(int start,int end) {\n this->start=start;\n this->end=end;\n }\n};\n\n// Sort on the basis of increasing starting points and decreasing endin points\nbool compare(const Interval* i1,const Interval* i2) {\n if (i1->start!=i2->start) \n return i1->start<i2->start;\n else\n return i1->end>i2->end;\n}\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n\t\n\t\t// Vector of Intervals\n vector<Interval*> A(n+1);\n for (int i=0;i<ranges.size();i++) {\n A[i]=new Interval(max(i-ranges[i],0),min(i+ranges[i],n));\n }\n sort(A.begin(),A.end(),compare);\n\t\t\n int cnt=0;\n int i=0;\n\t\t\n\t\t// Max watered area until now\n int watered=A[i]->end; \n \n\t cnt++;\n\t\t\n\t\t// If first tap can\'t water the interval starting from 0 no one can\n if (A[i]->start>0)\n return -1;\n\t\t\t\n\t\t// If first tap is sufficient\n if (watered>=n)\n return 1;\n //last watered tap\n\t\tint j=0;\n // find the next optimal tap\n\t i=1;\n\t \n while (j<n+1 && watered<n) {\n int nextTap=-1;\n while (i<n+1 && watered<n) {\n\t\t\t // Ignore if watering less area\n if (A[i]->end<=watered) {\n i++;\n } else if (A[i]->end>watered) {\n\t\t\t\t\t// check if maintains continuity\n if (A[i]->start<=A[j]->end) {\n nextTap=i; // probable next tap\n watered=A[i]->end; // Update the max area watered\n i++;\n } else {\n break; // Moving further will cause discontinuity\n }\n }\n }\n if (nextTap==-1) // No tap can maintain the continuity\n return -1;\n cnt++;\n j=nextTap; // next optimal tap\n \n }\n return cnt; \n }\n};\n```\n\nPlease comment your valuable suggestions!!\nUpvote if helpful!!\nCheers!! | 6 | 0 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | Java Solution - Greedy | java-solution-greedy-by-dixon_n-wz7x | 1024. Video Stitching\n45. Jump Game II\n1326. Minimum Number of Taps to Open to Water a Garden\n\n# Code\njava []\n// Approach -1\n\nclass Solution {\n publ | Dixon_N | NORMAL | 2024-08-30T17:40:54.531381+00:00 | 2024-08-30T17:41:33.660198+00:00 | 358 | false | [1024. Video Stitching](https://leetcode.com/problems/video-stitching/solutions/5712090/simple-solution-greedy/)\n[45. Jump Game II](https://leetcode.com/problems/jump-game-ii/solutions/5297066/all-three-solution/)\n[1326. Minimum Number of Taps to Open to Water a Garden](https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/solutions/5712096/java-solution-greedy/)\n\n# Code\n```java []\n// Approach -1\n\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n List<Pair> intervals = new ArrayList<>();\n for (int i = 0; i <= n; i++) {\n int left = Math.max(0, i - ranges[i]);\n int right = Math.min(n, i + ranges[i]);\n intervals.add(new Pair(left, right));\n }\n\n // Sort intervals based on the start point\n Collections.sort(intervals, (a, b) -> a.start - b.start);\n\n int jumps = 0;\n int currentEnd = 0;\n int i = 0;\n int farthestEnd = 0;\n\n while (currentEnd < n) {\n jumps++;\n farthestEnd = 0;\n\n // Find the tap that covers the farthest right while starting within or before currentEnd\n while (i < intervals.size() && intervals.get(i).start <= currentEnd) {\n farthestEnd = Math.max(farthestEnd, intervals.get(i).end);\n i++;\n }\n\n if (farthestEnd <= currentEnd) {\n // If we can\'t extend further, it\'s impossible to water the entire garden\n return -1;\n }\n\n currentEnd = farthestEnd;\n }\n\n return jumps;\n }\n\n class Pair {\n int start;\n int end;\n Pair(int start, int end) {\n this.start = start;\n this.end = end;\n }\n }\n}\n```\n```java []\n// Approach -2\n\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] maxReach = new int[n + 1];\n \n for (int i = 0; i <= n; i++) {\n int left = Math.max(0, i - ranges[i]);\n int right = Math.min(n, i + ranges[i]);\n maxReach[left] = Math.max(maxReach[left], right);\n }\n \n int jumps = 0;\n int currentEnd = 0;\n int farthestEnd = 0;\n \n for (int i = 0; i <= n; i++) {\n if (i > farthestEnd) {\n return -1;\n }\n \n if (i > currentEnd) {\n jumps++;\n currentEnd = farthestEnd;\n }\n \n farthestEnd = Math.max(farthestEnd, maxReach[i]);\n }\n \n return jumps;\n }\n}\n``` | 5 | 0 | ['Greedy', 'Java'] | 4 |
minimum-number-of-taps-to-open-to-water-a-garden | 🔥 Easy C++ : Minimum Jump to Reach Last Index Variation DP + Memoization🔥 | easy-c-minimum-jump-to-reach-last-index-o2gzz | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is to find the minimum number of taps required to water a garden. Each tap | eknath_mali_002 | NORMAL | 2023-08-31T02:55:24.692960+00:00 | 2023-08-31T02:55:24.692979+00:00 | 504 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find the minimum number of taps required to water a garden. Each tap has a range, and you can turn on a tap at any position within its range to water that segment of the garden. You need to cover the entire garden with the minimum number of taps.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Creating Valid Tap Ranges Array (v): The first step is to create an array v where each index represents a position in the garden, and the value at that index represents the rightmost point a tap can water from that position. To populate this array, iterate through the ranges array, and for each tap, update the valid watered area in the v array.\n\n2. Dynamic Programming (dp) for Minimum Taps: The main function minTaps() uses a dynamic programming approach to find the minimum number of taps required to cover the entire garden. The dp array is used to store the minimum number of taps required to water from each position.\n\n3. Recursive Helper Function (helper): A recursive helper function helper() calculates the minimum number of taps required starting from a given index. It iterates through the valid tap ranges array v and tries to find the optimal tap to turn on from the current position. It then recursively calculates the minimum number of taps required for the remaining garden.\n\n4. Base Cases and Optimization: In the helper() function, there are base cases to handle the end of the garden or if the tap at the current position has no valid range. To avoid recalculating the same subproblems, memoization using the dp array is employed.\n\n5. Final Result: The minTaps() function calls the helper() function for the starting position (index 0) and returns the result. If the result is still the initialized large value 1e9, it means that it\'s not possible to water the entire garden, and -1 is returned. Otherwise, the minimum number of taps needed is returned.\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:$$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nint helper(int ind , int n , vector<int>&nums, vector<int>&dp){\n if(ind >=n) return 0;\n if(nums[ind] == 0) return 1e9;\n if(dp[ind] != -1) return dp[ind];\n int temp = 1e9;\n for(int i = ind+1; i<=nums[ind]; i++){\n temp = min(temp , 1 + helper(i,n,nums,dp));\n }\n return dp[ind] = temp;\n}\nint minTaps(int n, vector<int>& ranges) {\n vector<int>v(n+1 , 0);\n for(int i=0;i<=n;i++){\n if(ranges[i] == 0) continue;\n int ind = max(0 , i-ranges[i]);\n int val = i+ranges[i];\n v[ind] = max(v[ind] , val);\n }\n\n // for(auto x : v)cout<<x<< " ";\n // cout<<endl;\n vector<int>dp(n+2 , -1);\n int ans = helper(0 , n , v,dp);\n return ans==1e9?-1:ans;\n }\n};\n``` | 5 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | GREEDY + SORTING ,WITHOUT DP | greedy-sorting-without-dp-by-comder_00-mmk3 | Okay so,\nthis is basically a question for overlapping ranges. You can find similar questions on leetcode itself.\nso what is the approach?\nwe first find the r | comder_00 | NORMAL | 2022-08-26T16:00:25.871138+00:00 | 2022-08-26T16:20:01.851736+00:00 | 587 | false | Okay so,\nthis is basically a question for overlapping ranges. You can find similar questions on leetcode itself.\nso what is the approach?\nwe first find the ranges of all the taps in the garden\nlet\'s understand with an example\nn=4;\n[2,1,1 ,2,1]\nso finding the ranges for indexes:\n0: (0-2,0+2)=(0,2)\n1:(1-1,1+1)=(0,2)\n2:(2-1,2+1)=(1,3)\n3:(3-2,3+2)=(1,4) (as max possible is 4 not 5)\n4:(4-1,4+1)=(3,4)\n \n now, we sort the ranges w.r.t the starting and ending positions\n we need to sort it like: asc order for the first value and desc order for the second as to get the maximum possible right end for a particular point.\n As, we need to water the entire garden, so we start from position 0\n\n\n\n as you can see these are the ranges, so we select the ranges greedly so as to get the minimum ranges possible\n and then we keep on considering overlapping intervals with the maximum last value.\n \n so first we take (0,2) \n 1st: (0,2) this doesnot increase the last value\n 2nd:(1,4) we an take this into consideration as 1<2(last value)\n hence temp is updated to 4;\n 3rd:(3,4) we cannot consider this as 3>2.\n now we update last value to 4 and increase the count of taps\n as(n==4)\n we return the count.\n **NOTE:** and if we find that the current last value is less than the start of the next range(i,e: range[i].first), then we can say that the interval (last,range[i].first) cannot be watered. So we return -1.\n **IF YOU FIND THE SOLUTION HELPFUL, DO UPVOTE**\n ```\nclass Solution {\npublic:\n static bool comp(pair<int,int> &a,pair<int,int> &b)\n {\n if(a.first==b.first)\n return a.second>b.second;\n return a.first<b.first;\n }\n int minTaps(int n, vector<int>& ranges) \n {\n vector<pair<int,int>> range;\n for(int i=0;i<=n;i++)\n {\n int left=max(i-ranges[i],0);\n int right=min(i+ranges[i],n);\n range.push_back({left,right});\n }\n sort(range.begin(),range.end(),comp);\n int ctr=1;\n int last=range[0].second;\n for(int i=0;i<range.size();i++)\n {\n int temp=last;\n if(last==n)\n return ctr;\n if(last<range[i].first)\n return -1;\n while(i<range.size() and range[i].first<=last)\n {\n temp=max(temp,range[i].second);\n i++;\n }\n if(i==range.size() or range[i].first>last)\n i--;\n last=temp;\n ctr++;\n if(last==n)\n return ctr;\n }\n return ctr;\n }\n};\n```\nTime complexity: O(NlogN)\nSpace Complexity: O(N) | 5 | 0 | ['Greedy', 'Sorting'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ simple solution using DP | c-simple-solution-using-dp-by-maitreya47-osc2 | Solution 1:\nThere are n+1 taps, so we first create our dp vector and initialise all to n+2 (impossible value as only options available == n+1).\ndp[i] will sto | maitreya47 | NORMAL | 2021-07-18T15:31:02.984691+00:00 | 2022-11-17T23:48:07.193855+00:00 | 1,176 | false | # Solution 1:\nThere are n+1 taps, so we first create our dp vector and initialise all to n+2 (impossible value as only options available == n+1).\ndp[i] will store minimum number of taps to cover range [0, i].\nStart from tap 1 and update for all the taps within its range [i-ranges[i], i+ranges[i]], we check it with It needs to be compared with dp[i-ranges[i]] + 1, as we can only cover range only upto i-ranges[i] to the left.\nAlso remember to check if i-ranges[i]<0 (in that case take 0)\nor if i+ranges[i]>n (in that case take n)\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> dp(n+1, n+2); //Need to initialise this n+2, as we might need to calculate dp[i] at some point were dp[i] is still unchanged, and intialising it to something like INT_MAX will make an overflow\n dp[0]=0;\n for(int i=0; i<ranges.size(); i++) // start from 0, or else miss calculations for further j\'s (i.e. dp\'s depending on dp[0])\n {\n for(int j = max(0, i-ranges[i]); j<=min(n, i+ranges[i]); j++)\n dp[j] = min(dp[j], dp[max(0, i-ranges[i])]+1);\n }\n return (dp[n]>=n+2)?-1:dp[n];\n }\n};\n```\nTime complexity: O(n^2)\nSpace complexity: O(n)\n\n# Solution 2:\nNow that we saw O(n^2) solution, lets see if it possible to do this in linear time. Now notice that this problem can be treated as a jump game problem where you have to cover range [0, n] in minimum number of jumps. Notice that ranges array just gives the span where the ranges[i] indicates tap placed position i would cover. Similarity here is that span can be treated as the range of the jump. So if we start from anywhere between max(0, i-ranges[i]) = l and min(n, i+ranges][i]) = r, we can "JUMP" r-l positions. So create a jump array that stores this values. \nOnce the jump vector is created, keep a counter of number of jumps done until now, currEnd that we can reach and the currFar which is the farthest position we can reach.\nStart a for loop from 0 to jumps.size()-2 (inclusive) because if we reach \nthe last position n, we dont need to jump from there hence, there is no need to process the jump value of last position.\nIf the current position if farther away from reach (>currFar) return -1 straight away. Update the currFar as maximum of current value and what is the furthest you can jump from here.\nIf you reach currEnd, meaning you have landed and now need to jump once more, increment the count of jumps and set currEnd = currFar as that will be the current End (GREDDY Solution).\nReturn count, only if n position was reachable.\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> jumps(n+1, 0);\n for(int i=0; i<ranges.size(); i++)\n {\n int l = max(0, i-ranges[i]);\n int r = min(n, i+ranges[i]);\n jumps[l] = max(jumps[l], r-l);\n }\n int count = 0, currEnd = 0, currFar = 0;\n for(int i=0; i<jumps.size()-1; i++)\n {\n if(i>currFar)\n return -1;\n currFar = max(currFar, i+jumps[i]);\n if(i==currEnd) //now we reach the end of the current range\n {\n count++;\n currEnd = currFar; //set current range to farthest we can reach\n }\n }\n return currFar>=n?count:-1;\n }\n};\n```\nTime complexity: O(n)\nSpace complexity: O(n) | 5 | 1 | ['Dynamic Programming', 'C', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Best explanation with visualisation || C++ || faster than 100% solution | best-explanation-with-visualisation-c-fa-vgut | After reading so many solutions, I got to know that whats actually happening.\nMy explanation and solution is really simple and straight forward.\n\nAlso please | arpitdhamija | NORMAL | 2021-07-18T13:17:32.323844+00:00 | 2021-07-18T13:21:07.945742+00:00 | 328 | false | After reading so many solutions, I got to know that whats actually happening.\nMy explanation and solution is really simple and straight forward.\n\nAlso please read some solutions on "most voted", you\'ll understand it more clearly then\n\nAlso do checkout jump game 2 on leetcode. Otherise I have also pasted an image here for understanding\n\nHere, I\'m calculating the max jump it can take from a position, basis on that problem breaks down to - "jumps game 2 - on leetcode"\n\nAlso given comments in code for more clearity\n\n\n\n\n\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int>maxJumps(n+1,0);\n for(int i=0;i<=n;i++){\n int left = max(0, i - ranges[i]);\n int right = min(n, i + ranges[i]);\n int jumpLength = right - left; // max jump it can take\n maxJumps[left] = max(maxJumps[left] , jumpLength); // max jump that can be taken from left. See the image and also draw yourself once for clear understanding\n }\n \n // now its jump game 2\n int currReach = 0;\n int maxReach = 0;\n int jumps = 0;\n \n for(int i=0; i < n; i++){\n maxReach = max(maxReach, i + maxJumps[i]);\n \n if(i > currReach) return -1; // suppose current reach was till 10 and i reaches 11, when jump can\'t be done, so return -1\n \n if(i == currReach){\n currReach = maxReach;\n jumps ++;\n }\n }\n return jumps;\n }\n};\n``` | 5 | 1 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ DP | c-dp-by-wzypangpang-8w1z | \nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int big = 1e7;\n\t\t// dp[i] stands for the minimum taps to cover the range | wzypangpang | NORMAL | 2021-03-31T20:47:45.168754+00:00 | 2021-03-31T20:51:26.063125+00:00 | 394 | false | ```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int big = 1e7;\n\t\t// dp[i] stands for the minimum taps to cover the range [0, i].\n\t\t// By definition, it can be deducted that dp[i] <= dp[j] for any i < j. Becasue dp[j] could always qualify dp[i].\n vector<int> dp(n+1, big); \n dp[0] = 0;\n \n for(int i=0; i<=n; i++) {\n int start = max(0, i - ranges[i]);\n int end = min(n, i + ranges[i]);\n \n if(dp[start] != big) {\n for(int j = start; j<=end; j++) {\n dp[j] = min(dp[j], 1 + dp[start]);\n }\n }\n }\n \n \n return dp[n] == big ? -1 : dp[n];\n }\n};\n``` | 5 | 0 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | 🏆Easy Understandble Code || 🚀Similar to Jump game-II 🚀 || O(N)🏆 | easy-understandble-code-similar-to-jump-ilf9b | \n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(1)\n\n# Code\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) | rajh_3399 | NORMAL | 2023-08-31T18:39:56.267239+00:00 | 2023-08-31T18:39:56.267271+00:00 | 71 | false | \n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> startEnd(n+1, 0);\n for(int i = 0; i<ranges.size(); i++) { \n int start = max(0, i - ranges[i]);\n int end = min(n, i + ranges[i]); \n startEnd[start] = max(startEnd[start], end); \n }\n int taps = 0;\n int currEnd = 0;\n int maxEnd = 0;\n for(int i = 0; i<n+1; i++) {\n if(i > maxEnd) return -1; \n if(i > currEnd) {\n taps++;\n currEnd = maxEnd;\n } \n maxEnd = max(maxEnd, startEnd[i]); \n }\n return taps; \n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'Greedy', 'C++'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Sorting + Greedy || Easy C++ || image Explanation ✅✅ | sorting-greedy-easy-c-image-explanation-cz3y5 | Approach\n Describe your approach to solving the problem. \nTry to convert the given array into the interval format given below and sort the intervals based on | Deepak_5910 | NORMAL | 2023-08-31T14:41:26.622363+00:00 | 2023-08-31T14:41:26.622381+00:00 | 633 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nTry to convert the given array into the **interval format** given below and **sort the intervals** based on the **starting position** and now choose the intervals that give the optimal answer.\n\n\n\n\n# Complexity\n- Time complexity:O(N*Log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool static compare(pair<int,int> p1,pair<int,int> p2)\n {\n if(p1.first!=p2.first) return p1.first<p2.first;\n return p1.second>=p2.second;\n }\n int minTaps(int n, vector<int>& arr) {\n vector<pair<int,int>> intr;\n int m = arr.size();\n for(int i = 0;i<m;i++)\n {\n int strt = max(0,i-arr[i]);\n int end = min(n,i+arr[i]);\n if(strt!=end)\n intr.push_back({strt,end});\n }\n if(intr.size()==0) return -1;\n sort(intr.begin(),intr.end(),compare);\n if(intr[0].second==0) return -1;\n int count = 1,strt = intr[0].first,end = intr[0].second;\n int maxend = 0,i= 0;\n for(int i = 1;i<intr.size();i++)\n {\n if(end>=n) return count;\n if(intr[i].first>end)\n {\n if(intr[i].first>maxend) return -1;\n end = maxend;\n count++;\n }\n maxend = max(maxend,intr[i].second);\n }\n if(maxend<n) return -1;\n if(end<maxend) count++;\n \n return count;\n }\n};\n``` | 4 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | || C++ || EASY EXPLANATION || | c-easy-explanation-by-amol_2004-vcv4 | Approach\n- Firstly convert the given array into interval array bu using formula {i - ranges[i], i + ranges[i]}\n- Sort the array\n- Now remove the overlapping | amol_2004 | NORMAL | 2023-08-31T06:12:41.995375+00:00 | 2023-08-31T06:14:22.994856+00:00 | 410 | false | # Approach\n- Firstly convert the given array into interval array bu using formula {i - ranges[i], i + ranges[i]}\n- Sort the array\n- Now remove the overlapping and count the ans. See code for better understanding.\n- In while loop first for loop if to check if 2 or move tap can fill that area then take the larger one\n<!-- Describe your approach to solving the problem. -->\n\n\n# Code\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<vector<int>> intervals;\n for(int i = 0; i < ranges.size(); i++){\n intervals.push_back({-ranges[i] + i, ranges[i] + i});\n }\n\n sort(intervals.begin(), intervals.end());\n int i = 0, start_time = 0, end_time = 0;\n int ans = 0;\n\n while(end_time < n){\n for(; i < intervals.size() && intervals[i][0] <= start_time; i++)\n end_time = max(end_time, intervals[i][1]); \n if(start_time == end_time)\n return -1;\n \n start_time = end_time;\n ans++;\n }\n return ans;\n }\n};\n```\n\n\n | 4 | 0 | ['C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Easy Java 5ms Solution using DP | easy-java-5ms-solution-using-dp-by-viraj-wl5x | Code\n\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] is_reachable = new int[n+1];\n\n int inf = (int) 1e9;\n\n A | Viraj_Patil_092 | NORMAL | 2023-08-31T05:16:53.134392+00:00 | 2023-08-31T05:16:53.134412+00:00 | 301 | false | # Code\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int[] is_reachable = new int[n+1];\n\n int inf = (int) 1e9;\n\n Arrays.fill(is_reachable, inf);\n is_reachable[0] = 0;\n\n for(int i = 0;i < ranges.length;i++){\n int mn = Math.max(0,i-ranges[i]);\n int mx = Math.min(n,i+ranges[i]);\n\n for(int j = mn;j < mx;j++){\n is_reachable[mx] = Math.min(is_reachable[mx],is_reachable[j]+1);\n }\n\n }\n\n return is_reachable[n] == inf ? -1 : is_reachable[n];\n }\n}\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Greedy', 'Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | [Python3][Stack] Easy Stack Solution beats 94% runtime. | python3stack-easy-stack-solution-beats-9-ewop | Approach\n Describe your approach to solving the problem. \n1. Initialize an empty stack called range_stack to keep track of the ranges being used.\n2. Initiali | near6334 | NORMAL | 2023-08-31T05:13:33.389097+00:00 | 2023-08-31T16:15:55.099857+00:00 | 552 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an empty stack called `range_stack` to keep track of the ranges being used.\n2. Initialize a variable `covered` to keep track of the total coverage achieved.\n3. Iterate through the given ranges. For each range, check if the current range can be extended to cover the garden.\n - If the current range overlaps with the last range in the `range_stack`, discard the range(s) from the `range_stack` that are no longer needed to extend the coverage.\n - If the current range does not overlap with the last range in the `range_stack`, add it to the `range_stack` and update the coverage.\n - If the total coverage becomes equal to or greater than `n`, return the number of taps used.\n4. If the entire garden is not covered after processing all ranges, return -1.\n.\n# Complexity\n- Time complexity:O(n)\n- The time complexity of this code depends on the number of ranges and the operations performed within the loops. The inner while loop that pops ranges from the `range_stack` runs in linear time O(m), where m is the number of taps in the `range_stack`. Since each tap can be added or removed at most once, the overall time complexity of the algorithm is O(n), where n is the number of ranges.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n- The space complexity is determined by the `range_stack`, which can hold at most all the ranges. Therefore, the space complexity is O(n).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n range_stack = []\n covered = 0\n res = len(ranges) + 1\n for idx, range_ in enumerate(ranges):\n if range_stack and idx+range_ < range_stack[-1][1]:\n continue\n while range_stack and range_stack[-1][0] >= idx - range_:\n popped_range = range_stack.pop()\n covered -= popped_range[1] - popped_range[0]\n if not range_stack or range_stack[-1][1] < idx+range_:\n if not range_stack:\n left_point = max(idx-range_, 0)\n else:\n left_point = max([idx-range_, 0, range_stack[-1][1]])\n new_coverage = min(idx+range_, n)-left_point\n range_stack.append([left_point, min(idx+range_, n)])\n covered += new_coverage\n if covered >= n:\n res = min(res, len(range_stack)) \n return -1 if res == len(ranges) + 1 else res\n \n``` | 4 | 0 | ['Python3'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | BEST C++ SOLUTION U CAN GET | best-c-solution-u-can-get-by-2005115-vz5y | PLEASE UPVOTE MY SOLUTION AND COMMENT FOR ANY DOUBT\n# Doubt shall be cleared within 3 hr )\nConnect with me here\n- https://www.linkedin.com/in/pratay-nandy-9b | 2005115 | NORMAL | 2023-08-31T04:05:43.958282+00:00 | 2023-08-31T04:05:43.958302+00:00 | 509 | false | # **PLEASE UPVOTE MY SOLUTION AND COMMENT FOR ANY DOUBT**\n# Doubt shall be cleared within 3 hr )\n**Connect with me here**\n- [https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n]()\n- [https://www.instagram.com/pratay_nandy/\n]()\n\n# Approach\nThe provided code is implementing a solution to the "Minimum Number of Taps to Open to Water a Garden" problem. This problem can be thought of as watering a garden with a set of sprinklers that have different ranges. The goal is to determine the minimum number of sprinklers that need to be opened to cover the entire garden. Here\'s an explanation of the approach:\n\nCreating an Array of Ranges:\n\nInitialize a vector arr of size n + 1 to represent the ranges of each sprinkler. Each index i corresponds to the position in the garden, and the value at index i represents the farthest position the sprinkler at i can reach.\nIterate through the given ranges vector. For each sprinkler, if its range is not zero, calculate the leftmost and rightmost positions it can cover and update the arr array with the farthest reachable position from that leftmost position.\nIterating through Garden Positions:\n\nInitialize variables: end to keep track of the farthest position reached by the sprinklers, far_can_reach to keep track of the farthest position a sprinkler can reach, and cnt to count the number of sprinklers turned on.\nIterate through each position in the garden (from 0 to n).\nIf the current position is beyond end, it means a new sprinkler needs to be turned on. Check if far_can_reach is less than or equal to end, indicating there\'s a gap that can\'t be covered by any sprinkler. In this case, it\'s not possible to cover the garden, so return -1.\nUpdate end to be far_can_reach (the farthest position a sprinkler can reach) and increment the cnt.\nReturning the Result:\n\nReturn the count of sprinklers turned on (cnt) plus 1 if end is less than n, which means the last position of the garden hasn\'t been covered yet.\nThe approach involves simulating the process of turning on sprinklers to cover the garden while keeping track of their ranges and the farthest positions they can reach. The algorithm aims to find the minimum number of sprinklers required to cover the entire garden.\n\nOverall, this algorithm is efficient as it iterates through the garden positions and the sprinkler ranges only once, resulting in a time complexity of O(n), where n is the length of the garden. The use of additional variables and arrays contributes to a space complexity of O(n).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> reach(n + 1, 0);\n for(int i = 0; i < ranges.size(); ++i) {\n if(ranges[i] == 0) continue;\n int leftBound = max(0, i - ranges[i]);\n reach[leftBound] = max(reach[leftBound], i + ranges[i]);\n }\n \n int endPos = 0, farthestReach = 0, tapCount = 0;\n for(int i = 0; i <= n; ++i) {\n if(i > endPos) {\n if(farthestReach <= endPos) return -1;\n endPos = farthestReach;\n ++tapCount;\n }\n farthestReach = max(farthestReach, reach[i]);\n }\n \n return tapCount + (endPos < n);\n }\n};\n\n``` | 4 | 0 | ['Array', 'Greedy', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Java | Progression from recursion to DP solution | java-progression-from-recursion-to-dp-so-79t0 | \n# Intuition\nFirst try simple recursion, get TLE, then try to return an output like integer, then try memoization using DP\n\n# Code (TLE, only recursion)\n\n | pacificlion | NORMAL | 2023-08-31T01:30:12.082938+00:00 | 2023-08-31T01:34:14.948870+00:00 | 622 | false | \n# Intuition\nFirst try simple recursion, get TLE, then try to return an output like integer, then try memoization using DP\n\n# Code (TLE, only recursion)\n```\nclass Solution {\n\n\n int res = Integer.MAX_VALUE;\n public int minTaps(int n, int[] ranges) {\n helper(0,0,0,ranges,0);\n\n return res==Integer.MAX_VALUE?-1:res;\n }\n\n private void helper(int start, int end, int index , int[] ranges, int len){\n if(end-start+1==ranges.length){\n res = Math.min(res, len);\n\n return;\n }\n if(index>=ranges.length){\n return;\n }\n\n // taken\n int new_start = Math.max(0,index-ranges[index]);\n int new_end = Math.min(ranges.length-1,index+ranges[index]);\n // System.out.printf("new_coord:(%d,%d), old:(%d,%d),curr:%d\\n",new_start,new_end,start,end,index);\n if((new_end>end)&&(new_start<=end)){\n helper(Math.min(new_start,start),new_end,index+1, ranges,len+1);\n }\n\n // not taken\n helper(start,end,index+1,ranges,len);\n }\n}\n```\n\n# Convert solution to convert it to give an integer output as dp requires some state (still TLE)\n\n```\nclass Solution {\n\n\n int res = Integer.MAX_VALUE;\n public int minTaps(int n, int[] ranges) {\n \n int out = helper(0,0,0,ranges);\n return out==Integer.MAX_VALUE?-1:out;\n }\n\n private int helper(int start, int end, int index , int[] ranges){\n if(end==ranges.length-1){\n return 0;\n }\n if(index>=ranges.length){\n return Integer.MAX_VALUE;\n }\n // taken\n int new_start = Math.max(0,index-ranges[index]);\n int new_end = Math.min(ranges.length-1,index+ranges[index]);\n int val1=Integer.MAX_VALUE,val2=Integer.MAX_VALUE;\n \n if((new_end>end)&&(new_start<=end)){\n \n int tmp = helper(Math.min(new_start,start),new_end,index+1, ranges);\n if(tmp!=Integer.MAX_VALUE){\n val1 = 1+ tmp;\n }\n \n }\n\n // not taken\n val2 = helper(start,end,index+1,ranges);\n // if(val1!=Integer.MAX_VALUE || val2!=Integer.MAX_VALUE)\n // System.out.printf("new_coord:(%d,%d), old:(%d,%d),curr:%d,val1=%d,val2=%d\\n",new_start,new_end,start,end,index, val1, val2);\n\n return Math.min(val1,val2);\n }\n}\n```\n\n\n# How dp array should be saved\n1. 2D array - int[n+1][n+1], (start,end) state, though it would work but it will give memory limit exceeded as n can go upto 10^4\n2. 1D array - int[n+1], end getting tracked as we will only consider if end becomes equal to n. We only consider changing end,i.e. new_end if it increases range and overlaps with existing range\n\n```\nclass Solution {\n\n\n int res = Integer.MAX_VALUE;\n public int minTaps(int n, int[] ranges) {\n \n int[] dp = new int[n+1];\n \n Arrays.fill(dp,-1);\n \n int out = helper(0,0,0,ranges,dp);\n return out==Integer.MAX_VALUE?-1:out;\n }\n\n private int helper(int start, int end, int index , int[] ranges, int[] dp){\n if(end==ranges.length-1){\n return 0;\n }\n if(index>=ranges.length){\n return Integer.MAX_VALUE;\n }\n\n if(dp[end]!=-1){\n return dp[end];\n }\n // taken\n int new_start = Math.max(0,index-ranges[index]);\n int new_end = Math.min(ranges.length-1,index+ranges[index]);\n int val1=Integer.MAX_VALUE,val2=Integer.MAX_VALUE;\n \n if((new_end>end)&&(new_start<=end)){\n \n int tmp = helper(Math.min(new_start,start),new_end,index+1, ranges,dp);\n if(tmp!=Integer.MAX_VALUE){\n val1 = 1+ tmp;\n }\n \n }\n\n // not taken\n val2 = helper(start,end,index+1,ranges,dp);\n // if(val1!=Integer.MAX_VALUE || val2!=Integer.MAX_VALUE)\n // System.out.printf("new_coord:(%d,%d), old:(%d,%d),curr:%d,val1=%d,val2=%d\\n",new_start,new_end,start,end,index, val1, val2);\n\n dp[end] = Math.min(val1,val2);\n return dp[end];\n }\n}\n```\n\n\n | 4 | 0 | ['Java'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | C++,Greedy,Interval based | cgreedyinterval-based-by-nideesh45-aiwx | \nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<pair<int,int>> v;\n for(int i=0;i<ranges.size();i++){\n | nideesh45 | NORMAL | 2022-07-08T03:49:12.244641+00:00 | 2022-07-08T03:49:12.244684+00:00 | 648 | false | ```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<pair<int,int>> v;\n for(int i=0;i<ranges.size();i++){\n // making ranges\n v.push_back({i-ranges[i],i+ranges[i]});\n }\n // sorting the intervals\n sort(v.begin(),v.end());\n \n // to keep track from where we need to cover\n int uncovered = 0;\n int idx = 0;\n // number of ranges used\n int cnt = 0;\n \n // to check if its possible\n bool ok = true;\n \n // as long as we have not covered the garden\n while(uncovered<n){\n // we will try to cover the uncovered such that new uncovered is maximum possible\n int new_uncovered = uncovered;\n while(idx<n+1 && v[idx].first<=uncovered){\n new_uncovered = max(new_uncovered,v[idx].second);\n idx++;\n }\n // we have used one range\n cnt++;\n \n // it means we were not able to cover with ranges so not possible\n if(new_uncovered == uncovered){\n ok = false;\n break;\n }\n // updating uncovered for next iteration\n uncovered = new_uncovered;\n }\n if(ok) return cnt;\n return -1;\n }\n};\n``` | 4 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | ✔️ EXPLANATION || PYTHON ✔️ | explanation-python-by-karan_8082-tkfy | First fid the ranges of all taps.\nHere ranges are stored in same array a.\na[ i ][ 0 ] = lower range of tap i\na[ i ][ 1 ] = upper range of tap i\n\nSort the r | karan_8082 | NORMAL | 2022-06-05T10:35:32.806431+00:00 | 2022-06-05T10:35:32.806456+00:00 | 359 | false | First fid the ranges of all taps.\nHere ranges are stored in same array a.\n**a[ i ][ 0 ] = lower range of tap i**\n**a[ i ][ 1 ] = upper range of tap i**\n\nSort the ranges according to first value.\nThen start from garden index to be watered. Choose the pair that has maximum upper range and has garden index between lower and upper values.\n```\nclass Solution:\n def minTaps(self, n: int, a: List[int]) -> int:\n for i in range(n+1):\n a[i]=[max(0,i-a[i]), i+a[i]]\n a.sort()\n s=0\n i=0\n ans=0\n while i<n+1 and s<n:\n l=s\n while i<n+1 and a[i][0]<=s:\n l=max(l,a[i][1])\n i+=1\n if s==l:\n break\n s=l\n ans+=1\n if s>=n:\n return ans\n return -1\n```\n\n | 4 | 0 | ['Array', 'Sorting'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Simple Javascript solution 1-dimensional DP Bottom Up | simple-javascript-solution-1-dimensional-5tr6 | Use bottom up approach dp to record the minimum number of taps needed. Iterate through all the ranges, and at location k, take the minimum of between the memoiz | liangpeter | NORMAL | 2022-04-23T03:13:39.355875+00:00 | 2022-04-23T03:13:39.355909+00:00 | 534 | false | Use bottom up approach dp to record the minimum number of taps needed. Iterate through all the ranges, and at location k, take the minimum of between the memoized result and 1 + (taps need to cover the rest of the ranges k - 1).\n```\nvar minTaps = function(n, ranges) {\n const dp = new Array(n + 1).fill(Infinity);\n dp[0] = 0;\n \n for (let i = 0; i < ranges.length; i++) {\n const leftCover = Math.max(0, i - ranges[i]);\n const rightCover = Math.min(n, i + ranges[i]);\n for (let k = leftCover; k <= rightCover; k++) {\n dp[k] = Math.min(dp[k], 1 + dp[leftCover]);\n }\n }\n if (dp[n] === Infinity) {\n return -1;\n }\n return dp[n]; \n};\n``` | 4 | 0 | ['Dynamic Programming', 'JavaScript'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ || GREEDY || SHORT AND CLEAN CODE || NO-SORTING | c-greedy-short-and-clean-code-no-sorting-z9s8 | ```\nclass Solution {\npublic:\n int minTaps(int n, vector& ranges) {\n int mn = 0;\n int reach = 0;\n int taps = 0;\n \n | Easy_coder | NORMAL | 2022-01-12T09:58:50.506878+00:00 | 2022-01-12T09:58:50.506912+00:00 | 621 | false | ```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int mn = 0;\n int reach = 0;\n int taps = 0;\n \n while(reach < n){\n for(int i=0; i<ranges.size(); i++){\n if(i-ranges[i] <= mn && i+ranges[i] > reach)\n reach = i + ranges[i];\n }\n if(mn == reach) return -1;\n taps++;\n mn = reach;\n }\n return taps;\n }\n}; | 4 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Java - O(N) - Jump Game II + I Concept | java-on-jump-game-ii-i-concept-by-protya-txpp | One of the classic Hard problem.\n\n\nSo, we need to build intervals of [left,right] for each of the given tap.\nTo convert this into a Jump Game II array, we n | protyay | NORMAL | 2021-07-04T18:34:07.924510+00:00 | 2021-07-04T18:34:07.924554+00:00 | 354 | false | One of the classic Hard problem.\n\n\nSo, we need to build intervals of _[left,right]_ for each of the given tap.\nTo convert this into a Jump Game II array, we need to store the max jump for each index(tap).\n\n*We re-iterate through the jumps array and check the maxReach at each index*\nOne concept of jump game I is used, where if we reach any index which is equal to maxReach\nthen, we cannot water the whole garden and we return -1;\n```\n\npublic int minTaps(int n, int[] ranges) {\n if(n == 1) return 1;\n int[] jumps = new int[n+1];\n for(int i = 0 ; i < ranges.length; i++){\n if(ranges[i] == 0) continue;\n \n int left = Math.max(0, i - ranges[i]);\n jumps[left] = Math.max(jumps[left], i + ranges[i]);\n }\n \n // jump game II\n int jump = 0, maxReach = 0, currEnd = 0;\n for(int i = 0 ; i < jumps.length; i++){\n maxReach = Math.max(jumps[i], maxReach);\n if(maxReach >= n ) break;\n \n if(i == maxReach) return -1; // Jump Game 1 concept\n if(i == currEnd){\n ++jump;\n currEnd = maxReach;\n }\n }\n return jump + 1;\n }\n``` | 4 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++, O(n) with a stack, only a few lines of code. | c-on-with-a-stack-only-a-few-lines-of-co-1925 | The idea is to just iterate though taps one by one, and see which previous taps the current tap can replace, and the put current tap onto the stack if it can ex | deeperblue | NORMAL | 2021-05-24T00:52:23.319447+00:00 | 2021-05-24T00:52:23.319488+00:00 | 428 | false | The idea is to just iterate though taps one by one, and see which previous taps the current tap can replace, and the put current tap onto the stack if it can expand the coverage.\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n stack<pair<int, int>> tapsInfo;\n tapsInfo.push(make_pair(INT_MIN, 0));\n \n for (int i = 0; i <= n; ++i) {\n if (ranges[i] > 0 && i + ranges[i] > tapsInfo.top().second) {\n while (i - ranges[i] <= tapsInfo.top().first) {\n tapsInfo.pop();\n }\n \n if (tapsInfo.top().second < n && i - ranges[i] <= tapsInfo.top().second) {\n tapsInfo.emplace(tapsInfo.top().second, i + ranges[i]);\n }\n }\n }\n \n return tapsInfo.top().second >= n ? tapsInfo.size() - 1 : -1;\n }\n};\n``` | 4 | 0 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | [Java] clean O(n) Greedy Solution || with detailed comments | java-clean-on-greedy-solution-with-detai-nmh7 | This problem is basically Leetcode 45. Jump Game II but construct the array (furthestIdx in the solution here) by ourselves. Before you solving this problem, I | xieyun95 | NORMAL | 2021-03-20T00:12:07.034957+00:00 | 2021-03-20T00:56:21.250993+00:00 | 1,116 | false | This problem is basically Leetcode 45. Jump Game II but construct the array (furthestIdx in the solution here) by ourselves. Before you solving this problem, I strongly recommand to get familiar with these "prototype" questions or revisit the solutions. \n* [55. Jump Game](https://leetcode.com/problems/jump-game/discuss/1117827/Java-clean-O(N)-time-O(1)-space-Greedy-Solution-oror-with-detailed-comments)\n* [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/discuss/1117791/Java-O(1)-space-Greedy-Solution-oror-with-detailed-comments)\n\nThe problem 1024. Video Stitching is another direct generalization of Jump Game Problems. Although the process to constructing the array is more straightforward. \n* [1024. Video Stitching](https://leetcode.com/problems/video-stitching/discuss/1117847/Java-clean-O(n)-Greedy-Solution-oror-with-useful-comments) \n\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n /*\n The array furthestIdx is defined as follows: \n \n furthestIdx[i] = j means suppose garden[0 : i-1] has been covered by some taps, \n then j is the furthest garden s.t. we may add 1 more tap and cover garden[i : j] \n \n */\n int[] furthestIdx = new int[n+1];\n Arrays.fill(furthestIdx, -1);\n \n for (int i = 0; i <= n; i++) {\n if (ranges[i] == 0) continue;\n \n // tap at garden[i] may cover garden[left, right]\n int left = Math.max(i - ranges[i], 0);\n int right = Math.min(i + ranges[i], n);\n \n // thus adding 1 tap at garden[i] can cover till garden[right]\n furthestIdx[left] = Math.max(furthestIdx[left], right);\n }\n \n // far : furthest garden we can cover with t tap\n // initailly we need 1 tap to cover garden[0], this tap can be chosen to cover garden[0, furthestIdx[0]]\n int far = furthestIdx[0]; \n int t = 1;\n \n if (far == n) return 1;\n \n // find the furthest position we can cover with t+1 taps\n int next = 0;\n \n for (int i = 0; i <= n; i++) {\n if (i > far) return -1;\n \n next = Math.max(next, furthestIdx[i]);\n if (next == n) return t+1;\n \n // i == far <==> i is the furthest garden we can cover using t taps\n // update far = next, the furthest garden we can cover using t+1 taps which is already calculated \n if (i == far) {\n far = next;\n t++;\n }\n }\n \n return -1;\n }\n}\n\n``` | 4 | 0 | ['Greedy', 'Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | JavaScript Interval Merging | javascript-interval-merging-by-daleighan-opwe | \nfunction minTaps(n, ranges) {\n let intervals = [];\n for (let i = 0; i < ranges.length; i++) {\n intervals.push([i - ranges[i], i + ranges[i]]);\n }\n | daleighan | NORMAL | 2020-01-21T02:42:09.324485+00:00 | 2020-01-21T02:42:09.324576+00:00 | 296 | false | ```\nfunction minTaps(n, ranges) {\n let intervals = [];\n for (let i = 0; i < ranges.length; i++) {\n intervals.push([i - ranges[i], i + ranges[i]]);\n }\n intervals.sort((a, b) => a[0] - b[0]);\n let currentL = 0, currentR = 0, taps = 0, i = 0;\n while (i < intervals.length) {\n while (i < intervals.length && intervals[i][0] <= currentL) {\n currentR = Math.max(currentR, intervals[i][1]);\n i++;\n }\n taps++;\n if (currentR >= n) {\n return taps;\n }\n if (currentL === currentR) {\n return -1;\n }\n currentL = currentR;\n }\n};\n``` | 4 | 0 | ['JavaScript'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | O(n^2) DP, O(nLog(n)) greedy, O(n) greedy solution | on2-dp-onlogn-greedy-on-greedy-solution-msxly | O(n^2) DP\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& r) {\n int dp[n+1];\n for(int i =0;i<n+1;i++) dp[i] = n+3;\n dp | objectobject | NORMAL | 2020-01-20T18:41:11.592283+00:00 | 2020-01-20T20:00:58.033407+00:00 | 465 | false | **O(n^2) DP**\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& r) {\n int dp[n+1];\n for(int i =0;i<n+1;i++) dp[i] = n+3;\n dp[0] = 0;\n for(int i = 0;i<=n;i++)\n {\n for(int j = max(0,i-r[i]);j<=min(i+r[i],n);j++)\n {\n dp[j] = min(dp[j],dp[max(0,i-r[i])]+1);\n }\n }\n return dp[n] == n+3?-1:dp[n];\n }\n};\n```\n\n**nLog(n) Greedy**\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& r) {\n vector<vector<int> >rng;\n for(int i =0;i<=n;i++)\n {\n rng.push_back({max(0,i-r[i]),min(n,i+r[i])});\n }\n sort(rng.begin(),rng.end());\n int beg=-1,end=0;\n int ans = 0;\n for(int i = 0;i<rng.size();i++)\n {\n if(rng[i][0] > end)\n {\n return -1;\n }\n if(rng[i][0]>beg and rng[i][1]>end)\n {\n ans++;\n beg = end;\n }\n end = max(end,rng[i][1]);\n }\n return end<n?-1:ans;\n }\n};\n```\n\n**O(n) Greedy**\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int reach[n+1] = {};\n for(int i = 0;i<=n;i++)\n {\n \n reach[max(0,i-ranges[i])] = max(reach[max(0,i-ranges[i])],min(n,i+ranges[i]));\n }\n int next = reach[0];\n int i = 0;\n int nextMax = next;\n int ans = 1;\n while(i<=next and i<n)\n {\n nextMax = max(nextMax,reach[i]);\n if(i == next)\n {\n if(nextMax == next and next!=n)\n {\n return -1;\n }\n next = nextMax;\n ans++;\n if(next == n)\n {\n break;\n }\n }\n i++;\n }\n return next!=n?-1:ans;\n }\n};\n``` | 4 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | JavaScript DP with detailed comments | javascript-dp-with-detailed-comments-by-7x3ce | js\nvar minTaps = function(n, ranges) {\n // dp[i] means the smallest number of taps required to water under i;\n const dp = Array(n + 1).fill(n + 2);\n dp[0 | paradite | NORMAL | 2020-01-19T06:08:30.847363+00:00 | 2020-01-19T06:08:30.847399+00:00 | 901 | false | ```js\nvar minTaps = function(n, ranges) {\n // dp[i] means the smallest number of taps required to water under i;\n const dp = Array(n + 1).fill(n + 2);\n dp[0] = 0;\n // iterate all taps\n for (let i = 0; i <= n; i++) {\n const start = i - ranges[i] > 0 ? i - ranges[i] : 0;\n const end = ranges[i] + i > n ? n : ranges[i] + i;\n // for each point j that the range of tap covers, update dp[j]\n for (let j = start; j <= end; j++) {\n // check what\'s the previous min number of taps required to cover until start of the range or j\n const previousMin = Math.min(...dp.slice(start, j + 1));\n dp[j] = Math.min(dp[j], previousMin + 1);\n }\n }\n\n return dp[n] === n + 2 ? -1 : dp[n];\n};\n\n``` | 4 | 0 | ['Dynamic Programming', 'JavaScript'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | is this a wrong test case? | is-this-a-wrong-test-case-by-ltt198612-qiyk | ```\n35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]\n 4 4 5 4 5\n\t\t | ltt198612 | NORMAL | 2020-01-19T04:08:12.946936+00:00 | 2020-01-19T04:08:12.946972+00:00 | 371 | false | ```\n35\n[1,0,4,0,4,1,4,3,1,1,1,2,1,4,0,3,0,3,0,3,0,5,3,0,0,1,2,1,2,4,3,0,1,0,5,2]\n 4 4 5 4 5\n\t\t \nThe result should be 5,\nHowever the test case is expecting 6?\n | 4 | 1 | [] | 3 |
minimum-number-of-taps-to-open-to-water-a-garden | Greedy solution using stack. Detailed explanation | greedy-solution-using-stack-detailed-exp-22xj | Python code\nInline explanation in the code\nNotes at the end\n\n\nclass Solution(object):\n def minTaps(self, n, ranges):\n ranges = sorted([(i - r, | kaiwensun | NORMAL | 2020-01-19T04:02:13.833889+00:00 | 2020-01-19T06:47:43.640273+00:00 | 790 | false | Python code\nInline explanation in the code\nNotes at the end\n\n```\nclass Solution(object):\n def minTaps(self, n, ranges):\n ranges = sorted([(i - r, min(i + r, n)) for i, r in enumerate(ranges)]) # sort by ranges\' left point. the min is needed. see notes below\n stack = [(0, 0), (0, 0)] # dummy ranges to avoid stack[-2] from overflow\n for r in ranges:\n if r[0] > stack[-1][1]:\n break # the gardon between stack[-1][1] and r[0] can\'t be watered. so return -1\n if r[1] <= stack[-1][1]:\n continue # r will not contribute more coverage. so r is useless.\n while r[0] <= stack[-2][1] and len(stack) > 2:\n stack.pop() # in this case, r can completely replace stack[-1]\n stack.append(r)\n if stack[-1][1] == n:\n return len(stack) - 2 # do not count the two dummy ranges\n else:\n return -1\n\n```\n## Notes\n\n> sort by ranges\' left point\n\nIf left points are same, sort by their right points. The ranges with smaller right point are actually useless, because they, if in the stack, will eventually meet the condition `r[0] <= stack[-2][1]` and be popped out from the stack by the range which has a bigger right point.\n\n---\n\n> the min is needed\n\nthe `min` is needed because even if this range has a very big right point, we wtill want to give remaining ranges an opportunity to pop this range, in case such a pop can make the stack shorter.\n\n---\n\n> the gardon between stack[-1][1] and r[0] can\'t be watered. so return -1\n\nActually, it is still possilble to return a positive number if the stack[-1][1] is already n\n | 4 | 1 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | Minimum Number of Taps to Open to Water a Garden | minimum-number-of-taps-to-open-to-water-vqpyb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rissabh361 | NORMAL | 2023-08-31T15:33:07.611548+00:00 | 2023-08-31T15:33:07.611568+00:00 | 910 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool static compare(pair<int,int> p1,pair<int,int> p2)\n {\n if(p1.first!=p2.first) return p1.first<p2.first;\n return p1.second>=p2.second;\n }\n int minTaps(int n, vector<int>& arr) {\n vector<pair<int,int>> intr;\n int m = arr.size();\n for(int i = 0;i<m;i++)\n {\n int strt = max(0,i-arr[i]);\n int end = min(n,i+arr[i]);\n if(strt!=end)\n intr.push_back({strt,end});\n }\n if(intr.size()==0) return -1;\n sort(intr.begin(),intr.end(),compare);\n if(intr[0].second==0) return -1;\n int count = 1,strt = intr[0].first,end = intr[0].second;\n int maxend = 0,i= 0;\n for(int i = 1;i<intr.size();i++)\n {\n if(end>=n) return count;\n if(intr[i].first>end)\n {\n if(intr[i].first>maxend) return -1;\n end = maxend;\n count++;\n }\n maxend = max(maxend,intr[i].second);\n }\n if(maxend<n) return -1;\n if(end<maxend) count++;\n \n return count;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | O(NlogN + N) Approach || Beginner Friendly | onlogn-n-approach-beginner-friendly-by-l-5yjo | Approach\n- Creating new array consisting of start and end ranges of each tap.\n- sorting the array according to their starting position.\n- traversing array ti | Lil_ToeTurtle | NORMAL | 2023-08-31T03:39:43.867169+00:00 | 2023-08-31T03:39:43.867194+00:00 | 149 | false | # Approach\n- Creating new array consisting of start and end ranges of each tap.\n- sorting the array according to their starting position.\n- traversing array till the furthest point that can be reached, if the new range is encountered, then loops continues and `res++` because that is a valid range\n- if no new range is encountered, then the garden cannot be fully watered.\n# Complexity\n- Time complexity: $$O(nlogn +n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n int r=ranges.length, ar[][]=new int[r][2];\n for(int i=0;i<r;i++) {\n ar[i][0]=Math.max(0, i-ranges[i]);\n ar[i][1]=Math.min(n, i+ranges[i]);\n }\n Arrays.sort(ar, (a,b)->a[0]-b[0]);\n int start=0, res=0;\n for(int i=0;i<r;) {\n int farthest = -1;\n for(;i<r && ar[i][0]<=start;i++) \n farthest = Math.max(farthest, ar[i][1]);\n if(farthest<=start) return -1;\n start=farthest;\n res++;\n if(farthest==n) return res;\n }\n return res;\n }\n}\n``` | 3 | 0 | ['Greedy', 'Sorting', 'Java'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Beats 92.85 in runtime 85.93 in memory Greedy approach | beats-9285-in-runtime-8593-in-memory-gre-h0mk | \n# Code\n\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for i, r in enumerate(ranges):\n | ayan_101 | NORMAL | 2023-08-31T02:51:58.574312+00:00 | 2023-08-31T02:53:21.560815+00:00 | 27 | false | \n# Code\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n arr = [0] * (n + 1)\n for i, r in enumerate(ranges):\n if r == 0:continue\n left = max(0, i - r);arr[left] = max(arr[left], i + r)\n end, far_can_reach, cnt = 0, 0, 0\n for i, reach in enumerate(arr):\n if i > end:\n if far_can_reach <= end:return -1\n end, cnt = far_can_reach, cnt + 1\n far_can_reach = max(far_can_reach, reach)\n return cnt + (end < n)\n``` | 3 | 0 | ['Array', 'Divide and Conquer', 'Dynamic Programming', 'Greedy', 'Brainteaser', 'Sliding Window', 'Suffix Array', 'Sorting', 'Counting', 'Python3'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Python3 Solution | python3-solution-by-motaharozzaman1996-vwkh | \n\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp=[0]+[n+2]*n\n for i,x in enumerate(ranges):\n for j | Motaharozzaman1996 | NORMAL | 2023-08-31T02:31:12.087729+00:00 | 2023-08-31T02:31:12.087750+00:00 | 337 | false | \n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n dp=[0]+[n+2]*n\n for i,x in enumerate(ranges):\n for j in range(max(i-x+1,0),min(i+x,n)+1):\n dp[j]=min(dp[j],dp[max(0,i-x)]+1)\n\n return dp[n] if dp[n]<n+2 else -1 \n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | JAVA Easily Understandable Solution with Explanation and Comments | java-easily-understandable-solution-with-2hxb | Approach: We just have to find the tap with largest rightMax range && which should start atleast from our current minimum ranged reached. Now the current minimu | abhi71k | NORMAL | 2022-08-09T08:26:48.853961+00:00 | 2022-08-09T17:41:13.607162+00:00 | 642 | false | **Approach:** We just have to find the tap with largest rightMax range && which should start **atleast** from our current minimum ranged reached. Now the current minimum point will be the rightMax range of previously selected tap.\nHence if no tap is selected, previous minimum would be 0, so next tap should be selected as: left point zero or less than zero, but right should be max of all.\nRepeat untill we get rightMax >= time.\n```\npublic int minTaps(int n, int[] ranges) {\n int max = 0;\n int min = 0;\n int taps = 0;\n while(max<n){\n\t\t\n\t\t//finding the best fit max by keeping min as constant\n for(int i=0; i<ranges.length; i++){\n int left = i-ranges[i];\n int right = i+ ranges[i];\n if(left<=min && right>max){\n max = right;\n }\n }\n\t\t\t\n\t\t\t//now if there is a gap, then it is not possible to merge ranges of taps,\n\t\t\t//hence min == max indicates that we end up getting same max as previous hence not possible.\n if(min == max) return -1;\n \t\n\t\t\t//now our max will be min\n min = max;\n\t\t\t\n\t\t\ttaps++;\n\t\t\t//now we will find the next best fit tap\n }\n return taps;\n }\n```\n\n**Upvote it, If you like the explanation** | 3 | 0 | ['Greedy', 'Java'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Great Explained Greedy Solution in Python, Very Easy to Understand!!! | great-explained-greedy-solution-in-pytho-c267 | Use Greedy method!\n\nTwo parts:\n\nPart 1:\nGenerate a jump list, which keeps the rightmost index that every index could reach in one move.\nFor Example:\n[3 4 | GeorgePot | NORMAL | 2022-05-08T18:33:08.739776+00:00 | 2022-05-21T19:17:09.430165+00:00 | 352 | false | Use **Greedy** method!\n\n**Two parts:**\n\n**Part 1:**\nGenerate a **jump list**, which keeps the rightmost index that every index could reach in one move.\n**For Example:**\n[3 4 1 1 0 0]\nindex 0: range [0 3], jump list[0] = 3 (**Note:** if left range is smaller than 0, left range would be 0)\nindex 1: range [0 5], jump list[0] = 5\nindex 2: range [1 3], jump list[1] = 3\nindex 3: range [2 4], jump list[2] = 4\nindex 4: range[4 4], jump list[4] = 4\nindex 5: range[5 5], jump list[5] = 5\nSo, **jump list** should be **[5 3 4 0 4 5]**\n\n**Part 2:**\nNow the question **becomes exactly another question: "Q45: Jump Game II**:\nSuppose we have a jump list, each value indicates how far we could reach in one jump from that index.\nWe can easily solve it using Greedy!\n\n**Reference:**\nhttps://leetcode.com/problems/jump-game-ii/\nhttps://leetcode.com/problems/jump-game-ii/discuss/2055683/Greatly-Explained-Greedy-Solution-in-Python-Time-O(n)-Easy-to-Understand!!!\n\n**Time:** O(n)\n**Space:** O(n)\n\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n \n rightmosts = [0] * len(ranges)\n for index, radius in enumerate(ranges):\n left = max(0, index - radius)\n rightmosts[left] = max(index + radius, rightmosts[left])\n \n res = 0\n start = end = 0\n \n\t\twhile end < n:\n start, end = end, max(rightmosts[start: end + 1])\n \n\t\t\tif end == start:\n return -1\n \n\t\t\tres += 1\n \n\t\treturn res\n``` | 3 | 0 | ['Greedy', 'Python'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Similair to 871. Minimum Number of Refueling Stops | similair-to-871-minimum-number-of-refuel-j1hc | I am writing this post as I was not able to find for some time that this question is almost similar to 871. Minimum Number of Refueling Stops. \nOther posts do | ahen445 | NORMAL | 2022-04-18T18:23:49.859360+00:00 | 2022-04-18T18:27:43.015334+00:00 | 457 | false | I am writing this post as I was not able to find for some time that this question is almost similar to 871. Minimum Number of Refueling Stops. \nOther posts do give many other problems which are almost similar to this, maybe we can add it to the same list. \nSharing code for both:\n## Minimum number of refueling stops\n```\nclass Solution {\npublic:\n int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {\n priority_queue<int> pq;\n int i=0, count=0, far=startFuel;\n while(far<target){\n while(i<stations.size() && stations[i][0]<=far){\n pq.push(stations[i][1]);\n i++;\n }\n if(pq.size()==0)\n return -1;\n far=far+pq.top();\n pq.pop();\n count++;\n }\n return count;\n }\n};\n```\n## Minimum Number of Taps to open to water a garden\n```\nclass Solution {\n struct comp{\n bool operator()(const vector<int> &a, const vector<int> &b){\n return a[0]<b[0];\n }\n };\npublic:\n int minTaps(int n, vector<int>& ranges) {\n int target=n;\n vector<vector<int>> stations;\n int k=0;\n for(auto r: ranges){\n int left=k-r;\n int right=k+r;\n k++;\n vector<int> temp;\n temp.push_back(left);\n temp.push_back(right);\n stations.push_back(temp);\n }\n comp cmp;\n sort(stations. begin(), stations.end(), cmp); //! Change from minimum gas refuel\n priority_queue<int> pq;\n int i=0, count=0, far=0, prev_far=0;\n while(far<target){\n while(i<stations.size() && stations[i][0]<=far){\n pq.push(stations[i][1]);\n i++;\n }\n if(pq.size()==0)\n return -1;\n far=far+(pq.top()-far);//! Change from minimum gas refuel\n pq.pop();\n count++;\n }\n return count;\n } \n};\n```\nPlease upvote if this similarity was puzzling you too. | 3 | 0 | ['Greedy', 'Heap (Priority Queue)', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ | Recursive DP | c-recursive-dp-by-codingsuju-61nn | ```\nLet dp[pos] be the minimum number of taps required to cover everything under [0,pos]. \nUsing top-down approach as we all are familiar with.\nsolve(pos) {\ | codingsuju | NORMAL | 2022-01-26T11:21:30.758751+00:00 | 2022-01-26T11:47:00.728050+00:00 | 886 | false | ```\nLet dp[pos] be the minimum number of taps required to cover everything under [0,pos]. \nUsing top-down approach as we all are familiar with.\nsolve(pos) {\nThen for each i from pos-100 to pos-1 {\n if(pos>=i+r[i]) //reachable to pos from i tap so that we can use i tap for pos\n dp[pos]=min(dp[pos],solve(i-r[i])+1) //next pos will be i-r[i]. Check below for explanation\n}\nif(r[pos]>0)\n dp[pos]=min(dp[pos],solve(pos-r[pos])+1)\n}\nIf we open tap no i for the current pos. Then it can cover i-r[i] to i+r[i]. So we should move pos to i-r[i] in top-down approach since \nopening tap no i covers i-r[i] to i+r[i].\n//Code\n\nclass Solution {\npublic:\n int dp[10002];\n vector<int> r;\n int INF=1e9;\n int solve(int pos){\n int ans=INF;\n if(pos<=0)return 0;\n if(dp[pos]!=-1) return dp[pos];\n for(int i=pos-1;i>=(pos-100) && i>=0;i--){\n if(pos<=(i+r[i]))\n ans=min(ans,solve(i-r[i])+1);\n }\n if(r[pos]>0)\n ans=min(ans,solve(pos-r[pos])+1);\n return dp[pos]=ans;\n }\n int minTaps(int n, vector<int>& ranges) {\n memset(dp,-1,sizeof dp);\n r=ranges;\n int ans=solve(n);\n if(ans>=INF)\n return -1;\n return ans;\n }\n}; | 3 | 0 | ['Dynamic Programming', 'Memoization'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Jump Game || Logic, TC: O(N), SC:O(N) | jump-game-logic-tc-on-scon-by-najimali-rcdv | \nclass Solution {\n static int minTaps(int n, int[] ranges) {\n\t\tint dp[] = new int[ranges.length];\n\t\t\n\t\tfor (int i = 0; i < dp.length; i++) {\n\t\t | najimali | NORMAL | 2022-01-18T05:54:44.057737+00:00 | 2022-01-18T05:54:44.057814+00:00 | 284 | false | ```\nclass Solution {\n static int minTaps(int n, int[] ranges) {\n\t\tint dp[] = new int[ranges.length];\n\t\t\n\t\tfor (int i = 0; i < dp.length; i++) {\n\t\t\tif (ranges[i] == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint left = Math.max(i - ranges[i], 0);\n\t\t\tint right = Math.min(i + ranges[i], n);\n\t\t\tdp[left] = Math.max(dp[left], right);\n\t\t}\n\n\t\tint next = 0;\n\t\tint right = dp[0];\n\t\tint count = 0;\n\t\tfor (int i = 0; i < ranges.length; i++) {\n\n\t\t\tnext = Math.max(next, dp[i]);\n\t\t\tif (i == right) {\n\t\t\t\tcount++;\n\t\t\t\tright = next;\n\t\t\t}\n\n\t\t}\n\n\t\treturn right != ranges.length - 1 ? -1 : count;\n \n\t}\n}\n\n\n``` | 3 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Totally Equal to Jump Game 2 -- Java | totally-equal-to-jump-game-2-java-by-fre-v01q | I tried Jump Game 2 first with the traditional BFS method and also a concise version of BFS (top-most voted).\n\nI found this question is totally the same as Ju | freya250817 | NORMAL | 2021-11-27T01:00:21.645629+00:00 | 2022-03-16T03:46:12.539650+00:00 | 397 | false | I tried Jump Game 2 first with the traditional BFS method and also a concise version of BFS `(top-most voted)`.\n\nI found this question is totally the same as Jump Game 2, where 2 steps are needed.\n1) construct an array `reached[]`, `reached[i]` means the furthest point can be reached at current position `i`\n - no need to care about the left-side of `0`\n2) solve Jump Game 2 with minor changes\n - just compare `furthest` with `reached[i]` not `i+ reached[i]` because it already represents the furthest point\n - check if the last level we can reach surpasses the `n`, if not, means we stop before reaching to the end, then should return `-1`\n```java\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n // construct an array: the furthest point it can reach at current index\n int[] reached = new int[ranges.length];\n for(int i = 0; i < ranges.length; i++) {\n int pos = Math.max(0, i - ranges[i]);\n reached[pos] = Math.max(reached[pos], Math.min(n , i + ranges[i]));\n }\n \n int furthest = 0, levelEnd = 0;\n int res = 0;\n for(int i = 0; i < reached.length - 1; i++) {\n furthest = Math.max(furthest, reached[i]);\n if (i == levelEnd) {\n res += 1;\n levelEnd = furthest;\n }\n }\n return levelEnd >= n ? res : -1;\n }\n}\n```\n---\nUpdate\n- Clear BFS version\n```java\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n // construct an array: the furthest point it can reach at current index\n int[] reached = new int[ranges.length];\n for(int i = 0; i < ranges.length; i++) {\n int pos = Math.max(0, i - ranges[i]);\n reached[pos] = Math.max(reached[pos], Math.min(n , i + ranges[i]));\n }\n \n int res = 0;\n int levelS = 0, levelE = 0; // next level start & end bound\n int furthest = 0;\n \n while (levelE < reached.length) {\n res += 1;\n for(int i = levelS; i <= levelE; i++) {\n furthest = Math.max(furthest, reached[i]);\n if (furthest >= n ) return res;\n }\n\t\t\t// If furthest not change & also not return in the above for loop\n\t\t\t// means the furthest we can get will never reach to the end\n if (levelE == furthest) return -1; \n\t\t\t\n // update the next level start & end bound\n levelS = levelE + 1;\n levelE = furthest;\n }\n return -1;\n }\n}\n```\n | 3 | 0 | ['Breadth-First Search'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ Solution | Greedy Approach | c-solution-greedy-approach-by-ajainuary-4kz1 | Solution Approach\n\nWe can solve this problem by using a Greedy Approach. Till we reach the end, determine the largest fountain that covers this position and a | ajainuary | NORMAL | 2021-11-11T07:40:50.996716+00:00 | 2021-11-11T07:40:50.996750+00:00 | 529 | false | ## Solution Approach\n\nWe can solve this problem by using a Greedy Approach. Till we reach the end, determine the largest fountain that covers this position and activate that. Implemented in a naive manner, this will be O(n^2) but with some simple preprocessing we can do this in O(n). We maintain a <code>jumps</code> array that marks the maximum range fountain that covers each position, now our problem reduces to finding the minimum number of jumps to reach the end of the array (<a href="https://leetcode.com/problems/jump-game-ii/">Jump Game II</a>). The final problem can be solved by iterating through the <code>jumps</code> array and marking the farthest position <code>currentReach</code> that could be reached with the jumps considered till now and a <code>endPosition</code> variable that marks the actual position we\'re at after making optimal jumps. Whenever we reach the <code>endPosition</code>, we make the jump to <code>currentReach</code>.\n\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> jumps(n+1, 0);\n for(int i = 0; i <= n; ++i) {\n int l = max(i-ranges[i], 0);\n int r = min(i+ranges[i], n);\n jumps[l] = max(jumps[l], r-l);\n }\n int currentReach = 0, endPosition = 0, cnt = 0;\n for(int i = 0; i < n; ++i) {\n if(i > currentReach) {\n return -1;\n }\n currentReach = max(i + jumps[i], currentReach);\n if(i == endPosition) {\n endPosition = currentReach;\n ++cnt;\n }\n }\n if(endPosition >= n) {\n return cnt;\n } else {\n return -1;\n }\n }\n};\n``` | 3 | 0 | [] | 2 |
minimum-number-of-taps-to-open-to-water-a-garden | Greedy | 8 line solution explained | greedy-8-line-solution-explained-by-hars-sy8p | The idea is we check the maximum ground (mx) we can water after opening the \'open\'th tap.\nwe check that in for loop.\nAfter each openth step, we set mn=mx, b | harshnadar23 | NORMAL | 2021-08-31T13:10:28.247322+00:00 | 2021-08-31T13:10:28.247365+00:00 | 376 | false | The idea is we check the maximum ground (mx) we can water after opening the \'open\'th tap.\nwe check that in for loop.\nAfter each openth step, we set mn=mx, because we need to find a tap which can water the ground from somewhere less than mn to any distance greater than mn.\n\n```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& range) {\n int mx=0,mn=0,open=0;\n while(mx<n){\n for(int i=0;i<n+1;i++){\n if(mn>=i-range[i] && mx<i+range[i]){\n mx=range[i]+i;\n }\n }\n if(mn==mx) return -1;\n mn=mx;\n open++;\n }\n return open;\n }\n};\n```\nThis problem is similar to:\nJump Game II (https://leetcode.com/problems/jump-game-ii/)\nVideo Stitching (https://leetcode.com/problems/video-stitching/)\n | 3 | 0 | ['Greedy'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ || O(n) Solution || Well Commented | c-on-solution-well-commented-by-anshumaa-332d | \nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n\t\n\t\t// dp array shows how far from current index you can give water, if hose is | anshumaaa | NORMAL | 2021-07-29T08:27:36.892788+00:00 | 2021-07-29T08:28:46.041772+00:00 | 450 | false | ```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n\t\n\t\t// dp array shows how far from current index you can give water, if hose is somewhere ahead\n vector<int>dp(n+1,-1);\n for(int i=0;i<=n;i++)\n {\n int left=max(0,i-ranges[i]);\n int right=min(n,i+ranges[i]);\n dp[left]=max(dp[left],right);\n }\n int ft=1; //count of taps\n int nextft=-1; //furtherest distance from next numbered tap if required\n int currft=dp[0]; // furtherest distance from current tap\n for(int i=0;i<n;i++)\n {\n // nextft for next tap\n nextft=max(nextft,dp[i]);\n //only increase tap value if not reached to final destination\n \t\t if(i==currft)\n {\n ft++;\n\t\t\t // choose next tap with maximum distance\n currft=nextft;\n }\n if(currft==n)\n return ft;\n }\n\n return -1;\n\n }\n};\n``` | 3 | 2 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | CPP | Very easy | like jump game | cpp-very-easy-like-jump-game-by-jammera5-b7g0 | \n// 1326. Minimum Number of Taps to Open to Water a Garden\n// similar to the jump game\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& range | jammera5 | NORMAL | 2021-07-14T06:21:11.920692+00:00 | 2021-07-14T06:21:11.920742+00:00 | 304 | false | ```\n// 1326. Minimum Number of Taps to Open to Water a Garden\n// similar to the jump game\n\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n vector<int> dp(n+1,0);\n for(int i=0; i<ranges.size(); i++){\n int piche = max(0,i-ranges[i]);\n int aage = min(n,i+ranges[i]);\n dp[piche] = max(dp[piche],aage);\n }\n int jump = 0;\n int next = 0;\n for(int i=0; i<dp.size(); ){\n int prev=next;\n while(i<=prev && i<=n) next = max(next,dp[i++]);\n if(next>=n) return jump+1;\n if(next==prev && next<n) return -1;\n jump++;\n }\n return -1;\n }\n};\n``` | 3 | 4 | ['C', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | O(N) Time, O(1) space, C++ | on-time-o1-space-c-by-ajaysaiva-0rao | \nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n\tfor(int i=0;i<=n;i++) {\n\t\tint start = max(i-ranges[i],0);\n\t\tranges[start] = | ajaysaiva | NORMAL | 2021-05-14T15:55:19.869861+00:00 | 2021-05-14T15:55:19.869908+00:00 | 344 | false | ```\nclass Solution {\npublic:\n int minTaps(int n, vector<int>& ranges) {\n\tfor(int i=0;i<=n;i++) {\n\t\tint start = max(i-ranges[i],0);\n\t\tranges[start] = max(ranges[start],i+ranges[i]);\n\t}\n\tint curEnd = ranges[0],maxEnd = 0,ans = 1;\n\tfor(int i=0;i<=n;i++) {\n\t\tif(i>curEnd) {\n\t\t\tif(curEnd<maxEnd) {\n\t\t\t\tans++;\n\t\t\t\tcurEnd = maxEnd;\n\t\t\t}\n\t\t\telse return -1;\n\t\t}\n\t\tmaxEnd = max(maxEnd,ranges[i]);\n\t}\n \treturn ans;\n }\n};\n\n``` | 3 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | GoLang DP Solution with Explanation | golang-dp-solution-with-explanation-by-n-bnq0 | Inspired By https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/736944/O(n)-time-complexity-greedy-implementation-in-C%2B%2B- | najis | NORMAL | 2020-12-06T06:00:17.602482+00:00 | 2020-12-06T17:05:59.911424+00:00 | 232 | false | Inspired By https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/736944/O(n)-time-complexity-greedy-implementation-in-C%2B%2B-with-comments\n\n```\nfunc minTaps(n int, ranges []int) int {\n // Find the reach of each position, NOT each tap. We do this by finding the left\n // and right ends of each tap, and then creating a list with the reach from the\n // left, aka pretending like that\'s where the water stream starts, and is only\n // shooting in a straight line.\n reach := make([]int, n+1)\n for i := 0; i < len(ranges); i++ {\n left := max(0, i - ranges[i])\n right := min(n, i + ranges[i])\n reach[left] = max(reach[left], right) \n }\n \n // Count how many taps it takes to get us to the max reach of all water streams.\n globalMax := reach[0]\n localMax := reach[0]\n taps := 1\n for i := 0; i < n; i++ {\n // If we\'ve ever started checking a point that\'s farther than the farthest\n // reach that we know about, that means no water stream has been able to\n // reach this point yet, and no stream ever will (because we\'re only looking \n // at streams shooting in a straight line.)\n if i > globalMax {\n return -1\n }\n \n // Check if the reach from this position is farther than the absolute\n // maximum that we know about, and update if it is.\n globalMax = max(globalMax, reach[i])\n \n // If we\'ve reached a position that\'s farther than the "current" maximum\n // that we\'re tracking, that means we need to be tracking a new water stream,\n // so we add 1 to our tap count, and set the local maximum that we\'re tracking\n // to the absolute maximum that we know about.\n if i == localMax {\n localMax = globalMax\n taps++\n }\n }\n return taps\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n``` | 3 | 0 | ['Dynamic Programming', 'Greedy', 'Go'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | JAVA | O(n) time O(1) space | Simple Solution | java-on-time-o1-space-simple-solution-by-70lu | \'\'\'class Solution {\n public int minTaps(int n, int[] ranges) {\n \n \n int left,right;\n for(int i=0;i<n+1;i++)\n {\n | smasher | NORMAL | 2020-09-21T09:44:00.470974+00:00 | 2020-09-21T09:44:00.471005+00:00 | 412 | false | \'\'\'class Solution {\n public int minTaps(int n, int[] ranges) {\n \n \n int left,right;\n for(int i=0;i<n+1;i++)\n {\n if(ranges[i] != 0)\n {\n left = i-ranges[i];\n right = i+ranges[i];\n \n if(left < 0) left = 0;\n \n if(ranges[left] < right) \n {\n ranges[left] = right;\n }\n }\n }\n \n int max = -1;\n for(int i=0;i<n+1;i++)\n {\n if(i <= max) \n {\n if(ranges[i] > max) max = ranges[i];\n else ranges[i] = max;\n }\n else\n {\n if(ranges[i] == 0) return -1;\n \n max = ranges[i];\n }\n }\n \n \n int lop = ranges[0];\n int taps = 0; \n \n \n while(true)\n {\n if(lop == 0) return -1;\n \n if(lop >= n) return taps+1;\n \n taps++;\n lop = ranges[lop];\n }\n \n }\n}\'\'\' | 3 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Easy Sorting | Python | Top 92% Speed | easy-sorting-python-top-92-speed-by-arag-so4k | Easy Sorting | Python | Top 92% Speed\n\nThe code below takes a very simple approach to this problem, yet it manages to achieve a Top 92% Speed rating.\n\nThe a | aragorn_ | NORMAL | 2020-07-21T21:50:59.818039+00:00 | 2020-07-21T21:51:49.957089+00:00 | 535 | false | **Easy Sorting | Python | Top 92% Speed**\n\nThe code below takes a very simple approach to this problem, yet it manages to achieve a Top 92% Speed rating.\n\nThe algorithm is the following:\n\n1. We first create explicit watering ranges for each Tap, and sort them. This solves 99% of the problem :)\n\n2. By looking at the given Diagram, we note that the problem actually consists in watering all the middle points [0.5 , 1.5, ... , n-0.5 ].\n\n3. Starting from x=0.5 we query all the Tap ranges starting before "x", and find the further reaching Tap. We pick this Tap as our anwer.\n\n4. If our chosen Tap is unable to water "x", we exit with an error (-1). Otherwise, we move to the point "+0.5" to the right from it.\n\n5. We repeat the previous steps until we reach "n-0.5".\n\nThat\'s the code, I hope you guys find it helpful. I think I achieved a High Speed Rating because, after the sorting step, the code does very few O(n) operations. For n = 10000, the difference between O(n) and O(n log n) is very small. If the operations after the sorting step are simple, the difference can be easily compensated.\nCheers,\n\n```\nclass Solution:\n def minTaps(self, n, ranges):\n # Shameless Range conversion\n\t\tfor i,x in enumerate(ranges):\n ranges[i] = [i-x,i+x]\n # Sorting Step\n ranges.sort(reverse=True) # Reverse, so pop() behaves like popleft()\n # Main Loop\n x, res = 0.5, 0 # Try to water points in the middle\n while x<n:\n b = -1\n while ranges and ranges[-1][0]<=x: \n # Idea: 1) Query/Pop all points Starting before "x"\n # 2) Pick the one reaching furthest\n # 3) After one fail, points start at x<a (leave for later)\n b = max(b,ranges.pop()[1])\n if b<0 or b<x: # We didn\'t find anything, or b<x (we never watered "x" at all)\n return -1\n x = b + 0.5\n res += 1\n return res\n``` | 3 | 0 | ['Python', 'Python3'] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Java, merge intervals, explained, clean code | java-merge-intervals-explained-clean-cod-ehs0 | This problem can be viewed as a variation of interval merge problem. Thus the approach can be same - form intervals, sort by starting coordinate, then traverse. | gthor10 | NORMAL | 2020-01-20T16:52:50.117942+00:00 | 2020-01-20T16:52:50.117982+00:00 | 301 | false | This problem can be viewed as a variation of interval merge problem. Thus the approach can be same - form intervals, sort by starting coordinate, then traverse.\n\nWe can exclude intervals with 0 distance - it doesn\'t add anything to solution. \n\nComplexity is O(nlgn) - while we iterate over each interval == range once we need to sort them by the start (left) coordinate. O(n) space - need to keep up to n - 1 intervals.\n\n```\n public int minTaps(int n, int[] ranges) {\n\t\t//form intial list of intervals\n List<int[]> intervals = new ArrayList();\n for (int i = 0; i < ranges.length; i++) {\n if (ranges[i] == 0)\n continue;\n int l = i - ranges[i], r = i + ranges[i];\n intervals.add(new int[] {l, r});\n }\n\t\t//sort intervals based on the left coordinate\n Comparator<int[]> comp = (a1, a2) -> a1[0] - a2[0];\n Collections.sort(intervals, comp);\n \n\t\t//checking how exactly we can merge intervals\n int l = 0, r = 0, res = 0, i = 0;\n while (l < n && i <= intervals.size()) {\n\t\t\t//getting the interval which ends the fatherst to the right\n while (i < intervals.size() && intervals.get(i)[0] <= l) {\n r = Math.max(r, intervals.get(i)[1]);\n ++i;\n }\n\t\t\t//if we can\'t find the right position that extends our current section - it means that there is a \n\t\t\t//gap and some interval of the pitch is not covered. Thus solution is not posible\n if (l >= r)\n return -1;\n\t\t\t//if we reach here means we found section that covers next piece of the pitch, so \n\t\t\t//make our right coordiate as a left for next searches, also increment count of solutions - we \n\t\t\t//picked just one from the list of intervals\n ++res;\n l = r;\n }\n return res;\n }\n``` | 3 | 0 | ['Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Java greedy sol by using sort | java-greedy-sol-by-using-sort-by-cuny-66-s4e1 | Explanation: First eliminate all zero since they are useless. Then sort the array base on the first index,then the second index. After that, we get the first ta | CUNY-66brother | NORMAL | 2020-01-19T05:10:54.839212+00:00 | 2020-01-19T05:29:11.083546+00:00 | 147 | false | Explanation: First eliminate all zero since they are useless. Then sort the array base on the first index,then the second index. After that, we get the first tap by used the 1st loop. With the first tap, we try to find the next tap with the fartest end point. The next tap should overlap with the pre tap. After we find the nexttap, update the previous tap\n\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n List<List<Integer>>list=new ArrayList<>();\n int ans=1;\n for(int i=0;i<ranges.length;i++){\n if(ranges[i]==0){\n continue;\n }\n List<Integer>l=new ArrayList<>();\n int start=Math.max(0,i-ranges[i]);\n int end=Math.min(n,i+ranges[i]);\n l.add(start);l.add(end);\n list.add(l);\n }\n int array[][]=new int[list.size()][2];\n for(int i=0;i<list.size();i++){\n array[i][0]=list.get(i).get(0);\n array[i][1]=list.get(i).get(1);\n }\n Arrays.sort(array, new Comparator<int[]>(){\n public int compare(int[] arr1, int[] arr2){\n if(arr1[0] == arr2[0])\n return arr2[1] - arr1[1];\n else\n return arr1[0] - arr2[0];\n } \n });\n\n int pre[][]=new int[1][2];\n int pos=0;\n int startIndex=0; \n for(int i=0;i<array.length;i++){\n if(array[i][0]==0){\n pre[0][0]=0;\n pre[0][1]=Math.max(pre[0][1],array[i][1]);\n pos=pre[0][1];\n continue;\n }\n startIndex=i;\n break;\n }\n if(pos==n){\n return 1;\n }\n for(int i=startIndex;i<array.length;i++){\n int preend=pre[0][1];\n while(i<array.length&&array[i][0]<=preend){\n if(array[i][1]>pre[0][1]){//update the next open\n pre[0][0]=array[i][0];\n pre[0][1]=Math.max(array[i][1],pre[0][1]);\n }\n pos=pre[0][1];\n i++;\n if(i>=array.length){\n break;\n }\n if(array[i][0]>preend){\n i--;\n break;\n }\n }\n ans++;\n if(pos>=n){\n break;\n }\n\n }\n if(pos<n){\n return -1;\n }\n return ans; \n }\n}\n``` | 3 | 1 | [] | 1 |
minimum-number-of-taps-to-open-to-water-a-garden | Easy Java nlogn Solution with PriorityQueue | easy-java-nlogn-solution-with-priorityqu-zes9 | java\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n if (ranges == null || ranges.length == 0 || n <= 0 || ranges.length != n + 1) ret | dreamyjpl | NORMAL | 2020-01-19T04:04:56.950501+00:00 | 2020-01-19T04:15:14.444996+00:00 | 648 | false | ```java\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n if (ranges == null || ranges.length == 0 || n <= 0 || ranges.length != n + 1) return -1;\n Queue<int[]> pq = new PriorityQueue<>((e1, e2) -> Integer.compare(e1[0], e2[0]));\n for (int i = 0; i < ranges.length; i++) {\n int[] range = {Math.max(0, i - ranges[i]), Math.min(n, i + ranges[i])};\n pq.offer(range);\n }\n int count = 1;\n int start = 0, end = 0;\n while (!pq.isEmpty()) {\n int[] cur = pq.poll();\n if (cur[0] <= start) {\n end = Math.max(end, cur[1]);\n if (end == n) return count;\n } else {\n if (end < cur[0]) return -1;\n\t\t\t\tcount++;\n start = end;\n end = cur[1];\n }\n }\n return -1;\n }\n}\n``` | 3 | 0 | ['Greedy', 'Heap (Priority Queue)', 'Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Python heap based solution | python-heap-based-solution-by-cubicon-absj | \ndef minTaps(self, n: int, ranges: List[int]) -> int:\n opens, closes, closed = [[] for _ in range(n)], [[] for _ in range(n)], set()\n for i in | Cubicon | NORMAL | 2020-01-19T04:02:15.285445+00:00 | 2020-01-19T04:02:15.285485+00:00 | 238 | false | ```\ndef minTaps(self, n: int, ranges: List[int]) -> int:\n opens, closes, closed = [[] for _ in range(n)], [[] for _ in range(n)], set()\n for i in range(len(ranges)):\n idx = 0\n if i - ranges[i] > 0:\n idx = i - ranges[i] \n if idx < len(opens):\n opens[idx].append(i)\n if i + ranges[i] < n:\n closes[i + ranges[i]].append(i)\n heap, cur_open_tap, res = [], None, 0\n for i in range(n):\n for op in opens[i]:\n heappush(heap, [-(op + ranges[op]), op])\n for cl in closes[i]:\n closed.add(cl)\n if cl == cur_open_tap:\n cur_open_tap = None\n while cur_open_tap is None:\n if not heap:\n return -1\n if heap[0][1] in closed:\n heappop(heap)\n else:\n cur_open_tap = heap[0][1]\n res += 1\n return res\n``` | 3 | 0 | [] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Best C++ Solution || Dynamic Programming || Bottom Up | best-c-solution-dynamic-programming-bott-rxuf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ravikumar50 | NORMAL | 2023-10-28T07:42:49.643359+00:00 | 2023-10-28T07:42:49.643384+00:00 | 149 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int minTaps(int n, vector<int>& arr) {\n\n \n vector<int> dp(n+1,INT_MAX-10);\n\n dp[0] = 0;\n\n\n for(int i=0; i<=n; i++){\n int st = max(0,i-arr[i]);\n int end = min(n,i+arr[i]);\n\n int ans = INT_MAX;\n\n for(int j=st; j<=end; j++){\n ans = min(ans,dp[j]);\n }\n\n dp[end] = min(ans+1,dp[end]);\n }\n\n if(dp[n]==INT_MAX-10) return -1;\n else return dp[n];\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | C++ || BFS || Jump Game -> Shortest distance from 0 to N | c-bfs-jump-game-shortest-distance-from-0-cflj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Anmol_Singh098 | NORMAL | 2023-09-01T16:43:38.984943+00:00 | 2023-09-01T16:44:01.811619+00:00 | 137 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(100*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(100*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int bfs(int n,vector<vector<int>> &adj){\n vector<int> dist(n+1,1e9);\n queue<pair<int,int>> q;\n q.push({0,0});\n dist[0]=0;\n while(!q.empty()){\n int curr = (q.front()).first;\n int dis = (q.front()).second;\n q.pop();\n for(auto neg : adj[curr]){\n if(dist[neg]<=dis+1) continue;\n dist[neg] = dis+1;\n q.push({neg,dist[neg]}); \n }\n }\n\n return dist[n]==1e9 ? -1 : dist[n];\n }\n int minTaps(int n, vector<int>& range) {\n vector<pair<int,int>> jump;\n vector<vector<int>> adj(n+1);\n for(int i=0;i<=n;i++){\n int lef = max(0,i-range[i]);\n int rig =min(i+range[i],n);\n jump.push_back({lef,rig});\n }\n \n for(int t=0;t<=n;t++){\n int start = jump[t].first;\n int end = jump[t].second;\n\n for(int k=start+1;k<=end;k++){\n adj[start].push_back(k);\n }\n }\n\n return bfs(n,adj);\n }\n};\n``` | 2 | 0 | ['Breadth-First Search', 'Graph', 'C++'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | Java Easy Solution with comments! | java-easy-solution-with-comments-by-kris-fftg | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | KrishnaaV | NORMAL | 2023-08-31T19:48:19.107040+00:00 | 2023-08-31T19:48:19.107061+00:00 | 59 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minTaps(int n, int[] ranges) {\n // minTapsOpen is used to find total number of taps to keep open to cover the garden\n int minTapsOpen = 0;\n // min and max variables are used to find a tap that covers min and max distance\n int min = 0;\n int max = 0;\n\n // we have to scan until max is less than n i.e., length of the garden\n while(max < n) {\n\n // scanning the ranges to find max distance a tap can cover\n for(int i = 0; i < ranges.length; i++) {\n \n // it was mentioned in the question that a tap can cover the area\n // [i - ranges[i], i + ranges[i]] if it was open\n if(i - ranges[i] <= min && i + ranges[i] > max) {\n // if this condition is satisfied then we update our max with i + ranges[i]\n max = i + ranges[i];\n }\n }\n \n // edge case\n // after first iteration, if still the min and max variables are equal\n // then we return -1\n if(min == max)\n return -1;\n // else we increment minTapsOpen and update our min with max\n // as the max will become the new minimum\n minTapsOpen++;\n min = max;\n\n }\n\n return minTapsOpen;\n \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
minimum-number-of-taps-to-open-to-water-a-garden | using Intervals | using-intervals-by-tanya-1109-6g2i | Intuition\nThis Problem can be solved using intervals and sorting\n\n# Approach\n\n1. An intervals list is created to store the intervals that each tap can cove | Tanya-1109 | NORMAL | 2023-08-31T19:48:16.017353+00:00 | 2023-08-31T19:48:16.017378+00:00 | 10 | false | # Intuition\nThis Problem can be solved using intervals and sorting\n\n# Approach\n\n1. An `intervals` list is created to store the intervals that each tap can cover. The interval for each tap is calculated as `[max(0, i - ranges[i]), min(n, i + ranges[i])]`, ensuring that it doesn\'t exceed the boundaries of the garden.\n\n2. The `intervals` list is sorted based on the left endpoint of each interval. This is important because we will iterate through the intervals in order.\n\n3. The `end`, `farthest`, and `count` variables are initialized to keep track of the current endpoint reached by taps, the rightmost endpoint reached so far, and the count of taps used, respectively.\n\n4. A loop is used to iterate through the intervals. The condition `while farthest < n` ensures that we continue adding taps until we cover the entire garden.\n\n5. Within the loop, another loop iterates through the intervals until the left endpoint of the interval is less than or equal to the current `end`. This loop simulates adding taps to cover the garden.\n\n6. While iterating through intervals, we update the `farthest` variable with the maximum right endpoint of the current interval.\n\n7. If `farthest` becomes equal to `end`, it means we cannot progress further with the current set of taps, and thus, it\'s not possible to cover the entire garden. In this case, we return -1.\n\n8. Otherwise, we update the `end` with the value of `farthest` and increment the `count` variable, indicating that we\'ve used a tap.\n\n9. Finally, we return the `count`, which represents the minimum number of taps required to water the entire garden.\n\n\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n intervals = []\n\n for i in range(len(ranges)):\n interval = [max(0, i - ranges[i]), min(n, i + ranges[i])]\n intervals.append(interval)\n\n intervals.sort(key=lambda x: x[0]) # Sort intervals based on the left endpoint\n\n end, farthest, count = 0, 0, 0\n i = 0\n\n while farthest < n:\n while i <= n and intervals[i][0] <= end:\n farthest = max(farthest, intervals[i][1])\n i += 1\n if farthest == end:\n return -1\n end = farthest\n count += 1\n\n return count\n\n\n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 2 | 0 | ['Array', 'Python3'] | 0 |
first-letter-to-appear-twice | Java 5-line solution👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍👍 | java-5-line-solution-by-ouyang2021-onwc | Upvote please, if it helps. \nThank you!\n\npublic char repeatedCharacter(String s) {\n Set<Character> set = new HashSet();\n for (char c : s.toC | Ouyang2021 | NORMAL | 2022-07-27T20:00:44.912997+00:00 | 2022-07-27T21:05:05.521662+00:00 | 4,626 | false | Upvote please, if it helps. \nThank you!\n```\npublic char repeatedCharacter(String s) {\n Set<Character> set = new HashSet();\n for (char c : s.toCharArray()) \n if (!set.add(c)) \n return c;\n\t\t\t\t\n return \'a\';// can\'t reach to this line, because there must be a letter appearing TWICE\n }\n``` | 42 | 1 | ['Java'] | 10 |
first-letter-to-appear-twice | CPP | Easy | O(1) Time | O(26) Space | cpp-easy-o1-time-o26-space-by-amirkpatna-v74e | \nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n vector<int> v(26);\n for(char c:s){\n v[c-\'a\']++;\n | amirkpatna | NORMAL | 2022-07-24T04:04:22.887551+00:00 | 2022-08-17T01:55:37.289533+00:00 | 5,161 | false | ```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n vector<int> v(26);\n for(char c:s){\n v[c-\'a\']++;\n if(v[c-\'a\']>1)return c;\n }\n return \'a\';\n }\n};\n```\n\n**Update** :\n```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n vector<bool> v(26);\n for(char c:s){\n if(v[c-\'a\'])return c;\n\t\t\tv[c-\'a\']=true;\n }\n return \'a\';\n }\n};\n``` | 28 | 0 | ['C++'] | 11 |
first-letter-to-appear-twice | ✅Python || Map || Easy Approach | python-map-easy-approach-by-chuhonghao01-kopd | Algorithm:\n(1) use setS to store the letter have ever seen;\n(2) one pass the input string:\n(3) if x is already in setS:\n\t\tx is what we need (it is the fir | chuhonghao01 | NORMAL | 2022-07-24T04:02:41.850260+00:00 | 2022-08-23T02:22:29.027617+00:00 | 3,544 | false | Algorithm:\n(1) use setS to store the letter have ever seen;\n(2) one pass the input string:\n(3) if x is already in setS:\n\t\tx is what we need (it is the first occurrence twice).\n(4) else (x is not in setS):\n\t\twe put the x into the setS to store it.\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n \n setS = set()\n\n for x in s:\n if x in setS:\n return x\n else:\n setS.add(x)\n \n``` | 21 | 0 | ['Python', 'Python3'] | 4 |
first-letter-to-appear-twice | ✅C++ | ✅Simple Solution | ✅Use Hashmap | c-simple-solution-use-hashmap-by-yash2ar-75qa | \nclass Solution \n{\npublic:\n char repeatedCharacter(string s) \n {\n unordered_map<char, int> mp; //for storing occurrences of char\n \n | Yash2arma | NORMAL | 2022-07-24T04:03:58.767415+00:00 | 2022-07-24T04:03:58.767507+00:00 | 3,101 | false | ```\nclass Solution \n{\npublic:\n char repeatedCharacter(string s) \n {\n unordered_map<char, int> mp; //for storing occurrences of char\n \n char ans;\n for(auto it:s)\n {\n if(mp.find(it) != mp.end()) //any char which comes twice first will be the ans; \n {\n ans = it;\n break;\n }\n mp[it]++; //increase the count of char\n }\n return ans;\n }\n};\n``` | 18 | 1 | ['String', 'C', 'C++'] | 2 |
first-letter-to-appear-twice | Return When First seen | return-when-first-seen-by-xxvvpp-vp0z | C++\n char repeatedCharacter(string s) {\n int cnt[26]{};\n for(char ch:s) if(++cnt[ch-\'a\']==2) return ch;\n return 0;\n }\n \n# | xxvvpp | NORMAL | 2022-07-24T04:01:44.160667+00:00 | 2022-07-24T04:01:44.160696+00:00 | 2,581 | false | # C++\n char repeatedCharacter(string s) {\n int cnt[26]{};\n for(char ch:s) if(++cnt[ch-\'a\']==2) return ch;\n return 0;\n }\n \n# Java\n public char repeatedCharacter(String s) {\n int cnt[]= new int[26];\n for(char ch:s.toCharArray()) if(++cnt[ch-\'a\']==2) return ch;\n return \'a\';\n }\nTime - O(N)\nSpace - O(26)= O(1) | 14 | 0 | ['C', 'Java'] | 6 |
first-letter-to-appear-twice | easy solution in c++ using unordered_map | easy-solution-in-c-using-unordered_map-b-ztuc | \nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n int n=s.size();\n int i;\n unordered_map<char,int>map;\n for(i | vinaykumar333j | NORMAL | 2024-10-22T07:49:45.898924+00:00 | 2024-10-22T07:50:07.041234+00:00 | 341 | false | ```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n int n=s.size();\n int i;\n unordered_map<char,int>map;\n for(i=0;i<n;i++){\n if(map.find(s[i])!=map.end()){\n return s[i];\n }\n map[s[i]];\n }\n return \'0\';\n }\n};\n``` | 12 | 0 | ['C'] | 0 |
first-letter-to-appear-twice | Count Chars | count-chars-by-votrubac-m9f7 | C++\ncpp\nchar repeatedCharacter(string s) {\n int seen[128] = {}, i = 0;\n for (i = 0; i < s.size() && ++seen[s[i]] < 2; ++i);\n return s[i];\n}\n | votrubac | NORMAL | 2022-07-24T04:01:57.919638+00:00 | 2022-07-24T04:01:57.919668+00:00 | 1,573 | false | **C++**\n```cpp\nchar repeatedCharacter(string s) {\n int seen[128] = {}, i = 0;\n for (i = 0; i < s.size() && ++seen[s[i]] < 2; ++i);\n return s[i];\n}\n``` | 12 | 0 | [] | 5 |
first-letter-to-appear-twice | C++ solutions | c-solutions-by-infox_92-5gu2 | \nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n vector<bool> v(26);\n for(char c:s){\n if(v[c-\'a\'])return c;\n\ | Infox_92 | NORMAL | 2022-11-12T06:13:54.907395+00:00 | 2022-11-12T06:13:54.907440+00:00 | 1,159 | false | ```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n vector<bool> v(26);\n for(char c:s){\n if(v[c-\'a\'])return c;\n\t\t\tv[c-\'a\']=true;\n }\n return \'a\';\n }\n};\n``` | 10 | 0 | ['C', 'C++'] | 0 |
first-letter-to-appear-twice | JavaScript Set less and faster than 85% | javascript-set-less-and-faster-than-85-b-x3rj | \nconst repeatedCharacter = s => {\n const set = new Set();\n \n for (let i = 0; i < s.length; i += 1) {\n const currentLetter = s[i]\n i | seredulichka | NORMAL | 2022-08-24T21:59:55.663403+00:00 | 2022-08-24T21:59:55.663435+00:00 | 1,311 | false | ```\nconst repeatedCharacter = s => {\n const set = new Set();\n \n for (let i = 0; i < s.length; i += 1) {\n const currentLetter = s[i]\n if(set.has(currentLetter)) {\n return currentLetter \n }\n set.add(currentLetter);\n }\n};\n``` | 10 | 0 | ['JavaScript'] | 0 |
first-letter-to-appear-twice | Python Simple Code (Hash Table , Set, List) | python-simple-code-hash-table-set-list-b-xy2y | If you got help from this,... Plz Upvote .. it encourage me\n\n# Code\n> # HashTable\n\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n | vvivekyadav | NORMAL | 2023-10-05T17:50:37.199659+00:00 | 2023-10-05T17:52:38.067488+00:00 | 292 | false | **If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n> # HashTable\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n d = {}\n for char in s:\n if char in d:\n return char\n else:\n d[char] = 1\n\n \n```\n\n> # Set\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n seen = set()\n for c in s:\n if c in seen:\n return c\n seen.add(c)\n\n\n```\n> # List\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n l = []\n for char in s:\n if char in l:\n return char\n else:\n l.append(char)\n\n\n``` | 8 | 0 | ['Hash Table', 'String', 'Counting', 'Python', 'Python3'] | 0 |
first-letter-to-appear-twice | Here Simple✔ and Easy ✌Solution With Clear Explanation|| 100% beats✨ | here-simple-and-easy-solution-with-clear-0vvd | Intuition\nHere im Initializing an array count of 26 and set the values 0\'s for all index and traverse the string and adding the char in the array by index and | sanjuzzz28 | NORMAL | 2024-10-14T17:06:11.948370+00:00 | 2024-10-14T17:09:55.591107+00:00 | 341 | false | # Intuition\nHere im Initializing an array count of 26 and set the values 0\'s for all index and traverse the string and adding the char in the array by index and if the index is equal to two return the character of the first letter appear twice string.\n\n# Approach\n##### ==>Character Count Array Initialization:\nc[26] itconsists of a-z letter.The index 0 corresponds to \'a\',index 1 corresponds to \'b\',and so on up to index 25 for \'z\'.\n\n##### ==>Loop Through the String: traverse the entire string\n\n##### ==>Increment Count for Each Character:\n##### c[(int)s[i]-97]++ - counting the character\n For example, if s[i] is \'a\', the index will be 0, for \'b\' it will be 1,and so forth.It then increments the count of that character in the array c.and increment the count.\n\n##### ==>Check for Duplicates:\n if c[(int)s[i]-97]==2 it have duplicate return the character.\n\n##### ==>else null.\n\n# Complexity\n- Time complexity:O(n)\n- Space complexity:O(1)\n\n# Code\n```c []\nchar repeatedCharacter(char* s) {\n int c[26]={0};\n for(int i=0;s[i];i++){\n c[(int)s[i]-97]++;\n if(c[(int)s[i]-97]==2){\n return s[i];\n }\n }\n return \'\\0\';\n} \n``` | 7 | 0 | ['String', 'C', 'C++'] | 0 |
first-letter-to-appear-twice | ✅C++ || ✅Simple || ✅Commented || ✅Easy to Understand | c-simple-commented-easy-to-understand-by-8apr | \nclass Solution {\npublic:\n char repeatedCharacter(string s) \n {\n map<char,int> mp; // for storing the frequency of char\n | mayanksamadhiya12345 | NORMAL | 2022-07-24T04:00:50.338457+00:00 | 2022-07-24T04:17:17.858992+00:00 | 896 | false | ```\nclass Solution {\npublic:\n char repeatedCharacter(string s) \n {\n map<char,int> mp; // for storing the frequency of char\n \n for(auto i: s)\n {\n // if we found that this char is already present menas it is our ans return it\n if(mp[i]==1)\n return i;\n \n // if it ocuurs first time then increase the frequency by 1\n else if(mp[i]==0)\n mp[i]++;\n }\n \n // if we do not have any char with frequency 2 then return 0\n return 0;\n }\n};\n``` | 7 | 0 | [] | 0 |
first-letter-to-appear-twice | Finding the First Repeated Character in a String Using Set | finding-the-first-repeated-character-in-aklmt | IntuitionApproachTo solve the problem of finding the first repeated character in a string, the idea is to keep track of characters that have already been seen. | lalith_chandra | NORMAL | 2025-02-23T03:58:55.454095+00:00 | 2025-02-23T03:58:55.454095+00:00 | 201 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
To solve the problem of finding the first repeated character in a string, the idea is to keep track of characters that have already been seen. As soon as a character is encountered again, return it as the result.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
1. Set for Tracking: Use a set to store characters as we iterate through the string.
2. Iteration: For each character in the string, check if it is already present in the set.
a. If the character is found in the set, return it as the first repeated character.
b. If not, insert the character into the set and continue.
3. Return: If no repeated character is found (though the problem implies there will be one), return an empty character as a default.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1. Space complexity:
O(k), where k is the number of distinct characters in the string, as we store characters in the set.
2. Time complexity:
O(n), where n is the length of the string. We iterate through the string once, and set operations (insert and find) take average O(1) time.
# Code
```cpp []
class Solution {
public:
char repeatedCharacter(string s) {
set<char> st;
for(int i=0;i<s.size();i++)
{
if(!st.empty() && st.find(s[i])!=st.end())
{
return s[i];
}
else
{
st.insert(s[i]);
}
}
return ' ';
}
};
``` | 6 | 0 | ['C++'] | 1 |
first-letter-to-appear-twice | C++ ✅ Easy to Understand O(n) Solution 🔥 | c-easy-to-understand-on-solution-by-_sxr-fbln | Intuition\nThe given code aims to find the first character in the string that appears twice. It uses an unordered map to keep track of the frequency of each cha | _sxrthakk | NORMAL | 2024-07-24T13:15:20.301985+00:00 | 2024-07-24T13:15:20.302019+00:00 | 469 | false | # Intuition\nThe given code aims to find the first character in the string that appears twice. It uses an unordered map to keep track of the frequency of each character as it iterates through the string. As soon as it detects a character that has appeared twice, it immediately returns that character.\n\n# Approach\n1. **Initialize the Map :** Create an unordered map m to store the frequency of each character in the string s.\n\n2. **Iterate through the String :** Traverse each character c in the string s.\n\n3. **Update Frequencies :** For each character c, increment its count in the map m.\n\n4. **Check for Repetition :** After updating the count, check if the count of c is equal to 2. If true, return the character c immediately as it is the first character to appear twice.\n\n# Complexity\n- **Time complexity :** O(n)\n\n- **Space complexity :** O(n)\n\n# Code\n```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n unordered_map<char,int> m;\n for(char c : s){\n m[c]++;\n if(m[c]==2) return c;\n }\n return \' \';\n }\n};\n``` | 6 | 0 | ['C++'] | 0 |
first-letter-to-appear-twice | bit manipulation | O(n) time | O(1) space | no Map, hash, array | bit-manipulation-on-time-o1-space-no-map-fml0 | Instead of allocating 26 boolean array, use 26 bits as flag. This reduces many spaces from O(26) to O(1).\n\n### Python\npython\nclass Solution:\n def repeat | wf9a5m75 | NORMAL | 2022-08-16T01:20:48.378578+00:00 | 2022-08-16T01:25:26.790742+00:00 | 331 | false | Instead of allocating 26 boolean array, use `26 bits` as flag. This reduces many spaces from `O(26)` to `O(1)`.\n\n### Python\n```python\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n appear = 0\n \n ordA = ord("a")\n for char in s:\n mask = 1 << (ord(char) - ordA)\n if ((appear & mask) != 0):\n return char\n appear |= mask\n```\n\n### Java\n```Java\nclass Solution {\n public char repeatedCharacter(String s) {\n int appear = 0;\n \n int mask = 0;\n for (int i = 0; i < s.length(); i++) {\n mask = 1 << (s.charAt(i) - \'a\');\n if ((appear & mask) != 0) {\n return s.charAt(i);\n }\n appear |= mask;\n }\n return \'-\';\n }\n}\n``` | 6 | 0 | ['Bit Manipulation', 'Python', 'Java'] | 1 |
first-letter-to-appear-twice | ✅💯Beats 100.00% of users || Best solution in C++/C#/C || Beginner friendly👍🤝 | beats-10000-of-users-best-solution-in-cc-egbn | PLEASE DO UPVOTE\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe code finds the first repeated character in a given string b | anand18402 | NORMAL | 2024-01-20T09:29:31.289168+00:00 | 2024-01-20T09:29:31.289196+00:00 | 389 | false | # PLEASE DO UPVOTE\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code finds the first repeated character in a given string by maintaining a count of each character using an unordered_map. It iterates through the string and returns the first character with a count of 2, indicating repetition.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, create a variable named ans to store the letter\n2. Then Create an unordered map in which you will store the count of each letter until you find a letter that appears twice\n3. Use a loop to iterate through each letter and increment the number of occurrences in the map\n4. When you find the first letter to appear twice, store it in the variable ans and use the break function to stop the loop\n5. Then return the ans\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n int n = s.size();\n char ans;\n unordered_map<char, int> count;\n for(int i=0; i<n; i++){\n count[s[i]]++;\n if(count[s[i]]==2){\n ans = s[i];\n break;\n }\n }\n return ans;\n }\n};\n```\n```C# []\npublic class Solution {\n public char RepeatedCharacter(string s) {\n int n = s.Length;\n char ans = \'\\0\';\n Dictionary<char, int> count = new Dictionary<char, int>();\n\n for (int i = 0; i < n; i++) {\n if (!count.ContainsKey(s[i])) {\n count[s[i]] = 1;\n } else {\n ans = s[i];\n break;\n }\n }\n\n return ans;\n }\n}\n```\n```C []\nchar repeatedCharacter(char *s) {\n int n = strlen(s);\n char ans = \'\\0\';\n\n int *count = (int *)malloc(256 * sizeof(int)); // Assuming ASCII characters\n\n for (int i = 0; i < 256; i++) {\n count[i] = 0;\n }\n\n for (int i = 0; i < n; i++) {\n count[(int)s[i]]++;\n if (count[(int)s[i]] == 2) {\n ans = s[i];\n break;\n }\n }\n\n free(count);\n\n return ans;\n}\n``` | 5 | 0 | ['String', 'Ordered Map', 'C', 'String Matching', 'C++', 'C#'] | 1 |
first-letter-to-appear-twice | O(n) || C++||Beats 100% ||Easy 4 line code ||counting || Simple Solution ||With Explanation | on-cbeats-100-easy-4-line-code-counting-tk09w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n Describe your approach to solving the problem. \ncount the frequency o | nikhil_2002_singh | NORMAL | 2023-05-16T12:20:17.287079+00:00 | 2023-05-16T16:32:46.531913+00:00 | 65 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncount the frequency of ech element \nwhen the frequeny becomes equals to 2 return the character.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n char repeatedCharacter(string s) {\n \n int n=s.length();\n vector<int>a(26,0);\n int i;\n for( i=0;i<n;i++)\n {\n a[s[i]-\'a\']++;\n if(a[s[i]-\'a\']==2)\n {\n return s[i];\n }\n }\n return s[i]; \n }\n};\n``` | 5 | 0 | ['Hash Table', 'String', 'Counting', 'C++'] | 0 |
first-letter-to-appear-twice | Easy Java Solution using HashSet | easy-java-solution-using-hashset-by-abhi-l06y | \nclass Solution {\n public char repeatedCharacter(String s) {\n HashSet<Character> set = new HashSet<>();//Create a set of characters\n for(in | Abhinav_0561 | NORMAL | 2022-10-10T03:43:12.567367+00:00 | 2022-10-10T03:43:12.567395+00:00 | 2,525 | false | ```\nclass Solution {\n public char repeatedCharacter(String s) {\n HashSet<Character> set = new HashSet<>();//Create a set of characters\n for(int i = 0 ; i < s.length() ; i++){\n if(set.contains(s.charAt(i))) return s.charAt(i);//If the set already contains the current character, then it is the required ans\n set.add(s.charAt(i));\n }\n return \'a\';//As it is given in the question that there is at least one letter that appears twice, therefore it is certain that the ans will be found before we reach this statement. So, just adding any random return statement so that there is no error in the code.\n }\n}\n```\nIt\'s time complexity is O(n). | 5 | 0 | ['Java'] | 1 |
first-letter-to-appear-twice | C++ || Simple Solution || O(26) Space || Easy | c-simple-solution-o26-space-easy-by-sura-dseo | C++ Code:\n\nclass Solution {\npublic:\n //using O(26) space \n char repeatedCharacter(string s) {\n vector<int> cnt(26,0);\n \n char | suraj_jha989 | NORMAL | 2022-07-25T02:47:08.956331+00:00 | 2022-07-25T02:48:28.902837+00:00 | 218 | false | # C++ Code:\n```\nclass Solution {\npublic:\n //using O(26) space \n char repeatedCharacter(string s) {\n vector<int> cnt(26,0);\n \n char ans;\n for(char ch: s){\n if(cnt[ch-\'a\'] == 1){\n ans = ch;\n break;\n }\n cnt[ch-\'a\']++;\n }\n \n return ans;\n }\n};\n``` | 5 | 0 | ['Array', 'C', 'C++'] | 0 |
first-letter-to-appear-twice | Count and check | Easy and simple | count-and-check-easy-and-simple-by-nadar-g49j | Code is self explanatory\n\n\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n occurences = defaultdict(int)\n for char in s:\n | nadaralp | NORMAL | 2022-07-24T04:01:46.976658+00:00 | 2022-07-24T04:01:46.976688+00:00 | 921 | false | Code is self explanatory\n\n```\nclass Solution:\n def repeatedCharacter(self, s: str) -> str:\n occurences = defaultdict(int)\n for char in s:\n occurences[char] += 1\n if occurences[char] == 2:\n return char\n``` | 5 | 0 | ['Python'] | 0 |
first-letter-to-appear-twice | Simple Java Code ☠️ | simple-java-code-by-abhinandannaik1717-6vw8 | \n# Code\n\nclass Solution {\n public char repeatedCharacter(String s) {\n int n = s.length();\n HashSet<Character> set = new HashSet<>();\n | abhinandannaik1717 | NORMAL | 2024-07-18T18:50:55.893254+00:00 | 2024-07-18T18:50:55.893285+00:00 | 423 | false | \n# Code\n```\nclass Solution {\n public char repeatedCharacter(String s) {\n int n = s.length();\n HashSet<Character> set = new HashSet<>();\n for(int i=0;i<n;i++){\n if(set.contains(s.charAt(i))){\n return s.charAt(i);\n }\n set.add(s.charAt(i));\n }\n return s.charAt(0);\n }\n}\n```\n\n### Explanation\n\nWe created a Hashset of characters and then run a for loop from start to the end of the string and for each iteration we check whether the character that the i is pointing to is already present in the set and if it is present we return that particular character and if it is not we add that to the set. So, if it is repeated then only will it be present in the set.\n\n### Time Complexity : O(n)\n### Space Complexity : O(n)\n | 4 | 0 | ['Hash Table', 'String', 'Java'] | 1 |
first-letter-to-appear-twice | Easy Solution Using HashMap [ JAVA ] [ 100% ] [ 0ms ] | easy-solution-using-hashmap-java-100-0ms-fy35 | Approach\n1. Initialize a HashMap st to store characters and their counts.\n2. Iterate through each character in the input string s.\n3. Check if the character | RajarshiMitra | NORMAL | 2024-04-20T10:56:51.376680+00:00 | 2024-06-16T08:32:09.217304+00:00 | 71 | false | # Approach\n1. Initialize a HashMap `st` to store characters and their counts.\n2. Iterate through each character in the input string `s`.\n3. Check if the character is already present in the HashMap:\n - If it is present, return the character as it\'s the first repeated character.\n - If it\'s not present, add it to the HashMap with a count of 1.\n4. If no repeated characters are found, return a space character.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public char repeatedCharacter(String s) {\n HashMap<Character, Integer> st=new HashMap<>();\n for(int i=0; i<s.length(); i++){\n if(st.containsKey(s.charAt(i))){\n return s.charAt(i);\n }\n else{\n st.put(s.charAt(i),1);\n }\n }\n return \' \';\n }\n}\n```\n\n\n | 4 | 0 | ['Java'] | 0 |
first-letter-to-appear-twice | 100% Beginners Friendly | 100-beginners-friendly-by-bhaskarkumar07-74b5 | \n# Approach\n Describe your approach to solving the problem. \n as the hashmap value of the key went to 2 return the char\n\n# Complexity\n- Time comp | bhaskarkumar07 | NORMAL | 2023-04-18T18:55:48.574796+00:00 | 2023-04-18T18:55:48.574851+00:00 | 655 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\n as the hashmap value of the key went to 2 return the char\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public char repeatedCharacter(String s) {\n HashMap<Character, Integer> hm= new HashMap<>();\n\n for(int i=0;i<s.length();i++){\n //if present\n if(hm.containsKey(s.charAt(i))){\n return s.charAt(i);\n }else{\n hm.put(s.charAt(i), 1);\n }\n }\n return \'1\';\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
first-letter-to-appear-twice | Solution in C++ | solution-in-c-by-ashish_madhup-vdf0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ashish_madhup | NORMAL | 2023-04-18T17:48:29.482312+00:00 | 2023-04-18T17:48:29.482363+00:00 | 412 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n char repeatedCharacter(string s) \n {\n unordered_map<char,int>m;\n for(int i=0;i<s.size();i++)\n {\n m[s[i]]++;\n if(m[s[i]]==2) return s[i];\n }\nreturn 1;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.