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-amount-of-time-to-collect-garbage | Best Java Solution || Beats 100% | best-java-solution-beats-100-by-ravikuma-cyuz | 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-11-20T02:56:03.023507+00:00 | 2023-11-20T02:56:03.023537+00:00 | 239 | 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 boolean hasG = false, hasP = false, hasM = false;\n\n public int garbageCollection(String[] garbage, int[] travel) {\n int n = garbage.length;\n int ans = 0;\n for (int i = 0; i < n - 1; i++) {\n ans += 3 * travel[i];\n }\n for (String s : garbage) {\n ans += s.length();\n }\n for (int i = n - 1; i > 0; i--) {\n if (!garbage[i].contains("G")) {\n ans -= travel[i - 1];\n } else {\n break;\n }\n }\n for (int i = n - 1; i > 0; i--) {\n if (!garbage[i].contains("P")) {\n ans -= travel[i - 1];\n } else {\n break;\n }\n }\n for (int i = n - 1; i > 0; i--) {\n if (!garbage[i].contains("M")) {\n ans -= travel[i - 1];\n } else {\n break;\n }\n }\n return ans;\n }\n}\n``` | 3 | 0 | ['Java'] | 3 |
minimum-amount-of-time-to-collect-garbage | ✅ 100% || 🚀 Greedy Approach || | 100-greedy-approach-by-lazy_coder007-l6mn | \n\n# C++ Result:\n\n\n# Python Result:\n\n\n# Java Result:\n\n\n# Intuition:\nHere we are given a list of garbage and a list of travel times. We need to find t | Lazy_Coder007 | NORMAL | 2023-11-20T00:31:08.903910+00:00 | 2023-11-20T00:31:08.903941+00:00 | 943 | false | \n\n# C++ Result:\n\n\n# Python Result:\n\n\n# Java Result:\n\n\n# Intuition:\n**Here we are given a list of garbage and a list of travel times. We need to find the minimum time to pick up all the garbage. We can do this by iterating from the end of the garbage array and checking if the current house has any of the garbage. If it does, we add the travel time to the garbage. If all the garbage has been found, we break and return the sum of the garbage and the travel time.**\n\n# Approach: Using a greedy approach\n1. Iterate from the end of the garbage array\n2. Check if the current house has any of the garbage\n3. If it does, add the travel time to the garbage\n4. If all the garbage has been found, break\n5. Return the sum of the garbage and the travel time\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## UpVote\u2B06\uFE0F If this helps you:)\n\n# Code\n``` Python []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n ans = 0\n\n n = len(garbage)\n\n m,p,g = False,False,False\n for i in range(n-1,-1,-1):\n if not g and "G" in garbage[i]:\n g=True\n ans+=sum(travel[:i])\n if not m and "M" in garbage[i]:\n m=True\n ans+=sum(travel[:i])\n if not p and "P" in garbage[i]:\n p=True\n ans+=sum(travel[:i])\n if all([m,p,g]):\n break\n\n return len("".join(garbage))+ans\n```\n``` C++ []\n#include <iostream>\n#include <vector>\n#include <numeric> // Include the numeric header for std::accumulate\n\nclass Solution {\npublic:\n int garbageCollection(std::vector<std::string>& garbage, std::vector<int>& travel) {\n int ans = 0;\n int n = garbage.size();\n bool m = false, p = false, g = false;\n for (int i = n - 1; i >= 0; --i) {\n if (!g && garbage[i].find(\'G\') != std::string::npos) {\n g = true;\n ans += std::accumulate(travel.begin(), travel.begin() + i, 0);\n }\n if (!m && garbage[i].find(\'M\') != std::string::npos) {\n m = true;\n ans += std::accumulate(travel.begin(), travel.begin() + i, 0);\n }\n if (!p && garbage[i].find(\'P\') != std::string::npos) {\n p = true;\n ans += std::accumulate(travel.begin(), travel.begin() + i, 0);\n }\n if (m && p && g) {\n break;\n }\n }\n return ans + std::accumulate(garbage.begin(), garbage.end(), 0, [](int sum, const std::string& str) {\n return sum + str.size();\n });\n }\n};\n```\n``` Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans = 0;\n int n = garbage.length;\n boolean m = false, p = false, g = false;\n\n for (int i = n - 1; i >= 0; i--) {\n if (!g && garbage[i].contains("G")) {\n g = true;\n ans += Arrays.stream(travel, 0, i).sum();\n }\n if (!m && garbage[i].contains("M")) {\n m = true;\n ans += Arrays.stream(travel, 0, i).sum();\n }\n if (!p && garbage[i].contains("P")) {\n p = true;\n ans += Arrays.stream(travel, 0, i).sum();\n }\n if (m && p && g) {\n break;\n }\n }\n\n return Arrays.stream(garbage).mapToInt(String::length).sum() + ans;\n }\n}\n```\n | 3 | 0 | ['Array', 'Greedy', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | Python O(n) | python-on-by-shubhlaxh_porwal-v9d9 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code is implementing a garbage collection algorithm that calculates the total dista | shubhlaxh_porwal | NORMAL | 2023-06-20T07:08:59.697128+00:00 | 2023-06-20T07:08:59.697161+00:00 | 54 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code is implementing a garbage collection algorithm that calculates the total distance traveled by a garbage truck based on the type of garbage collected at each house and the travel distances between consecutive houses. The types of garbage are \'G\', \'P\', and \'M\', representing different categories of waste. The algorithm calculates the distance traveled for each type of garbage and returns the sum of these distances.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code defines a function fn(Type) that takes a parameter Type representing the type of garbage. This function iterates over the garbage list, which contains the type of garbage at each house. For each house, it counts the number of times the specified Type occurs in the garbage string.\n\nIf the count is not zero (indicating that the current house has the specified Type of garbage), it calculates the distance traveled by summing the values in the travel list from the current position (curr) to the current house (number). It adds this distance to the total variable. Then, it updates curr to the current house and adds the count of the Type to the total variable.\n\nFinally, the algorithm calls fn for each type of garbage (\'G\', \'P\', and \'M\'), and sums the returned distances to obtain the total distance traveled by the garbage truck.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity: The algorithm iterates over the garbage list once and performs string counting operations for each house. The sum of the distances in the travel list is calculated for each house with non-zero count. Therefore, the overall time complexity is O(n), where n is the length of the garbage list\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity: The algorithm uses a constant amount of extra space, regardless of the input size. Hence, the space complexity is O(1).\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n \n def fn(Type):\n total=0\n curr=0\n for number,house in enumerate(garbage):\n times=house.count(Type)\n if times!=0:\n distance=sum(travel[curr:number])\n total+=distance\n curr=number\n total+=times\n return total\n ans=fn(\'G\')+fn(\'P\')+fn(\'M\')\n return ans\n \n``` | 3 | 0 | ['String', 'Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | Easy Java Solution || Beats 97% online submissions | easy-java-solution-beats-97-online-submi-sq1i | Code\n\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans = 0;\n \n int g = 0, m = 0, p = 0;\n | Viraj_Patil_092 | NORMAL | 2023-04-27T06:47:57.286400+00:00 | 2023-04-27T06:47:57.286443+00:00 | 489 | false | # Code\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans = 0;\n \n int g = 0, m = 0, p = 0;\n\n for(int i = garbage.length-1;i >= 0;i--){\n if(garbage[i].contains("G")){\n g = i;\n break;\n }\n }\n for(int i = garbage.length-1;i >= 0;i--){\n if(garbage[i].contains("P")){\n p = i;\n break;\n }\n }\n for(int i = garbage.length-1;i >= 0;i--){\n if(garbage[i].contains("M")){\n m = i;\n break;\n }\n }\n\n for(int i = 0;i < garbage.length;i++){\n ans += garbage[i].length();\n }\n\n for(int i = 1;i < travel.length;i++){\n travel[i] += travel[i-1];\n }\n\n if(p != 0){\n ans += travel[p-1];\n }\n if(g != 0){\n ans += travel[g-1];\n }\n if(m != 0){\n ans += travel[m-1];\n }\n\n return ans;\n }\n}\n``` | 3 | 0 | ['Array', 'String', 'Prefix Sum', 'Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | JAVA | solution in function | java-solution-in-function-by-firdavs06-j16a | 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 | Firdavs06 | NORMAL | 2023-02-26T12:04:01.232595+00:00 | 2023-02-26T12:04:01.232627+00:00 | 321 | 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 garbageCollection(String[] garbage, int[] travel) {\n return fun(garbage,\'M\',travel) + fun(garbage,\'P\',travel) + fun(garbage,\'G\',travel);\n }\n\n public int fun(String[] garbage, char c,int[] travel){\n int m = 0;\n int step = 0;\n int x = 0;\n for(int i = 0; i < garbage.length; i++){\n if(i !=0 ){\n step += travel[i-1];\n }\n for(int j = 0; j < garbage[i].length(); j++){\n if(garbage[i].charAt(j) == c){\n m += step+1;\n step = 0;\n }\n }\n }\n return m;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | [Python3] 'One-liner' || Beats 100% || O(n)/O(n)🚛 | python3-one-liner-beats-100-onon-by-gepr-8m94 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe want to know two things about our garbage collection:\n\nThe number of bins to colle | gepru | NORMAL | 2023-01-14T03:46:13.878212+00:00 | 2023-11-20T11:04:41.504265+00:00 | 636 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to know two things about our garbage collection:\n\nThe number of bins to collect (1 minute each), and the number of houses each truck must travel to in order to collect all bins of their waste type (`travel` summed up to the last house that has the truck\'s type of waste).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe number of bins can be obtained by finding the length of the string formed by joining each bin string in `garbage`.\n\nThe last house to be visited by each truck is the first element starting from the end of `garbage` that has the truck\'s type of waste [see https://stackoverflow.com/a/6890255].\n```\nnext(i for i in reversed(range(len(garbage))) if w in garbage[i])\n```\nWe want to sum the travel vector up to this point. To prevent issues when the waste type is not at any house, a single-line if-else is used.\n\nWe sum `travel` up to this index, and then sum over all waste types.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: \n return len(\'\'.join(garbage)) + sum([sum(travel[:next(i for i in reversed(range(len(garbage))) if w in garbage[i])]) if w in \'\'.join(garbage) else 0 for w in "MPG"])\n```\n | 3 | 0 | ['Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | c++ O(n*m) solution, constant space | c-onm-solution-constant-space-by-augus7-q2w1 | \n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(n * m)\n Add your time complexity here, e.g. O(n) \n\n- Space complexit | Augus7 | NORMAL | 2023-01-10T14:14:24.123411+00:00 | 2023-01-10T14:14:24.123458+00:00 | 627 | false | \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n * m)$$\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 {\npublic:\n int garbageCollection(vector<string>& gar, vector<int>& travel) {\n int sum = 0;\n bool gbool = false, pbool = false, mbool = false;\n for(auto i : gar) {\n sum += i.size();\n }\n int g = -1, m = -1, p = -1;\n for(int i=gar.size()-1;i>=0;i--) {\n for(int j=0;j<gar[i].size();j++) {\n if(gar[i][j] == \'G\' && !gbool) {\n g = i - 1;\n gbool = true;\n }\n else if(gar[i][j] == \'P\' && !pbool) {\n p = i - 1;\n pbool = true;\n }\n else if(gar[i][j] == \'M\' && !mbool) {\n m = i - 1;\n mbool = true;\n }\n }\n if(gbool && pbool && mbool) break;\n }\n for(int i=0;i<=g;i++) {\n sum += travel[i];\n }\n for(int i=0;i<=p;i++) {\n sum += travel[i];\n }\n for(int i=0;i<=m;i++) {\n sum += travel[i];\n }\n return sum;\n }\n};\n``` | 3 | 0 | ['Array', 'String', 'Prefix Sum', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Short || Clean || HashMap || Java Solution | short-clean-hashmap-java-solution-by-him-ul28 | \njava []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n Map<String,Integer> map = new HashMap();\n for(i | HimanshuBhoir | NORMAL | 2023-01-05T07:57:37.554985+00:00 | 2023-01-05T07:57:37.555047+00:00 | 554 | false | \n```java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n Map<String,Integer> map = new HashMap();\n for(int i=1; i<travel.length; i++) travel[i] += travel[i-1];\n for(int i=1; i<garbage.length; i++){\n if(garbage[i].contains("M")) map.put("M", travel[i-1]);\n if(garbage[i].contains("P")) map.put("P", travel[i-1]);\n if(garbage[i].contains("G")) map.put("G", travel[i-1]);\n }\n String s = String.join("",garbage);\n for(char c: s.toCharArray()) map.put(c+"",map.getOrDefault(c+"",0)+1);\n int mnts = 0;\n for(int val: map.values()) mnts += val;\n return mnts;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | Simulation | simulation-by-fllght-pfif | Java\njava\npublic int garbageCollection(String[] garbage, int[] travel) {\n int totalTime = 0;\n\n for (int house = 0, metal = 0, glass = 0, plas | FLlGHT | NORMAL | 2022-08-28T13:14:12.230938+00:00 | 2022-08-28T13:14:12.230977+00:00 | 117 | false | ##### *Java*\n```java\npublic int garbageCollection(String[] garbage, int[] travel) {\n int totalTime = 0;\n\n for (int house = 0, metal = 0, glass = 0, plastic = 0; house < garbage.length; ++house) {\n String currentHouse = garbage[house];\n if (currentHouse.contains("M")) {\n totalTime += (travelTime(metal, house, travel) + garbageCollectionTime(currentHouse, \'M\'));\n metal = house;\n }\n if (currentHouse.contains("G")) {\n totalTime += (travelTime(glass, house, travel) + garbageCollectionTime(currentHouse, \'G\'));\n glass = house;\n }\n if (currentHouse.contains("P")) {\n totalTime += (travelTime(plastic, house, travel) + garbageCollectionTime(currentHouse, \'P\'));\n plastic = house;\n }\n }\n\n return totalTime;\n }\n\n private int travelTime(int start, int end, int[] travel) {\n int time = 0;\n for (int stop = start; stop < end; ++stop) \n time += travel[stop];\n \n return time;\n }\n\n\n private int garbageCollectionTime(String house, Character type) {\n return (int) house.chars().filter(c -> c == type).count();\n }\n```\n\nC++\n\n```c++\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int totalTime = 0;\n\n for (int house = 0, metal = 0, glass = 0, plastic = 0; house < garbage.size(); ++house) {\n string currentHouse = garbage[house];\n if (currentHouse.find(\'M\') != string::npos) {\n totalTime += (travelTime(metal, house, travel) + garbageCollectionTime(currentHouse, \'M\'));\n metal = house;\n }\n if (currentHouse.find(\'G\') != string::npos) {\n totalTime += (travelTime(glass, house, travel) + garbageCollectionTime(currentHouse, \'G\'));\n glass = house;\n }\n if (currentHouse.find(\'P\') != string::npos) {\n totalTime += (travelTime(plastic, house, travel) + garbageCollectionTime(currentHouse, \'P\'));\n plastic = house;\n }\n }\n\n return totalTime;\n }\n\nprivate:\n int travelTime(int start, int end, vector<int>& travel) {\n int time = 0;\n for (int stop = start; stop < end; ++stop) \n time += travel[stop];\n \n return time;\n }\n\n\nprivate:\n int garbageCollectionTime(string house, char type) {\n return count(house.begin(), house.end(), type);\n }\n``` | 3 | 0 | ['C', 'Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | O(1) Memory | O(n) time | o1-memory-on-time-by-nadaralp-ed41 | Only 1 garbage truck can move at a time. This directly tells us that this problem IS NOT A DP because we can calculate it with simulations/greedy.\n\nEvery truc | nadaralp | NORMAL | 2022-08-28T09:00:09.984170+00:00 | 2022-08-28T09:01:37.231493+00:00 | 64 | false | Only 1 garbage truck can move at a time. This directly tells us that this problem **IS NOT A DP** because we can calculate it with simulations/greedy.\n\nEvery truck must move one index at a time, stopping at the latest index that has it\'s material type (paper, glass, etc). Because from that point onwards there is no point in incurring the cost of traveling, it won\'t clean any more garbage.\n\nTo know the last index of every type, let\'s find it and store it in a pointer.\n\nAt any point we must collect all the garbage, and trucks that didn\'t find the latest material continue driving.\n\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n last_paper_index = 0\n last_metal_index = 0\n last_glass_index = 0\n \n n = len(garbage)\n for i, s in enumerate(garbage):\n for c in s:\n if c == \'M\': last_metal_index = i\n if c == \'P\': last_paper_index = i\n if c == \'G\': last_glass_index = i\n \n S = 0\n for i in range(n):\n S += len(garbage[i])\n \n if i < last_paper_index: S += travel[i]\n if i < last_metal_index: S += travel[i]\n if i < last_glass_index: S += travel[i]\n \n return S\n``` | 3 | 0 | [] | 0 |
minimum-amount-of-time-to-collect-garbage | O(n) solution | on-solution-by-aniketpanchal52648-8r7o | \nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n // vector<char> t={\'G\',\'P\'};\n vector | aniketpanchal52648 | NORMAL | 2022-08-28T08:54:12.801978+00:00 | 2022-08-28T08:58:19.482494+00:00 | 94 | false | ```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n // vector<char> t={\'G\',\'P\'};\n vector<pair<char,int>> t;\n t.push_back({\'M\',-1});\n t.push_back({\'P\',-1});\n t.push_back({\'G\',-1});\n int n=garbage.size();\n int ans=0;\n // int n=garbage.size();\n for(int i=n-1;i>=0;i--){\n int m=0;\n int p=0;\n int g=0;\n for(auto x:garbage[i]){\n if(x==\'M\') m++;\n else if(x==\'G\') g++;\n else p++;\n }\n \n if(m>0){\n t[0].second=max(t[0].second,i);\n }\n if(p>0){\n t[1].second=max(t[1].second,i);\n }\n if(g>0){\n t[2].second=max(t[2].second,i);\n }\n }\n for(int i=0;i<3;i++){\n for(int j=0;j<=t[i].second;j++){\n int c=0;\n for(char x:garbage[j]) {\n if(x==t[i].first) c++;\n }\n // cout<<c<<" j:"<<j<<endl;\n if(j!=t[i].second){\n \n ans=ans +(c+travel[j]);\n // cout<<ans<<" j:"<<j<<endl;\n }else{\n ans+=c;\n }\n \n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | [] | 2 |
minimum-amount-of-time-to-collect-garbage | Constant Space java solution | constant-space-java-solution-by-siddhant-627i | ```\nclass Solution {\n public int garbageCollection(String[] g, int[] t) {\n int a[]=new int[3];\n int k=g.length;\n String c[] = {"M", | Siddhant_1602 | NORMAL | 2022-08-28T08:17:06.593291+00:00 | 2022-08-28T08:17:06.593402+00:00 | 76 | false | ```\nclass Solution {\n public int garbageCollection(String[] g, int[] t) {\n int a[]=new int[3];\n int k=g.length;\n String c[] = {"M", "P", "G"};\n for(int i=0;i<3;i++)\n {\n for(int j=k-1;j>=0;j--)\n {\n if(g[j].contains(c[i]))\n {\n a[i]=j;\n break;\n }\n }\n }\n int s=0;\n for(int i=0;i<3;i++)\n {\n for(int j=0;j<a[i];j++)\n {\n s+=t[j];\n }\n }\n for(int i=0;i<k;i++)\n {\n s+=g[i].length();\n }\n return s;\n }\n} | 3 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | Rust | rust-by-wallicent-h58w | This is my unaltered submission to the 2022-08-28 Weekly Contest 308. We have to know how many \'P\'s, \'M\'s and \'G\'s there are in total (1 minute to process | wallicent | NORMAL | 2022-08-28T07:49:40.156060+00:00 | 2022-08-28T07:49:40.156098+00:00 | 88 | false | This is my unaltered submission to the 2022-08-28 Weekly Contest 308. We have to know how many \'P\'s, \'M\'s and \'G\'s there are in total (1 minute to process each letter). We also want to know the position of the last of each letter, since then the truck doesn\'t have to travel further. We need to know the sum of travel times to each stop, because the truck has to travel to each stop in turn. So we\'ll compute the prefix sum of travel times ((O(n)) as well as the sum of number of letters (O(n * k), where k is the maximum length of `garbage[i]`, and the last positions of the respective letters (O(n * k)). The total time is then the sum of the number of letters plus the sum of the corresponding prefix sum for the last stop for each letter.\n\nTime: O(n * k)\nSpace: O(n) for vector of prefix sums\n\nComment: I could have made things simpler by not splitting the sums of letters and just having something like `total_len += s.len()`, not that it would make any difference to big-O time complexity.\n\n```\nimpl Solution {\n pub fn garbage_collection(garbage: Vec<String>, travel: Vec<i32>) -> i32 {\n let mut acc = 0;\n let travel: Vec<i32> = std::iter::once(0).chain(travel.into_iter().map(|t| { acc += t; acc })).collect();\n let (p, m, g, last_p, last_m, last_g) = garbage.into_iter().enumerate().fold((0, 0, 0, 0, 0, 0), |(mut p, mut m, mut g, mut last_p, mut last_m, mut last_g), (i, s)| {\n for &b in s.as_bytes() {\n match b {\n b\'P\' => { p += 1; last_p = i; },\n b\'M\' => { m += 1; last_m = i; },\n _ => { g += 1; last_g = i; },\n }\n }\n (p, m, g, last_p, last_m, last_g)\n });\n p + m + g + travel[last_p] + travel[last_m] + travel[last_g]\n }\n}\n``` | 3 | 0 | ['Rust'] | 0 |
minimum-amount-of-time-to-collect-garbage | Swift solution (Brute force O(n)) | swift-solution-brute-force-on-by-andreev-anqa | \nclass Solution {\n func garbageCollection(_ garbage: [String], _ travel: [Int]) -> Int {\n "MGP".map{ collectGarbage(garbage, travel + [0], type: $0 | AndreevIVdev | NORMAL | 2022-08-28T06:13:13.554031+00:00 | 2022-08-28T06:13:13.554081+00:00 | 104 | false | ```\nclass Solution {\n func garbageCollection(_ garbage: [String], _ travel: [Int]) -> Int {\n "MGP".map{ collectGarbage(garbage, travel + [0], type: $0) }.reduce(0, +)\n }\n \n private func collectGarbage(_ garbage: [String], _ travel: [Int], type: Character) -> Int {\n var time = 0\n var res = 0\n for i in 0..<garbage.count {\n let n = garbage[i].filter{ $0 == type }.count\n if n > 0 {\n time += n\n res = time\n }\n time += travel[i]\n }\n \n return res\n }\n}\n``` | 3 | 0 | ['Swift'] | 1 |
minimum-amount-of-time-to-collect-garbage | C++ frequency count O(N) solution | c-frequency-count-on-solution-by-abhay53-v25y | Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\n\nclass Solution {\npublic:\n\n int garbageCollection(vector<string>& garbage, ve | abhay5349singh | NORMAL | 2022-08-28T04:03:13.503625+00:00 | 2023-07-14T03:51:13.470749+00:00 | 62 | false | **Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n```\nclass Solution {\npublic:\n\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n vector<vector<int>> freq(garbage.size(),vector<int> (3,0)); // frequency for each type of garbage for all indexes\n \n int lastM=-1, lastP=-1, lastG=-1; // to keep track of last indexes where the respective trucks have to move\n for(int i=0;i<garbage.size();i++){\n for(int j=0;j<garbage[i].length();j++){\n if(garbage[i][j] == \'M\') freq[i][0]++, lastM=i;\n if(garbage[i][j] == \'P\') freq[i][1]++, lastP=i;\n if(garbage[i][j] == \'G\') freq[i][2]++, lastG=i;\n }\n }\n \n int t=0;\n for(int i=0;i<garbage.size();i++){\n if(i<=lastM) t += freq[i][0] + (i>0 ? travel[i-1]:0);\n if(i<=lastP) t += freq[i][1] + (i>0 ? travel[i-1]:0);\n if(i<=lastG) t += freq[i][2] + (i>0 ? travel[i-1]:0);\n }\n return t;\n }\n};\n``` | 3 | 2 | [] | 0 |
minimum-amount-of-time-to-collect-garbage | c++ hashmap easy solution | c-hashmap-easy-solution-by-chandakji2204-c6t9 | \nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n map<int,vector<int>> house;\n vector<int> | chandakji2204 | NORMAL | 2022-08-28T04:01:55.296373+00:00 | 2022-08-28T04:01:55.296408+00:00 | 100 | false | ```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n map<int,vector<int>> house;\n vector<int> last(3);\n for(int i=0;i<garbage.size();i++){\n house[i]={0,0,0}; \n for(char& c:garbage[i]){\n if(c==\'G\')\n {\n house[i][0]++;\n last[0]=i;\n }\n if(c==\'M\')\n {\n house[i][1]++;\n last[1]=i;\n }\n if(c==\'P\')\n {\n house[i][2]++;\n last[2]=i;\n }\n }\n }\n int ans=0;\n ans=house[0][0]+house[0][1]+house[0][2];\n for(int i=0;i<3;i++){\n for(int j=1;j<garbage.size();j++){\n if(last[i]>=j){\n ans+=travel[j-1]+house[j][i]; \n }else break;\n \n }\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['C'] | 1 |
minimum-amount-of-time-to-collect-garbage | Ho gya re abbbaaa wah ji wah :D socha ki nhi hoga aur karna kaam lekin ho gyaaaaaaaaaaaaaaaaaaaaaaaa | ho-gya-re-abbbaaa-wah-ji-wah-d-socha-ki-jaz2d | 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 | yesyesem | NORMAL | 2024-10-12T17:26:48.124207+00:00 | 2024-10-12T17:26:48.124239+00:00 | 11 | 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```cpp []\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel){\n int g=0;\n int p=0;\n int m=0;\n\n int tempg=0;\n int tempp=0;\n int tempm=0;\n \n //this to do jus for the first element of the garbage vector\n int k=0;\n for(int i=0;i<garbage[0].size();i++)\n {\n if(garbage[0][i]==\'M\')\n m++;\n else if(garbage[0][i]==\'P\')\n p++;\n else\n g++;\n\n }\n\n k++;\n\n for(int i=0;i<travel.size();i++)\n {\n if(garbage[k].find(\'G\')!=string::npos)\n { \n g+=tempg;\n tempg=0;\n g+=travel[i];\n }\n else \n tempg+=travel[i];\n \n if(garbage[k].find(\'M\')!=string::npos)\n { \n m+=tempm;\n tempm=0;\n m+=travel[i];\n }\n else \n tempm+=travel[i];\n\n if(garbage[k].find(\'P\')!=string::npos)\n { \n p+=tempp;\n tempp=0;\n p+=travel[i];}\n else \n tempp+=travel[i];\n \n\n for(int j=0;j<garbage[k].size();j++)\n {\n if(garbage[k][j]==\'G\')\n g++;\n else if(garbage[k][j]==\'P\')\n p++;\n else\n m++;\n }\n k++;\n\n\n }\n\n \n return g+m+p;\n\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Counting || C++, Python, Java | counting-c-python-java-by-not_yl3-aqm3 | Approach\n Describe your approach to solving the problem. \nWe only need to sum up all the minutes ending at the last house with each garbage type. We can use s | not_yl3 | NORMAL | 2024-05-11T23:45:45.732648+00:00 | 2024-05-11T23:57:28.274284+00:00 | 70 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe only need to sum up all the minutes ending at the last house with each garbage type. We can use some boolean variables `metal`, `paper`, and `glass` to keep track of when we need to start adding the minutes. In each iteration also add the length of the string since we have to pick up all garbage. Additionally, starting from the end of `garbage` makes this approach much easier.\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```C++ []\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int ans = 0;\n bool metal = false, paper = false, glass = false;\n for (int i = garbage.size() - 1; i >= 0; i--){\n ans += garbage[i].length();\n if (!metal) metal = (garbage[i].find(\'M\') != string::npos);\n if (!paper) paper = (garbage[i].find(\'P\') != string::npos);\n if (!glass) glass = (garbage[i].find(\'G\') != string::npos);\n if (i > 0) ans += travel[i-1] * (metal + paper + glass);\n }\n return ans;\n }\n};\n```\n```python3 []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n ans = 0\n metal = paper = glass = False\n for i in range(len(garbage)-1, -1, -1):\n ans += len(garbage[i])\n if not metal: metal = \'M\' in garbage[i]\n if not paper: paper = \'P\' in garbage[i]\n if not glass: glass = \'G\' in garbage[i]\n if i > 0: ans += travel[i-1] * (metal + paper + glass)\n return ans\n```\n```Java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans = 0;\n boolean metal = false, paper = false, glass = false;\n for (int i = garbage.length - 1; i >= 0; i--){\n ans += garbage[i].length();\n if (!metal) metal = garbage[i].contains("M");\n if (!paper) paper = garbage[i].contains("P");\n if (!glass) glass = garbage[i].contains("G");\n if (i > 0) ans += travel[i-1] * ((metal ? 1 : 0) + (paper ? 1 : 0) + (glass ? 1 : 0));\n }\n return ans;\n }\n}\n```\n | 2 | 0 | ['Array', 'String', 'C', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3'] | 0 |
minimum-amount-of-time-to-collect-garbage | C++ || Single For Loop || O(n) || O(1) space | c-single-for-loop-on-o1-space-by-prajnan-yohj | Approach\n\n- In the scenario described, the garbage truck needs to visit the houses sequentially, starting from the 0th index. It\'s not necessary for the truc | prajnanam | NORMAL | 2024-04-21T07:28:25.249730+00:00 | 2024-04-21T07:31:00.123524+00:00 | 133 | false | # Approach\n\n- In the scenario described, the garbage truck needs to visit the houses sequentially, starting from the 0th index. It\'s not necessary for the truck to visit all the houses; it should stop at the last index where G, M, or P appears. After that point, the truck shouldn\'t visit any more houses, as our goal is to achieve minimum.\n\n- One approach is to construct a prefix array and add it to our answer for the last index of each truck. However, this approach would require O(n) space.\n\n- Another method is to compute the prefix directly in the travel vector itself while traversing the string.\n\n- If the last index of any truck is -1, it means it doesn\'t appear anywhere. If it\'s 0, it means it appeared only at the 0th index, so we don\'t need to add it to our answer.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int gi=-1,pi=-1,mi=-1,ans=0,n = garbage.size(); \n //gi pi mi all store lastindex of glass plastic metal respectively\n for(int i=0;i<n;i++){\n for(auto &ch:garbage[i]){\n if(ch == \'G\') gi=i; \n else if(ch == \'P\') pi=i;\n else mi=i;\n ans++;\n }\n if(i>0 && i<n-1){\n travel[i]+=travel[i-1];\n }\n }\n if(gi!=-1 && gi!=0) ans+=travel[gi-1];\n if(pi!=-1 && pi!=0) ans+=travel[pi-1];\n if(mi!=-1 && mi!=0) ans+=travel[mi-1];\n return ans;\n }\n};\n\n``` | 2 | 0 | ['Prefix Sum', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | using prefixsum || simple c++ approach||only one iteration||beginner friendly approach | using-prefixsum-simple-c-approachonly-on-574u | Intuition\n1. we need to calculate prefix sum of travel array of one length more than travel array in which first element is zero for avoiding overflow.\n2. we | Faiizzz786 | NORMAL | 2024-01-03T19:17:58.319705+00:00 | 2024-01-04T08:37:00.603582+00:00 | 10 | false | # Intuition\n1. we need to calculate prefix sum of travel array of one length more than travel array in which first element is zero for avoiding overflow.\n2. we need to calculate frequency of \'G\',\'P\' and \'M\' and their last index i.e; its last city.(note: last index helps to minimize the result).\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize gLastidx,pLastidx,mlastidx to calculate last occurance of \'G\',\'P\' and \'M\'.\n2. initialize cntg,cntp and cntm to calculate frequencies of \'G\',\'P\' and \'M\'.\n3. we need to iterate just once to calculate their last occurances and their frequencies.\n4. Initialize psum to calculate prefix sum in which first element is 0 just to avoid runtime error;\n5. add all frequencies(time for collecting garbages) and thier time using prefix sum (time to reach its destination).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int gLastidx=-1,pLastidx=-1,mLastidx=-1,n=garbage.size();\n int cntg=0,cntp=0,cntm=0;\n vector<int>psum(n,0);\n int sum=0;\n for(int i=1;i<n;i++){\n sum+=travel[i-1];\n psum[i]=sum;\n }\n int ans=0;\n for(int i=0;i<n;i++){\n for(auto x:garbage[i]){\n if(x==\'G\'){gLastidx=max(i,gLastidx);cntg++;};\n if(x==\'P\'){pLastidx=max(i,pLastidx);cntp++;};\n if(x==\'M\'){mLastidx=max(i,mLastidx);cntm++;};\n }\n }\n if(cntg)ans+=(cntg+psum[gLastidx]);\n if(cntp)ans+=(cntp+psum[pLastidx]);\n if(cntm)ans+=(cntm+psum[mLastidx]);\n \n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
minimum-amount-of-time-to-collect-garbage | Simple and Intuitive Java Solution | simple-and-intuitive-java-solution-by-ra-oksi | Intuition\nIf you examine the testcases carefully you will notice for each garbage truck the distance they will travel is the highest index that has at least 1 | rainvert | NORMAL | 2023-11-20T21:36:24.823414+00:00 | 2023-11-20T21:36:24.823442+00:00 | 20 | false | # Intuition\nIf you examine the testcases carefully you will notice for each garbage truck the distance they will travel is the highest index that has at least 1 unit of that type of garbage.\n\nSo if you just count all the letters along with noting the highest index of each type of garbage, the problem can be solved optimally.\n\n# Approach\nIn solving this problem, I count the garbage units at each house and track the last house for each type of garbage (\'G\', \'P\', \'M\'). \n\nI also used a prefix sum array to calculate the culmilative travel times between houses. \n\nFinally, I sum the garbage collection time and travel time to the furthest house for each garbage type to get the total time required.\n\n# Complexity\n- Time complexity:\nO(n*m), where n is the number of houses and \nm is the average length of the garbage strings. This is because you need to iterate through each character in each garbage string.\n\n- Space complexity:\nO(n) for the prefix array\n\n# Code\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n // Initialize variables\n int sum = 0; // Total time for collecting garbage and travel\n int g = 0; // Index of the last house with glass garbage\n int p = 0; // Index of the last house with paper garbage\n int m = 0; // Index of the last house with metal garbage\n int[] prefix = new int[travel.length]; // Prefix sum array for travel times\n\n // Creating the prefix sum array (Optional)\n prefix[0] = travel[0];\n for (int i = 1; i < travel.length; i++) {\n prefix[i] = prefix[i - 1] + travel[i];\n }\n\n // Iterating over each house\'s garbage\n for (int i = 0; i < garbage.length; i++) {\n for (int j = 0; j < garbage[i].length(); j++) {\n char type = garbage[i].charAt(j);\n // Check the type of garbage and update time and last house index\n if (type == \'G\') {\n g = i;\n sum++; // Increment for picking up one unit of garbage\n }\n if (type == \'P\') {\n p = i;\n sum++; // Increment for picking up one unit of garbage\n }\n if (type == \'M\') {\n m = i;\n sum++; // Increment for picking up one unit of garbage\n }\n }\n }\n\n // Add travel time to reach the furthest house for each type of garbage\n if (g != 0) {\n sum += prefix[g - 1];\n }\n if (m != 0) {\n sum += prefix[m - 1];\n }\n if (p != 0) {\n sum += prefix[p - 1];\n }\n\n // Return the total time required\n return sum;\n }\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | No HashMap | Easy and Intuitive | no-hashmap-easy-and-intuitive-by-spats7-9x4e | ```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int[] time = new int[3];\n \n for(int i=garbage | spats7 | NORMAL | 2023-11-20T19:02:23.646508+00:00 | 2023-11-20T19:02:23.646536+00:00 | 23 | false | ```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int[] time = new int[3];\n \n for(int i=garbage.length-1; i>=0; i--){\n \n for(char c : garbage[i].toCharArray()){\n int idx = c == \'P\' ? 0 : (c==\'M\' ? 1 : 2);\n time[idx] += 1;\n }\n \n int transfer = i>0 ? travel[i-1] : 0;\n \n for(int j=0; j<3; j++)\n time[j] += time[j] !=0 ? transfer : 0;\n }\n return time[0] + time[1] + time[2];\n }\n} | 2 | 0 | ['Array', 'Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | ✅Python || Beats 100% || O(n) | python-beats-100-on-by-ruzibekoff-miy3 | \n\n# Problem\nThe problem is asking to minimize the time taken to collect all the garbage. We have three types of garbage and three trucks, each responsible fo | ruzibekoff | NORMAL | 2023-11-20T15:21:00.357619+00:00 | 2023-11-20T15:21:00.357648+00:00 | 222 | false | \n\n# Problem\nThe problem is asking to minimize the time taken to collect all the garbage. We have three types of garbage and three trucks, each responsible for one type of garbage. The trucks can only move in one direction and cannot skip any houses. Therefore, we need to find the last occurrence of each type of garbage and calculate the total time taken to reach these houses and collect the garbage.\n# What we do\nWe first calculate the cumulative travel time for each house.\n```\nfib = [0]\nfor time in travel: fib.append(fib[-1] + time)\n```\n Then, we iterate over the garbage array in reverse order and keep track of the last occurrence of each type of garbage.\n```\nfor i in range(len(garbage)-1, -1, -1):\n v = garbage[i]\n if not memo[0] and "M" in v: memo[0] = i\n if not memo[1] and "P" in v: memo[1] = i\n if not memo[2] and "G" in v: memo[2] = i\n```\n ```all(memo)``` checks if all elements in the memo list are truthy (i.e., they have a value other than zero). If all elements in memo are non-zero, it means that we have found at least one occurrence of each type of garbage (metal, paper, and glass), and ```all(memo)``` will return ```True```. If any element in memo is zero, it means that we haven\u2019t found an occurrence of that type of garbage yet, and all(memo) will return ```False```.\n```\nif all(memo): break\n```\n Finally, we return the total amount of garbage plus the sum of the travel times to the last occurrence of each type of garbage. This ensures that all garbage is collected in the minimum amount of time.\n```\nreturn len("".join(garbage)) + (fib[memo[0]] + fib[memo[1]] + fib[memo[2]])\n```\n\n# Complexity\n- Time complexity: \n $$O(n)$$\n where $$n$$ is the number of houses. This is because we need to iterate over the garbage array once.\n- Space complexity: $$O(n)$$\n\n \n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n fib, memo = [0], [0] * 3\n\n for time in travel: fib.append(fib[-1] + time)\n \n for i in range(len(garbage)-1, -1, -1):\n v = garbage[i]\n if not memo[0] and "M" in v: memo[0] = i\n if not memo[1] and "P" in v: memo[1] = i\n if not memo[2] and "G" in v: memo[2] = i\n\n if all(memo): break\n\n return len("".join(garbage)) + (fib[memo[0]] + fib[memo[1]] + fib[memo[2]])\n\n \n```\n# CodeExplanation\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n # Initialize an array to store the cumulative travel time and an array to store the last occurrence of each type of garbage\n fib, memo = [0], [0] * 3\n\n # Calculate the cumulative travel time for each house\n for time in travel: fib.append(fib[-1] + time)\n \n \n # Iterate over the garbage array in reverse order\n for i in range(len(garbage)-1, -1, -1):\n v = garbage[i]\n # If the current house has metal garbage and it\'s the first occurrence, store its index\n if not memo[0] and "M" in v: memo[0] = i\n # If the current house has paper garbage and it\'s the first occurrence, store its index\n if not memo[1] and "P" in v: memo[1] = i\n # If the current house has glass garbage and it\'s the first occurrence, store its index\n if not memo[2] and "G" in v: memo[2] = i\n\n # If we have found at least one occurrence of each type of garbage, stop the iteration\n if all(memo): break\n\n # Return the total amount of garbage plus the sum of the travel times to the last occurrence of each type of garbage\n return len("".join(garbage)) + (fib[memo[0]] + fib[memo[1]] + fib[memo[2]])\n```\n# Upvote\n```\nUpvote = False\nif my_code == "Helpful":\n Upvote = True\nprint("Thank You")\n``` | 2 | 0 | ['Python3'] | 2 |
minimum-amount-of-time-to-collect-garbage | populating hashtable in o[n] then counting no of operations | populating-hashtable-in-on-then-counting-6xhy | \n\n# Complexity\n- Time complexity:\no[n]\n\n\n# Code\n\nclass Solution(object):\n def garbageCollection(self, garbage, travel):\n hash = {}\n | AdhamEhabElsheikh | NORMAL | 2023-11-20T10:17:48.875437+00:00 | 2023-11-20T10:17:48.875459+00:00 | 92 | false | \n\n# Complexity\n- Time complexity:\no[n]\n\n\n# Code\n```\nclass Solution(object):\n def garbageCollection(self, garbage, travel):\n hash = {}\n string = \' \'.join(garbage) \n counter = 0 \n \n for char in string:\n if char != \' \':\n if char not in hash:\n hash[char] = []\n hash[char].append(counter)\n else:\n counter += 1\n if \'G\' in hash: \n last_g = hash[\'G\'][-1]\n if \'P\' in hash:\n last_p = hash[\'P\'][-1]\n if \'M\' in hash:\n last_m = hash[\'M\'][-1]\n total_time = 0\n i=0\n \n if \'P\' in hash: \n while i < last_p :\n print(travel[i])\n total_time += travel[i]\n i+=1\n total_time += len(hash[\'P\'])\n \n i=0 \n if \'G\' in hash: \n while i < last_g :\n print(travel[i])\n total_time += travel[i]\n i+=1\n total_time += len(hash[\'G\'])\n \n i=0\n if \'M\' in hash: \n while i < last_m :\n total_time += travel[i]\n i+=1\n total_time += len(hash[\'M\'])\n \n return total_time\n\n \n \n \n\n """\n :type garbage: List[str]\n :type travel: List[int]\n :rtype: int\n """\n \n``` | 2 | 0 | ['Python'] | 0 |
minimum-amount-of-time-to-collect-garbage | Beats 100%🔥|| easy JAVA Solution✅ | beats-100-easy-java-solution-by-priyansh-oood | Code\n\nclass Solution {\n public int garbageCollection(String[] g, int[] t) {\n int ans=0;\n for(int i:t){\n ans+=i;\n }\n | priyanshu1078 | NORMAL | 2023-11-20T08:28:25.022572+00:00 | 2023-11-20T08:28:25.022592+00:00 | 26 | false | # Code\n```\nclass Solution {\n public int garbageCollection(String[] g, int[] t) {\n int ans=0;\n for(int i:t){\n ans+=i;\n }\n ans*=3;\n for(String i:g) ans+=i.length();\n for(int i=g.length-1;i>0;i--){\n if(!g[i].contains("M")) ans-=t[i-1];\n else break;\n }\n for(int i=g.length-1;i>0;i--){\n if(!g[i].contains("P")) ans-=t[i-1];\n else break;\n }\n for(int i=g.length-1;i>0;i--){\n if(!g[i].contains("G")) ans-=t[i-1];\n else break;\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | Beats 83.88% in Runtime and 91.88% in Memory | C++ | JavaScript | beats-8388-in-runtime-and-9188-in-memory-6y2g | 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 | Nurliaidin | NORMAL | 2023-11-20T08:03:47.496892+00:00 | 2023-11-20T08:03:47.496927+00:00 | 612 | 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```javascript []\n/**\n * @param {string[]} garbage\n * @param {number[]} travel\n * @return {number}\n */\nlet travelCounter = function(truck, travel) {\n let sum = 0;\n for(let i=0; i<truck; i++) {\n sum += travel[i];\n }\n return sum;\n};\nvar garbageCollection = function(garbage, travel) {\n let g=0;\n let m=0;\n let p=0;\n // travel = [0].concat(travel);\n let res=0;\n // let position = new Map([\'G\', 0], [\'M\', 0], [\'P\', 0]);\n \n for(let i=0; i<garbage.length; i++) {\n if(garbage[i].includes("G", 0)) {\n g = i;\n // position.set(\'G\', i);\n // g += (garbage[i].match(/G/g) || []).length;\n }\n if(garbage[i].includes("M", 0)) {\n m = i;\n // position.set(\'M\', i);\n // m += (garbage[i].match(/M/g) || []).length;\n }\n if(garbage[i].includes("P", 0)) {\n p = i;\n // position.set(\'P\', i);\n // p += (garbage[i].match(/P/g) || []).length;\n }\n res = res + garbage[i].length;\n }\n console.log(res);\n res += travelCounter(g, travel);\n res += travelCounter(p, travel);\n res += travelCounter(m, travel);\n return res;\n};\n```\n```cpp []\nclass Solution {\npublic:\n int travelDuration(int& truck, vector<int>& travel) {\n int sum = 0;\n for(int i=0; i<=truck; i++) {\n sum += travel[i];\n }\n return sum;\n }\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int m=0, p=0, g=0;\n int res = 0;\n travel.insert(travel.begin(), 0);\n for(int i=0; i<garbage.size(); i++) {\n if(garbage[i].find(\'G\') != string::npos) g = i;\n if(garbage[i].find(\'P\') != string::npos) p = i;\n if(garbage[i].find(\'M\') != string::npos) m = i;\n res += garbage[i].size();\n }\n res += travelDuration(m, travel);\n res += travelDuration(g, travel);\n res += travelDuration(p, travel);\n return res;\n } \n};\n```\n | 2 | 0 | ['C++', 'JavaScript'] | 1 |
minimum-amount-of-time-to-collect-garbage | Video Solution | Explanation With Drawings | In Depth | Java | C++ | video-solution-explanation-with-drawings-rywl | Intuition, approach, and complexity discussed in detail in video solution\nhttps://youtu.be/43u8AipcfOk\n\n# Code\nC++\n\nclass Solution {\npublic:\n int gar | Fly_ing__Rhi_no | NORMAL | 2023-11-20T06:23:35.346993+00:00 | 2023-11-20T06:24:47.490278+00:00 | 675 | false | # Intuition, approach, and complexity discussed in detail in video solution\nhttps://youtu.be/43u8AipcfOk\n\n# Code\nC++\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n long long totalTimeToPick = 0, sz = garbage.size();\n unordered_map<char, int> lastHouseToVisit;\n vector<long long> travelTime(sz-1);\n for(int indx = 0; indx < sz-1; indx++){\n if(indx > 0) \n travelTime[indx] = travelTime[indx - 1] + travel[indx];\n else \n travelTime[indx] = travel[indx]; \n } \n for(int indx = 0; indx < sz; indx++){\n int totalGrabUnits = garbage[indx].size();\n totalTimeToPick += totalGrabUnits;\n for(auto grab : garbage[indx])lastHouseToVisit[grab] = indx;\n }\n for(auto &pr : lastHouseToVisit){\n int lastHouse = pr.second;\n if(lastHouse != 0)\n totalTimeToPick += travelTime[lastHouse - 1];\n }\n return totalTimeToPick;\n }\n};\n```\nJava\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int totalTimeToPick = 0, sz = garbage.length;\n Map<Character, Integer> lastHouseToVisit = new HashMap<>();\n int travelTime[] = new int[sz-1];\n for(int indx = 0; indx < sz-1; indx++){\n if(indx > 0) \n travelTime[indx] = travelTime[indx - 1] + travel[indx];\n else \n travelTime[indx] = travel[indx]; \n } \n for(int indx = 0; indx < sz; indx++){\n int totalGrabUnits = garbage[indx].length();\n totalTimeToPick += totalGrabUnits;\n for(var grab : garbage[indx].toCharArray())lastHouseToVisit.put(grab, indx);\n }\n for(var pr : lastHouseToVisit.entrySet()){\n int lastHouse = pr.getValue();\n if(lastHouse != 0)\n totalTimeToPick += travelTime[lastHouse - 1];\n }\n return totalTimeToPick;\n }\n}\n``` | 2 | 0 | ['C++', 'Java'] | 1 |
minimum-amount-of-time-to-collect-garbage | Simple python solution for beginners | simple-python-solution-for-beginners-by-fkmqx | \n\n# Code\n\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n garbage.reverse()\n sum=0\n | Dhaxina | NORMAL | 2023-11-20T06:08:31.129257+00:00 | 2023-11-20T06:08:31.129277+00:00 | 34 | false | \n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n garbage.reverse()\n sum=0\n for x in travel:\n sum+=x\n sum*=3\n for i in range(len(garbage)-1):\n if \'G\' not in garbage[i]:\n sum-=travel[len(garbage)-i-2]\n else:\n break\n for i in range(len(garbage)-1):\n if \'M\' not in garbage[i]:\n sum-=travel[len(garbage)-i-2]\n else:\n break\n for i in range(len(garbage)-1):\n if \'P\' not in garbage[i]:\n sum-=travel[len(garbage)-i-2]\n else:\n break\n a=\'\'.join(garbage)\n return sum+len(a)\n \n \n\n``` | 2 | 0 | ['Math', 'Python', 'Python3'] | 0 |
minimum-amount-of-time-to-collect-garbage | C++ Solution | c-solution-by-pranto1209-07tf | Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n O(N * K)\n Where N is garbage.length and K is garbage[i].length\n\n- Space c | pranto1209 | NORMAL | 2023-11-20T05:56:36.902763+00:00 | 2023-11-20T05:56:36.902786+00:00 | 6 | false | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N * K)\n Where N is garbage.length and K is garbage[i].length\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n string st = "MPG";\n int ans = 0;\n for(auto truck: st) {\n bool fl = 0;\n for(int i = garbage.size() - 1; i >= 0; i--) {\n for(int j = 0; j < garbage[i].size(); j++) {\n if(garbage[i][j] == truck) fl = 1, ans++;\n }\n if(fl && i > 0) {\n ans += travel[i - 1];\n } \n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | C++ | Easy code | Beat 95% | c-easy-code-beat-95-by-ankita2905-r6qk | 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 | Ankita2905 | NORMAL | 2023-11-20T04:33:46.066378+00:00 | 2023-11-20T04:33:46.066396+00:00 | 8 | 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```\n/** Ankita Kumari. */\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n // Vector to store the prefix sum in travel.\n vector<int> prefixSum(travel.size() + 1, 0);\n prefixSum[1] = travel[0];\n for (int i = 1; i < travel.size(); i++) {\n prefixSum[i + 1] = prefixSum[i] + travel[i];\n }\n \n // Map to store garbage type to the last house index.\n unordered_map<char, int> garbageLastPos;\n\n // Map to store the total count of each type of garbage in all houses.\n unordered_map<char, int> garbageCount;\n for (int i = 0; i < garbage.size(); i++) {\n for (char c : garbage[i]) {\n garbageLastPos[c] = i;\n garbageCount[c]++;\n }\n }\n \n char garbageTypes[3] = {\'M\', \'P\', \'G\'};\n int ans = 0;\n for (char c : garbageTypes) {\n // Add only if there is at least one unit of this garbage.\n if (garbageCount[c]) {\n ans += prefixSum[garbageLastPos[c]] + garbageCount[c];\n }\n }\n \n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | [C++] Simple Solution without Prefix Sum | c-simple-solution-without-prefix-sum-by-qo42d | Intuition\n Describe your first thoughts on how to solve this problem. \n- We can simulate the garbage collection for each truck separately\n - All trucks are | pepe-the-frog | NORMAL | 2023-11-20T04:30:21.861908+00:00 | 2023-11-20T04:30:21.861930+00:00 | 261 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We can simulate the garbage collection for each truck separately\n - All trucks are independent, because ```Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.```\n- End the simulation of each truck when the target garbage (metal/paper/glass) is empty\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Summarize the garbage `by house` and `in total`\n- Collect the metal/paper/glass garbage\n - Collect the garbage with `type` in the house `i`\n - Break if there is no garbage after the house `i`\n - Travel to the next house\n\n# Complexity\n- Time complexity: $$O({n}\\times{k})$$\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 // time/space: O(nk)/O(n)\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n // summarize the garbage `by house` and `in total`\n int n = garbage.size();\n vector<unordered_map<char, int>> house_count(n);\n unordered_map<char, int> total_count;\n for (int i = 0; i < n; i++) {\n for (auto& c : garbage[i]) {\n house_count[i][c]++;\n total_count[c]++;\n }\n }\n\n // collect the metal/paper/glass garbage\n int time = 0;\n for (auto& type : "MPG") {\n for (int i = 0; i < n; i++) {\n // collect the garbage with `type` in the house `i`\n time += house_count[i][type];\n total_count[type] -= house_count[i][type];\n // break if there is no garbage after the house `i`\n if (total_count[type] == 0) break;\n // travel to the next house\n if (i < (n - 1)) time += travel[i];\n }\n }\n return time;\n }\n};\n``` | 2 | 0 | ['Hash Table', 'Simulation', 'Counting', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Easy Python Solution || Beats 94% in Runtime | easy-python-solution-beats-94-in-runtime-u9la | \n\n# Approach\n1. Keep track of index of the last occurance of each garbage.\n2. Also keep track of frequency of Each letter. (You can maintain a single variab | pranav743 | NORMAL | 2023-11-20T03:59:55.949273+00:00 | 2023-11-20T04:04:30.984849+00:00 | 161 | false | \n\n# Approach\n1. Keep track of index of the last occurance of each garbage.\n2. Also keep track of frequency of Each letter. (You can maintain a single variable which stores total freq of each letter, here i have used variable `ans`).\n3. At the end sum up `travel` upto the last index of each letter and add them together.\n4. Also don\'t forget to add the total count of all the letters.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n \n lm = 0 # Last index at which "M" was seen\n lg = 0 # Last index at which "G" was seen\n lp = 0 # Last index at which "P" was seen\n ans = 0\n\n for i in range(len(garbage)):\n if "G" in garbage[i]:\n lg = i\n if "P" in garbage[i]:\n lp = i\n if "M" in garbage[i]:\n lm = i\n ans+=len(garbage[i])\n\n ans+=sum(travel[:lm])+sum(travel[:lg])+sum(travel[:lp])\n\n return ans\n \n``` | 2 | 0 | ['Python3'] | 2 |
minimum-amount-of-time-to-collect-garbage | Easy Intuitive solution using Hashmap and Prefix Sum | easy-intuitive-solution-using-hashmap-an-yl79 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \ntravel time(taking pref | yashaswisingh47 | NORMAL | 2023-11-20T03:43:15.722193+00:00 | 2023-11-20T03:43:15.722221+00:00 | 592 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntravel time(taking prefix sum) will give us the time to travel to the particular index and travel_time[last_index[i] - 1] will give us the time to travel to the last index of the i -{\'M\', \'P\' , \'G\'} and adding that to the frequency will give us the total time for that particular i.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n travel_time , s = [] , 0 \n lis=\'\'.join(garbage)\n d = Counter(lis)\n for i in range(1,len(garbage)):\n s += travel[i-1]\n travel_time.append(s)\n last_index = defaultdict(int)\n for i in range(len(garbage)):\n if \'M\' in garbage[i]:\n last_index[\'M\'] = i\n if \'P\' in garbage[i]:\n last_index[\'P\'] = i\n if \'G\' in garbage[i]:\n last_index[\'G\'] = i\n ans = 0\n for i in d:\n ans += d[i]\n if last_index[i] > 0 : ans += travel_time[last_index[i] - 1]\n return ans\n``` | 2 | 0 | ['Hash Table', 'Prefix Sum', 'Python3'] | 0 |
minimum-amount-of-time-to-collect-garbage | 🫠Simplest_Brute_Force.py🙌 | simplest_brute_forcepy-by-jyot_150-bwk0 | Code\n\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n def cnt(ch,g):\n gb=[]\n | jyot_150 | NORMAL | 2023-11-20T03:32:28.342454+00:00 | 2023-11-20T03:32:28.342516+00:00 | 38 | false | # Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n def cnt(ch,g):\n gb=[]\n for i in g:gb.append(i.count(ch))\n for i in range(len(gb)-1,-1,-1):\n if gb[i]==0:gb.pop()\n else:break\n ans=0\n for i in range(len(gb)):\n ans+=gb[i]\n for i in range(len(gb)-1):ans+=travel[i]\n return ans\n return cnt(\'G\',garbage)+cnt(\'P\',garbage)+cnt(\'M\',garbage)\n``` | 2 | 0 | ['Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | C# Solution for Minimum Amount of Time to Collect Garbage Problem | c-solution-for-minimum-amount-of-time-to-s35n | Intuition\n Describe your first thoughts on how to solve this problem. \n1.\tPrefix Sum Calculation: The solution calculates the prefix sum of travel times, pro | Aman_Raj_Sinha | NORMAL | 2023-11-20T03:08:48.263489+00:00 | 2023-11-20T03:08:48.263508+00:00 | 163 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1.\tPrefix Sum Calculation: The solution calculates the prefix sum of travel times, providing the accumulated time from the 0th house to the i-th house.\n2.\tMapping Last House Index and Garbage Count: It maps each garbage type to its last encountered house index and counts the total occurrences of each garbage type across all houses.\n3.\tTotal Time Calculation: Based on the last house index and count of each garbage type, the solution computes the total time required to collect all garbage type\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tPrefix Sum of Travel Times: The code generates the prefix sum of travel times, stored in the prefixSum array.\n2.\tMapping Last House Index and Garbage Count: It uses dictionaries (garbageLastPos and garbageCount) to map each garbage type to its last house index and track the total count of each garbage type, respectively.\n3.\tTotal Time Calculation: It iterates through predefined garbage types (\u2018M\u2019, \u2018P\u2019, \u2018G\u2019), retrieves their counts and last house indices, and computes the total time required to collect each type of garbage based on the stored information.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tPrefix Sum Calculation: O(N), where N is the number of houses (length of travel array).\n\u2022\tMapping Last House Index and Garbage Count: O(total characters in all garbage strings), which is the total length of all strings in the garbage array.\n\u2022\tIterating through Garbage Types: O(1) as there are only three predefined garbage types.\n\nTherefore, the overall time complexity is O(N + total characters in all garbage strings).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tPrefix Sum Array: O(N) for storing the prefix sum of travel times.\n\u2022\tDictionaries: O(total characters in all garbage strings) for storing mappings and counts of garbage types.\n\nThus, the overall space complexity is O(N + total characters in all garbage strings).\n\n# Code\n```\npublic class Solution {\n public int GarbageCollection(string[] garbage, int[] travel) {\n int[] prefixSum = new int[travel.Length + 1];\n prefixSum[1] = travel[0];\n \n for (int i = 1; i < travel.Length; i++) {\n prefixSum[i + 1] = prefixSum[i] + travel[i];\n }\n\n Dictionary<char, int> garbageLastPos = new Dictionary<char, int>();\n Dictionary<char, int> garbageCount = new Dictionary<char, int>();\n \n for (int i = 0; i < garbage.Length; i++) {\n foreach (char c in garbage[i].ToCharArray()) {\n garbageLastPos[c] = i;\n if (!garbageCount.ContainsKey(c)) {\n garbageCount[c] = 1;\n } else {\n garbageCount[c]++;\n }\n }\n }\n\n string garbageTypes = "MPG";\n int ans = 0;\n \n foreach (char c in garbageTypes.ToCharArray()) {\n if (garbageCount.ContainsKey(c)) {\n ans += (prefixSum[garbageLastPos[c]] + garbageCount[c]);\n }\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | ['C#'] | 0 |
minimum-amount-of-time-to-collect-garbage | Java Solution for Minimum Amount of Time to Collect Garbage Problem | java-solution-for-minimum-amount-of-time-01y4 | Intuition\n Describe your first thoughts on how to solve this problem. \n1.\tTravel Time Calculation: The first loop modifies the travel array to hold the prefi | Aman_Raj_Sinha | NORMAL | 2023-11-20T03:00:39.180878+00:00 | 2023-11-20T03:00:39.180910+00:00 | 442 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1.\tTravel Time Calculation: The first loop modifies the travel array to hold the prefix sum of travel times. This step ensures that travel[i] holds the total time taken to travel from the 0th house to the i-th house.\n2.\tGarbage Type and Last House Index Mapping: It uses a HashMap garbageLastPos to map each garbage type to the index of the last house where that garbage type is encountered. This step is achieved by iterating through the garbage array.\n3.\tCalculating the Total Time: It calculates the total time needed to collect all types of garbage based on the last index of each garbage type and the prefix sum travel times.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tPrefix Sum of Travel Times: The code snippet modifies the travel array to store the prefix sum of travel times. This allows for quick access to the total travel time from the 0th house to any i-th house.\n2.\tMapping Garbage Types to Last House Index: It iterates through the garbage array to map each garbage type to the index of the last house where that garbage type is encountered. The total length of all garbage strings is initially added to ans.\n3.\tIterating through Garbage Types: It iterates through the predefined garbage types (\u2018M\u2019, \u2018P\u2019, \u2018G\u2019) and adds the travel time to the last house where that garbage type is found (using the prefix sum of travel times).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tPrefix Sum Calculation: O(N), where N is the number of houses.\n\u2022\tMapping Garbage Types: O(total characters in all garbage strings), which is the total length of all strings in the garbage array.\n\u2022\tIterating through Garbage Types: O(1) because there are only three predefined garbage types.\n\nHence, the overall time complexity is dominated by the prefix sum calculation and mapping of garbage types, resulting in a complexity of O(N + total characters).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tPrefix Sum Array: O(N) for storing the prefix sum of travel times.\n\u2022\tHashMap: O(total characters in all garbage strings) for storing the mapping of garbage types to their last house indices.\n\nTherefore, the overall space complexity is O(N + total characters).\n\n# Code\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n \n for (int i = 1; i < travel.length; i++) {\n travel[i] = travel[i - 1] + travel[i];\n }\n\n \n Map<Character, Integer> garbageLastPos = new HashMap<Character, Integer>();\n int ans = 0;\n for (int i = 0; i < garbage.length; i++) {\n for (char c : garbage[i].toCharArray()) {\n garbageLastPos.put(c, i);\n }\n ans += garbage[i].length();\n }\n\n String garbageTypes = "MPG";\n for (char c : garbageTypes.toCharArray()) {\n \n ans += (garbageLastPos.getOrDefault(c, 0) == 0 ? 0 : travel[garbageLastPos.get(c) - 1]);\n }\n\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 2 |
minimum-amount-of-time-to-collect-garbage | 16 line Simple C++ Solution | 16-line-simple-c-solution-by-yashmenaria-75tn | \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# | yashmenaria | NORMAL | 2023-11-20T02:17:13.197789+00:00 | 2023-11-20T02:17:13.197811+00:00 | 10 | false | \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 {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int res = 0;\n int k = 0;\n int m_i = -1, g_i = -1, p_i = -1;\n for(int i = 1; i < travel.size(); i++) travel[i] = travel[i-1] + travel[i];\n for(auto x : garbage){\n for(auto c : x){\n res++;\n if(c == \'M\') m_i = k;\n if(c == \'P\') p_i = k;\n if(c == \'G\') g_i = k;\n }\n k++;\n }\n res += ((m_i > 0) ? travel[m_i - 1] : 0);\n res += ((p_i > 0) ? travel[p_i - 1] : 0);\n res += ((g_i > 0) ? travel[g_i - 1] : 0);\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Python3 Solution | python3-solution-by-motaharozzaman1996-rlp2 | \n\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n ans=0\n n=len(garbage)\n for c in "MP | Motaharozzaman1996 | NORMAL | 2023-11-20T01:36:42.411017+00:00 | 2023-11-20T01:36:42.411054+00:00 | 132 | false | \n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n ans=0\n n=len(garbage)\n for c in "MPG":\n best=0\n cur=0\n cur+=garbage[0].count(c)\n best=max(cur,best)\n for i in range(1,n):\n cur+=travel[i-1]\n if c in garbage[i]:\n cur+=garbage[i].count(c)\n best=max(cur,best)\n ans+=best\n return ans \n\n``` | 2 | 0 | ['Python', 'Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | 🔥💥 C++ Simple Solution Using HashMap💥🔥 | c-simple-solution-using-hashmap-by-eknat-ghka | Intuition\n Describe your first thoughts on how to solve this problem. \nThe approach involves iterating through the given houses and their respective garbage, | eknath_mali_002 | NORMAL | 2023-11-20T01:05:19.006789+00:00 | 2023-11-20T01:05:19.006808+00:00 | 682 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe approach involves iterating through the given houses and their respective garbage, keeping track of the `last occurrence of each type of garbage`. Then, simulate the traversal of each type of garbage truck through the houses while calculating the `time` taken to pick up the garbage.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create an `unordered map mp` to store the `count` of each type of `garbage` in each house.\n2. Maintain a last_index vector to store the `last occurrence of each type of garbage`.\n3. Traverse the garbage array to populate mp and update last_index accordingly.\n4. Simulate the traversal of each type of garbage truck through the houses while calculating the time taken to pick up the garbage.\n5. Calculate the total time required by each truck to pick up its corresponding garbage and travel between houses.\n# Complexity\n- Time complexity:$$O(N)$$\n - where `N` is the number of houses\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N)$$\n - for the unordered map `mp` and `last_index` vector, where `N` is the number of houses.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n unordered_map<int , vector<int>>mp;\n vector<int>last_index(3);\n for(int i=0; i<garbage.size(); i++){\n int m = 0 , p= 0, g =0;\n for(auto ch :garbage[i]){\n if(ch==\'M\')m++;\n else if(ch==\'P\')p++;\n else g++;\n }\n mp[i].push_back(m); // 0th index for metal\n mp[i].push_back(p); // 1st index for paper\n mp[i].push_back(g); // 2nd index for glass\n if(m>0)last_index[0] = i;\n if(p>0)last_index[1] = i;\n if(g>0)last_index[2] = i;\n }\n\n // for metal\n int ans = 0;\n travel.insert(travel.begin(), 0);\n for(int i=0; i<=last_index[0]; i++){\n ans += mp[i][0];\n ans += travel[i];\n }\n // for paper\n for(int i=0; i<=last_index[1]; i++){\n ans += mp[i][1];\n ans += travel[i];\n }\n // for glass\n for(int i=0; i<=last_index[2]; i++){\n ans += mp[i][2];\n ans += travel[i];\n }\n\n return ans;\n\n\n }\n};\n``` | 2 | 0 | ['Array', 'Hash Table', 'String', 'C++'] | 1 |
minimum-amount-of-time-to-collect-garbage | ✅ Python3 || 🚀 Count || ⭐️ Thoroughly Explanation and Clean code ⭐️ | python3-count-thoroughly-explanation-and-ikqp | Intuition\nIt is hard to understand the description of this problem, if we focus on meaning of it we realize that calculating each step when it picked a garbage | lutfullo_m | NORMAL | 2023-11-14T11:38:39.638068+00:00 | 2023-12-12T16:14:39.752248+00:00 | 11 | false | # Intuition\nIt is hard to understand the description of this problem, if we focus on meaning of it we realize that calculating each step when it picked a garbage and moving every house accrording to travel distance is our work.\n\n# Approach\n1. First, we assign a variable to calculatin each step` s minutes as well as seperate varibales for each garbage type and additional varibales for thiers inedex in order to know each garbge final distination since there is no need to continue to move if there is no any this type of garabage as explained in description.\n2. Iterating in for loop through its index and check if garabage[x] house contains specefic type of garbage for each type of garabage if so add its number to a varible created befeore, at the same time we obtain its index\n3. After iteration, we again add for each garbage` time taken during the collecting garbage. In this situation, we slice travel until a house a garbag truck final distination. \n\n\n\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: list[str], travel: list[int]) -> int:\n M = G = P = counter = 0\n M_i = G_i = P_i = 0\n\n for x in range(len(garbage)):\n\n if "M" in garbage[x]:\n counter += garbage[x].count("M")\n M_i = x\n\n if "P" in garbage[x]:\n counter += garbage[x].count("P")\n P_i = x\n\n if "G" in garbage[x]:\n counter += garbage[x].count("G")\n G_i = x\n\n counter += sum(travel[:P_i])\n counter += sum(travel[:G_i])\n counter += sum(travel[:M_i])\n return counter\n\n\nobj = Solution()\nprint(obj.garbageCollection(garbage=["MMM", "PGM", "GP"], travel=[3, 10]))\n\n```\n\n\n | 2 | 0 | ['Counting', 'Iterator', 'Python3'] | 0 |
minimum-amount-of-time-to-collect-garbage | 99% Faster✅ 86% Less Memory✅ Clean Explained C++ Code | 99-faster-86-less-memory-clean-explained-l7an | Intuition\nAll kinds of elements take same amount of time to be picked up, their difference only matters to calculate the no. of trips to be made.\nSo calculate | ayunick | NORMAL | 2023-07-29T18:23:38.921945+00:00 | 2023-07-29T18:23:38.921994+00:00 | 20 | false | # Intuition\nAll kinds of elements take same amount of time to be picked up, their difference only matters to calculate the no. of trips to be made.\nSo calculate the last index (and eventually time) upto which truck will need to go for each type of garbage.\n# Approach\nCalculate prefix travel array, travel[i] = time required to reach ith house starting from 0th house\nint M,P,G are the last house indices at which respective garbage will be found, for ex- if M=4 then metal garbage truck will not need to go further than the 4th house.\n\nAdd up each string length = total time for "collecting" garbage\nAdd up travel[M-1] travel[P-1] travel[G-1] for the time of travelling.\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# Please Upvote! If you like the explanation and solution, it means a lot! \uD83E\uDD70\n\n# Code\n```\nclass Solution\n{\npublic:\n bool contains(char z, string s)\n {\n for (int i = 0; i < s.size(); i++)\n {\n if (s[i] == z)\n return true;\n }\n return false;\n }\n int garbageCollection(vector<string> &garbage, vector<int> &travel)\n {\n int n = garbage.size(), m = travel.size();\n\n for (int i = 1; i < m; i++)\n travel[i] += travel[i - 1];\n\n int time = 0;\n int M = 0, P = 0, G = 0;\n\n for (int i = 0; i < n; i++)\n {\n if (contains(\'M\', garbage[i]))\n M = i;\n\n if (contains(\'P\', garbage[i]))\n P = i;\n\n if (contains(\'G\', garbage[i]))\n G = i;\n\n time += garbage[i].size();\n }\n\n if (M != 0)\n time += travel[M - 1];\n if (P != 0)\n time += travel[P - 1];\n if (G != 0)\n time += travel[G - 1];\n\n return time;\n }\n};\n``` | 2 | 0 | ['Array', 'String', 'Prefix Sum', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Easy Peasy implementation C++ | easy-peasy-implementation-c-by-ajay_1134-8nrb | 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 | ajay_1134 | NORMAL | 2023-05-11T02:47:13.778139+00:00 | 2023-05-11T02:47:13.778185+00:00 | 18 | 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 int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int n = garbage.size();\n int ans = 0;\n int m = 0, g = 0, p = 0;\n for(auto ch:garbage[0]){\n if(ch == \'M\') m++;\n else if(ch == \'G\') g++;\n else p++;\n }\n int cost_m = 0;\n int cost_g = 0;\n int cost_p = 0;\n for(int i=1; i<n; i++){\n cost_m += travel[i-1];\n cost_g += travel[i-1];\n cost_p += travel[i-1];\n int flag1=0, flag2=0, flag3=0;\n for(auto ch:garbage[i]){\n if(ch == \'M\'){\n flag1 = 1;\n m++;\n }\n else if(ch == \'G\'){\n flag2 = 1;\n g++;\n }\n else{\n flag3 = 1;\n p++;\n }\n }\n if(flag1){\n m += cost_m;\n cost_m = 0;\n }\n if(flag2){\n g += cost_g;\n cost_g = 0;\n }\n if(flag3){\n p += cost_p;\n cost_p = 0;\n }\n }\n ans = m + p + g;\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | 💯🚨Prefix Sum | JAVA | Very Easy | prefix-sum-java-very-easy-by-dipesh_12-wy07 | 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 | dipesh_12 | NORMAL | 2023-05-10T07:32:37.659513+00:00 | 2023-05-10T07:32:37.659545+00:00 | 332 | 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 garbageCollection(String[] garbage, int[] travel) {\n for(int i=1;i<travel.length;i++){\n travel[i]+=travel[i-1];\n }\n\n int p=0;\n int m=0;\n int g=0;\n int ans=0;\n for(int i=garbage.length-1;i>=0;i--){\n if(garbage[i].contains("P")){\n p=i;\n break;\n }\n }\n for(int i=garbage.length-1;i>=0;i--){\n if(garbage[i].contains("M")){\n m=i;\n break;\n }\n }\n for(int i=garbage.length-1;i>=0;i--){\n if(garbage[i].contains("G")){\n g=i;\n break;\n }\n }\n\n for(int i=0;i<garbage.length;i++){\n ans+=garbage[i].length();\n }\n\n if(p!=0){\n ans+=travel[p-1];\n }\n if(m!=0){\n ans+=travel[m-1];\n }\n if(g!=0){\n ans+=travel[g-1];\n }\n return ans;\n\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | Minimum Amount of Time to Collect Garbage Solution in C++ | minimum-amount-of-time-to-collect-garbag-6qns | 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 | The_Kunal_Singh | NORMAL | 2023-04-16T07:07:01.154194+00:00 | 2023-04-27T16:34:13.065099+00:00 | 253 | 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)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int i, j, k, time=0, idxg=-1, idxp=-1, idxm=-1;\n time = garbage[0].length();\n\n for(i=1 ; i<travel.size() ; i++)\n {\n travel[i] += travel[i-1];\n }\n\n for(i=1 ; i<garbage.size() ; i++)\n {\n for(j=0 ; j<garbage[i].length() ; j++)\n {\n if(garbage[i][j]==\'G\')\n {\n time += 1;\n idxg = i-1;\n }\n else if(garbage[i][j]==\'P\')\n {\n time += 1;\n idxp = i-1;\n }\n else if(garbage[i][j]==\'M\')\n {\n time += 1;\n idxm = i-1;\n }\n }\n cout<<time<<endl;\n }\n cout<<idxg<<" "<<idxp<<" "<<idxm<<endl;\n if(idxg>=0)\n time += travel[idxg];\n if(idxp>=0)\n time += travel[idxp];\n if(idxm>=0)\n time += travel[idxm];\n return time;\n }\n};\n\n```\n | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | EASY TO UNDERSTANDING || C++ | easy-to-understanding-c-by-tapabrata_007-7uoi | \n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) O(n^2)\n\n- Space complexity:\n Add your space complexity here, e.g. O(n) O(1)\n\n | tapabrata_007 | NORMAL | 2023-04-01T09:10:22.653131+00:00 | 2023-04-01T09:10:22.653167+00:00 | 381 | false | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution\n{\npublic:\n\tint garbageCollection(vector<string> &garbage, vector<int> &travel)\n\t{\n\t\tint answer = 0;\n\t\tint k = 0;\n\t\tint mSum = -1, gSum = -1, pSum = -1;\n\t\tfor (int i = 1; i < travel.size(); i++)\n\t\t{\n\n\t\t\ttravel[i] = travel[i - 1] + travel[i];\n\t\t}\n\t\tfor (auto x : garbage)\n\t\t{\n\t\t\tfor (auto c : x)\n\t\t\t{\n\t\t\t\tanswer++;\n\t\t\t\tif (c == \'M\')\n\t\t\t\t\tmSum = k;\n\t\t\t\tif (c == \'P\')\n\t\t\t\t\tpSum = k;\n\t\t\t\tif (c == \'G\')\n\t\t\t\t\tgSum = k;\n\t\t\t}\n\t\t\tk++;\n\t\t}\n\t\tanswer += ((gSum > 0) ? travel[gSum - 1] : 0);\n\t\tanswer += ((mSum > 0) ? travel[mSum - 1] : 0);\n\t\tanswer += ((pSum > 0) ? travel[pSum - 1] : 0);\n\t\treturn answer;\n\t}\n};\n``` | 2 | 0 | ['Array', 'Prefix Sum', 'C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | Faster Than 99% C++ Solution | faster-than-99-c-solution-by-anish25-l3q3 | 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 | Anish25 | NORMAL | 2023-01-11T13:04:57.204795+00:00 | 2023-01-11T13:04:57.204840+00:00 | 295 | 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- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int g=-1,p=-1,m=-1;\n int sum=0;\n for(int i=garbage.size()-1;i>=0;i--){\n sum+=garbage[i].size();\n if(g==-1){\n if(garbage[i].find(\'G\')!=-1){\n g=i;\n }\n }\n if(p==-1){\n if(garbage[i].find(\'P\')!=-1){\n p=i;\n }\n }\n if(m==-1){\n if(garbage[i].find(\'M\')!=-1){\n m=i;\n }\n }\n\n }\n int sm=0;\n for(int &i:travel){\n sm+=i;\n i=sm;\n }\n int ans=0;\n if(m>0)ans+=travel[m-1];\n if(g>0)ans+=travel[g-1];\n if(p>0)ans+=travel[p-1];\n \n return ans+sum;\n\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-amount-of-time-to-collect-garbage | ✅✅✅ very easy to understand solution using python arrays | very-easy-to-understand-solution-using-p-klf7 | \nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n travel.insert(0, 0)\n answer, trash = [0, 0, 0 | Najmiddin1 | NORMAL | 2023-01-03T03:40:40.251955+00:00 | 2023-01-03T03:40:40.252014+00:00 | 390 | false | ```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n travel.insert(0, 0)\n answer, trash = [0, 0, 0], [0, 0, 0]\n for i, v in enumerate(garbage):\n trash = [trash[0]+travel[i], trash[1]+travel[i], trash[2]+travel[i]]\n paper, glass, metal = v.count(\'P\'), v.count(\'G\'), v.count(\'M\')\n if paper:\n answer[0]+=paper+trash[0]\n trash[0]=0\n if glass:\n answer[1]+=glass+trash[1]\n trash[1]=0\n if metal:\n answer[2]+=metal+trash[2]\n trash[2]=0\n return sum(answer)\n``` | 2 | 0 | ['Python', 'Python3'] | 1 |
minimum-amount-of-time-to-collect-garbage | ✅ [Rust] 22 ms, fastest (100%) & concise solution using smart counting (with detailed comments) | rust-22-ms-fastest-100-concise-solution-4s7e4 | This solution employs a smart counting technique to calculate total time. It demonstrated 22 ms runtime (100.00%) and used 9.3 MB memory (25.00%). Time complexi | stanislav-iablokov | NORMAL | 2022-10-05T10:12:56.241348+00:00 | 2022-10-23T12:44:36.532864+00:00 | 67 | false | This [**solution**](https://leetcode.com/submissions/detail/815668646/) employs a smart counting technique to calculate total time. It demonstrated **22 ms runtime (100.00%)** and used **9.3 MB memory (25.00%)**. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**. Detailed comments are provided.\n\n**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n```\nuse std::iter::once;\n\nimpl Solution \n{\n pub fn garbage_collection(garbage: Vec<String>, travel: Vec<i32>) -> i32 \n {\n let mut total_time = 0;\n \n // [1] to detect the last house where each type of garbage\n // was seen, we use binary flags for \'P\', \'G\' and \'M\'\n let mut seen_garbage: i32 = 0;\n \n // [2] iterate over all houses & times in reverse order\n // using zipped iterator; in the cycle, we update data\n // on seen garbage types and count time depending on \n // the number of gabage units and seen garbage types\n // (notice the Rusty trick with \'once\' dummy iterator \n // to make both iterators have the same length)\n for (t, house) in travel.into_iter().rev().chain(once(0))\n .zip(garbage.into_iter().rev())\n {\n for b in house.bytes()\n {\n // [3] for P,G,M mod (%) operation gives 0,1,2\n seen_garbage |= 1 << (b % 5);\n \n // [4] if all garbage types were seen, no need to continue;\n // 8 = 0b00000111 (all 3 binary flags are set)\n if seen_garbage == 8 { break; }\n }\n \n total_time += house.len() as i32 + seen_garbage.count_ones() as i32 * t;\n }\n \n return total_time;\n }\n}\n``` | 2 | 0 | ['Rust'] | 0 |
minimum-amount-of-time-to-collect-garbage | easy python solution | easy-python-solution-by-sghorai-iu3r | \nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n counter = 0 \n garbageDict = {}\n for i | sghorai | NORMAL | 2022-09-30T03:02:31.414934+00:00 | 2022-09-30T03:02:31.414974+00:00 | 115 | false | ```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n counter = 0 \n garbageDict = {}\n for i in range(len(garbage)) : \n counter += len(garbage[i])\n if \'G\' in garbage[i] : \n garbageDict[\'G\'] = i\n if \'P\' in garbage[i] : \n garbageDict[\'P\'] = i\n if \'M\' in garbage[i] : \n garbageDict[\'M\'] = i\n \n for key in garbageDict.keys() : \n counter += sum(travel[:garbageDict[key]])\n \n return counter \n``` | 2 | 0 | ['Prefix Sum', 'Python', 'Python3'] | 0 |
minimum-amount-of-time-to-collect-garbage | JAVA solution | Prefix sum | Easy | java-solution-prefix-sum-easy-by-sourin_-qdmt | Please Upvote !!! (\u25E0\u203F\u25E0)\n\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int glassLastIdx = 0, pl | sourin_bruh | NORMAL | 2022-09-22T09:41:21.832660+00:00 | 2022-09-22T09:44:07.996312+00:00 | 146 | false | ### Please Upvote !!! **(\u25E0\u203F\u25E0)**\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int glassLastIdx = 0, plasticLastIdx = 0, metalLastIdx = 0;\n int totalTime = 0;\n\n for (int i = 0; i < garbage.length; i++) {\n // if m/g/p seen at current index, its the last index its been seen for now\n for (char c : garbage[i].toCharArray()) {\n if (c == \'P\') plasticLastIdx = i;\n if (c == \'M\') metalLastIdx = i;\n if (c == \'G\') glassLastIdx = i;\n\t\t\t\t// totalTime++; // +1 for each pick\n }\n // number of minutes taken = length of the strings for each garbage[i]\n totalTime += garbage[i].length();\n }\n \n // creating a prefix sum array for travel time\n for (int i = 1; i < travel.length; i++) {\n travel[i] += travel[i - 1];\n }\n \n // adding LastIndex - 1 because travel time of i-th house is given by travel[i - 1]\n totalTime += (metalLastIdx == 0) ? 0 : travel[metalLastIdx - 1];\n totalTime += (plasticLastIdx == 0) ? 0 : travel[plasticLastIdx - 1];\n totalTime += (glassLastIdx == 0) ? 0 : travel[glassLastIdx - 1];\n\n return totalTime;\n }\n}\n\n// TC: O(n), SC: O(1)\n``` | 2 | 0 | ['Prefix Sum', 'Java'] | 0 |
minimum-amount-of-time-to-collect-garbage | 𝗖++ | 𝗣𝗥𝗘𝗙𝗜𝗫 𝗦𝗨𝗠 | 𝗛𝗔𝗦𝗛𝗠𝗔𝗣 | c-prefix-sum-hashmap-by-nikhil1947-pg2w | ```\nclass Solution {\npublic:\n int garbageCollection(vector& garbage, vector& travel) {\n\t\n unordered_map mp;\n int ans=0;\n\t\t\n for | nikhil1947 | NORMAL | 2022-09-19T16:20:53.191423+00:00 | 2022-09-19T16:20:53.191472+00:00 | 258 | false | ```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n\t\n unordered_map<char,int> mp;\n int ans=0;\n\t\t\n for(int i=0;i<garbage.size();i++){\n for(int j=0;j<garbage[i].length();j++){\n mp[garbage[i][j]]=i;\n ans++;\n }\n }\n\t \n for(int i=1;i<travel.size();i++){\n travel[i]=travel[i]+travel[i-1];\n }\n\t\t\n\t\t\n if(mp[\'G\']!=0) ans+=travel[mp[\'G\']-1];\n if(mp[\'M\']!=0) ans+=travel[mp[\'M\']-1];\n if(mp[\'P\']!=0) ans+=travel[mp[\'P\']-1];\n \n return ans;\n }\n}; | 2 | 0 | ['C', 'Prefix Sum'] | 1 |
minimum-amount-of-time-to-collect-garbage | PYTHON FASTER THAN 97% !!!!! | python-faster-than-97-by-vansh-grover-o2gu | \nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n st=\'\'\n for xx in garbage:\n st+= | Vansh-Grover | NORMAL | 2022-09-07T19:25:23.995182+00:00 | 2022-09-07T19:25:23.995218+00:00 | 107 | false | ```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n st=\'\'\n for xx in garbage:\n st+=xx\n ans=0\n x=-1\n y=-1\n z=-1\n for i in range(len(garbage)):\n if "P" in garbage[i]:\n x=(i)\n if "G" in garbage[i]:\n y=(i)\n if "M" in garbage[i]:\n z=(i)\n for j in range(x):\n ans+=travel[j]\n for k in range(y):\n ans+=travel[k]\n for l in range(z):\n ans+=travel[l]\n ans+=len(st)\n return ans\n\n``` | 2 | 0 | ['Python'] | 1 |
minimum-amount-of-time-to-collect-garbage | C | c-by-tinachien-izx3 | Runtime: 185 ms, faster than 95.45% of C online submissions for Minimum Amount of Time to Collect Garbage.\nMemory Usage: 27.8 MB, less than 31.82% of C online | TinaChien | NORMAL | 2022-09-05T04:03:36.603821+00:00 | 2022-09-05T04:05:10.750119+00:00 | 48 | false | Runtime: 185 ms, faster than 95.45% of C online submissions for Minimum Amount of Time to Collect Garbage.\nMemory Usage: 27.8 MB, less than 31.82% of C online submissions for Minimum Amount of Time to Collect Garbage.\n```\nint garbageCollection(char ** garbage, int garbageSize, int* travel, int travelSize){\n int totalBag = 0;\n bool Mflag = false, Pflag = false, Gflag = false;\n int len;\n int ans = 0;\n \n for(int i = garbageSize -1; i >= 0; i-- ){\n len = strlen(garbage[i]); \n totalBag += len;\n for(int j = 0; j < len ;j++)\n if(!Mflag || !Pflag || !Gflag){\n for(int j = 0; j < len; j++){\n if(!Mflag && garbage[i][j]== \'M\'){\n Mflag = true; \n for(int k = i - 1; k >=0; k--){\n ans += travel[k];\n }\n }\n else if(!Pflag && garbage[i][j]== \'P\'){\n Pflag = true; \n for(int k = i - 1; k >=0; k--){\n ans += travel[k];\n }\n }\n else if(!Gflag && garbage[i][j]== \'G\'){\n Gflag = true; \n for(int k = i - 1; k >=0; k--){\n ans += travel[k];\n }\n }\n }\n }\n }\n \n ans += totalBag;\n return ans;\n}\n``` | 2 | 0 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Simple Java efficient solution beats 100% time and 100% memory | simple-java-efficient-solution-beats-100-7wpm | \nclass Solution {\n public int specialArray(int[] nums) {\n int x = nums.length;\n int[] counts = new int[x+1];\n \n for(int ele | sr1105 | NORMAL | 2020-10-04T04:59:10.876707+00:00 | 2020-10-07T01:38:37.236882+00:00 | 9,902 | false | ```\nclass Solution {\n public int specialArray(int[] nums) {\n int x = nums.length;\n int[] counts = new int[x+1];\n \n for(int elem : nums)\n if(elem >= x)\n counts[x]++;\n else\n counts[elem]++;\n \n int res = 0;\n for(int i = counts.length-1; i > 0; i--) {\n res += counts[i];\n if(res == i)\n return i;\n }\n \n return -1;\n }\n}\n``` | 94 | 3 | ['Java'] | 14 |
special-array-with-x-elements-greater-than-or-equal-x | Clean Python 3, O(sort) | clean-python-3-osort-by-lenchen1112-im17 | Concept is similar to H-index\nAfter while loop, we can get i which indicates there are already i items larger or equal to i.\nMeanwhile, if we found i == nums[ | lenchen1112 | NORMAL | 2020-10-04T04:02:07.020099+00:00 | 2020-10-05T11:26:31.902951+00:00 | 11,268 | false | Concept is similar to H-index\nAfter `while` loop, we can get `i` which indicates there are already `i` items larger or equal to `i`.\nMeanwhile, if we found `i == nums[i]`, there will be `i + 1` items larger or equal to `i`, which makes array not special.\nTime: `O(sort)`, can achieve `O(N)` if we use counting sort\nSpace: `O(sort)`\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n i = 0\n while i < len(nums) and nums[i] > i:\n i += 1\n return -1 if i < len(nums) and i == nums[i] else i\n```\n\nit can be faster by using binary search if list is already sorted.\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n left, right = 0, len(nums)\n while left < right:\n mid = left + (right - left) // 2\n if mid < nums[mid]:\n left = mid + 1\n else:\n right = mid \n return -1 if left < len(nums) and left == nums[left] else left\n``` | 93 | 1 | [] | 17 |
special-array-with-x-elements-greater-than-or-equal-x | ✅Detailed Explanation🔥2 Approaches🔥🔥Extremely Simple and effective🔥🔥🔥 Beginner-friendly🔥 | detailed-explanation2-approachesextremel-754k | \uD83C\uDFAFProblem Explanation:\nYou are given a list of integers nums and want to find the special number i for which here\'s exactly i numbers greater then o | heir-of-god | NORMAL | 2024-05-27T05:42:43.424375+00:00 | 2024-05-27T05:42:43.424425+00:00 | 11,494 | false | # \uD83C\uDFAFProblem Explanation:\nYou are given a list of integers ```nums``` and want to find the special number ```i``` for which here\'s exactly ```i``` numbers greater then or equal to ```i```. (If ```i``` doesn\'t exist then return -1)\n\n# \uD83D\uDCE5Input:\n- Integer array ```nums```\n\n# \uD83D\uDCE4Output:\nSpecial number ```i``` or -1 if it doesn\'t exist\n\n# \uD83E\uDDE0 Approach 1: Brute force with binary search\n\n# \uD83E\uDD14 Intuition\nOkay, so this problem has some points to think about before we start code something.\n- Firstly, in which range the speacial number ```i``` can be? If we take ```i=0``` then in array must be 0 elements which is impossible by constraints and if we take ```i=n+1``` then in the array must be ```n + 1``` number greater then or equal to ```n + 1``` but its length is ```n``` so this is impossible => ```i is in the range [1, n]```.\n- After we figured out this we can come up with very simple brute force solution - let\'s iterate through every possible i from 1 to n and calculate how many elements are greater than or equal to this ```i```. If we haven\'t found number like this then return -1.\n\n# \uD83D\uDCBB Coding \nThe main point in this solution is to how to find number of elements greater then or equal efficiently.\n- To find something efficiently we can use ```binary_search```. This is it, we don\'t interested in the order of elements in array so we can just sort it and implement binary search to find out how many elements are greater than or equal to ```i```\n- Let\'s talk about binary search and consider a simple example.\n - We don\'t want to find some element with binary search but rather number of elements greater or equal to ```i```.\n - So, in fact, what we are interested in is the index of first element in array which is greater or equal to ```i``` because if array sorted and ```nums[j] >= i``` then ```nums[j + 1] >= i```. (So we want to return the index of ```mid``` at the time we changed right pointer last time because we know for sure that ```nums[mid] >= cur_num```)\n- There\'s my image which exemplifies binary search algorithm for our situation.\n\n\n\n# \uD83D\uDCD2 Complexity\n- \u23F0 Time complexity: O(n*log n), we use sorting (nlogn) and also for every num in range [1, n] we call binary search which is also O(nlogn)\n- \uD83E\uDDFA Space complexity: O(1) no extra space is used\n\n# \uD83E\uDDD1\u200D\uD83D\uDCBB Code\n``` python []\nclass Solution:\n def specialArray(self, nums: list[int]) -> int:\n nums.sort()\n n: int = len(nums)\n\n def find_number_of_nums(cur_num) -> int:\n left: int = 0\n right: int = n - 1\n\n first_index: int = n\n while left <= right:\n mid: int = (left + right) // 2\n\n if nums[mid] >= cur_num:\n first_index = mid\n right = mid - 1\n else:\n left = mid + 1\n\n return n - first_index\n\n for candidate_number in range(1, n + 1, 1):\n if candidate_number == find_number_of_nums(candidate_number):\n return candidate_number\n\n return -1\n```\n``` C++ []\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n \n auto find_number_of_nums = [&](int cur_num) -> int {\n int left = 0, right = n - 1;\n int first_index = n;\n\n while (left <= right) {\n int mid = (left + right) / 2;\n\n if (nums[mid] >= cur_num) {\n first_index = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return n - first_index;\n };\n\n for (int candidate_number = 1; candidate_number <= n; ++candidate_number) {\n if (candidate_number == find_number_of_nums(candidate_number)) {\n return candidate_number;\n }\n }\n\n return -1;\n }\n};\n```\n``` JavaScript []\nvar specialArray = function(nums) {\n nums.sort((a, b) => a - b);\n let n = nums.length;\n\n function findNumberOfNums(curNum) {\n let left = 0, right = n - 1;\n let firstIndex = n;\n\n while (left <= right) {\n let mid = Math.floor((left + right) / 2);\n\n if (nums[mid] >= curNum) {\n firstIndex = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return n - firstIndex;\n }\n\n for (let candidateNumber = 1; candidateNumber <= n; ++candidateNumber) {\n if (candidateNumber === findNumberOfNums(candidateNumber)) {\n return candidateNumber;\n }\n }\n\n return -1;\n};\n```\n``` Java []\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n\n for (int candidateNumber = 1; candidateNumber <= n; ++candidateNumber) {\n if (candidateNumber == findNumberOfNums(nums, n, candidateNumber)) {\n return candidateNumber;\n }\n }\n\n return -1;\n }\n\n private int findNumberOfNums(int[] nums, int n, int curNum) {\n int left = 0, right = n - 1;\n int firstIndex = n;\n\n while (left <= right) {\n int mid = (left + right) / 2;\n\n if (nums[mid] >= curNum) {\n firstIndex = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return n - firstIndex;\n }\n}\n```\n``` C []\nint compare(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n\nint specialArray(int* nums, int numsSize) {\n qsort(nums, numsSize, sizeof(int), compare);\n\n int findNumberOfNums(int curNum) {\n int left = 0, right = numsSize - 1;\n int firstIndex = numsSize;\n\n while (left <= right) {\n int mid = (left + right) / 2;\n\n if (nums[mid] >= curNum) {\n firstIndex = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n\n return numsSize - firstIndex;\n }\n\n for (int candidateNumber = 1; candidateNumber <= numsSize; ++candidateNumber) {\n if (candidateNumber == findNumberOfNums(candidateNumber)) {\n return candidateNumber;\n }\n }\n\n return -1;\n}\n```\n\n\n# \uD83E\uDDE0 Approach 2: Suffix-sum with pretty logic\n\n# \uD83E\uDD14 Intuition\nThis approach is optimized but a little harder to understand but I\'m sure you will.\n- One of the main point to understand is that maximum value of ```i``` is ```n``` so this is doesn\'t matter whether we have ```2n``` or ```10000n```. For our solution this numbers are the same, they\'re both greater then any possible ```i``` so when we will calculate frequency we can calculate any number greater than ```n``` as frequency of ```n``` to reduce space complexity.\n- Okay, the next very important thing is that (was already said) if ```nums[j] > i``` so ```nums[j] > i - 1 ```. That means that if we will iterate ```i``` in reverse order then we can just use previous number of elements greater or equal and add only elements which is equal to this ```i``` (because step of ```i``` is -1). \n- So if at any moment we have situation where ```current_number_of_greater_or_equal == cur_index``` we want to return this ```cur_index``` and in case we\'ve reached the end of the loop and haven\'t returned any value then this special number doesn\'t exist and we want to return -1.\n\n# \uD83D\uDCBB Coding \nLet\'s code this up\n- Initialize array for frequency ```frequency``` (any number from [n, +inf] is the same as n so we will count this just to ```frequency[n]```).\n- Count every frequency with loop\n- Iterate ```i``` from n to one and for every number add to ```num_greater_equal``` number of numbers which are equal to current ```i``` and on every step check whether current candidate for special number is equal to number of greater or equal. \n\n# \uD83D\uDCD2 Complexity\n- \u23F0 Time complexity: O(n), we iterate from 1 to n which is O(n) and also every num in array to store frequency which is O(n)\n- \uD83E\uDDFA Space complexity: O(n), since we\'re creating array of size n + 1 (from 0 to n) which is O(n)\n\n# \uD83E\uDDD1\u200D\uD83D\uDCBB Code\n``` python []\nclass Solution:\n def specialArray(self, nums: list[int]) -> int:\n n: int = len(nums)\n frequency: list[int] = [0 for _ in range(n + 1)] # frequence[i] means there is frequence[i] elements equal to i\n\n for num in nums:\n frequency[min(n, num)] += 1\n\n num_greater_equal = 0\n for candidate_number in range(n, 0, -1):\n num_greater_equal += frequency[candidate_number]\n if candidate_number == num_greater_equal:\n return candidate_number\n\n return -1\n```\n``` C++ []\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n = nums.size();\n vector<int> frequency(n + 1, 0);\n\n for (int num : nums) {\n frequency[min(n, num)]++;\n }\n\n int num_greater_equal = 0;\n for (int candidate_number = n; candidate_number > 0; --candidate_number) {\n num_greater_equal += frequency[candidate_number];\n if (candidate_number == num_greater_equal) {\n return candidate_number;\n }\n }\n\n return -1;\n }\n};\n```\n``` JavaScript []\nvar specialArray = function(nums) {\n let n = nums.length;\n let frequency = new Array(n + 1).fill(0);\n\n for (let num of nums) {\n frequency[Math.min(n, num)]++;\n }\n\n let num_greater_equal = 0;\n for (let candidate_number = n; candidate_number > 0; --candidate_number) {\n num_greater_equal += frequency[candidate_number];\n if (candidate_number === num_greater_equal) {\n return candidate_number;\n }\n }\n\n return -1;\n};\n```\n``` Java []\nclass Solution {\n public int specialArray(int[] nums) {\n int n = nums.length;\n int[] frequency = new int[n + 1];\n\n for (int num : nums) {\n frequency[Math.min(n, num)]++;\n }\n\n int num_greater_equal = 0;\n for (int candidate_number = n; candidate_number > 0; --candidate_number) {\n num_greater_equal += frequency[candidate_number];\n if (candidate_number == num_greater_equal) {\n return candidate_number;\n }\n }\n\n return -1;\n }\n}\n```\n``` C []\nint specialArray(int* nums, int numsSize) {\n int n = numsSize;\n int* frequency = (int*)calloc(n + 1, sizeof(int));\n\n for (int i = 0; i < numsSize; ++i) {\n int num = nums[i];\n if (num >= n) {\n frequency[n]++;\n } else {\n frequency[num]++;\n }\n }\n\n int num_greater_equal = 0;\n for (int candidate_number = n; candidate_number > 0; --candidate_number) {\n num_greater_equal += frequency[candidate_number];\n if (candidate_number == num_greater_equal) {\n free(frequency);\n return candidate_number;\n }\n }\n\n free(frequency);\n return -1;\n}\n```\n\n## \uD83D\uDCA1I encourage you to check out [my profile](https://leetcode.com/heir-of-god/) and [Project-S](https://github.com/Heir-of-God/Project-S) project for detailed explanations and code for different problems (not only Leetcode). Happy coding and learning! \uD83D\uDCDA\n\n### Please consider *upvote* because I try really hard not just to put here my code and rewrite testcase to show that it works but explain you WHY it works and HOW. Thank you\u2764\uFE0F\n\n## If you have any doubts or questions feel free to ask them in comments. I will be glad to help you with understanding\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\n\n | 72 | 3 | ['Array', 'Binary Search', 'C', 'Sorting', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 13 |
special-array-with-x-elements-greater-than-or-equal-x | 🔥🔥 Every Step Explained! A detailed Explanation 😱😱 || 2 Methods | every-step-explained-a-detailed-explanat-oaw7 | Approach - 1\n\nLet\'s understand and solve this problem using an example!\n\nInput: nums = [1,2,5,3,4]\nOutput: 3\n\n\nSo, in the starting we will check!\n\n[1 | hi-malik | NORMAL | 2024-05-27T00:40:31.395551+00:00 | 2024-05-27T02:30:40.282252+00:00 | 18,745 | false | **Approach - 1**\n\nLet\'s understand and solve this problem using an example!\n```\nInput: nums = [1,2,5,3,4]\nOutput: 3\n```\n\nSo, in the starting we will check!\n```\n[1, 2, 5, 3, 4]\n ^\n```\nIs there one number, i.e. greater than or equals to **1**, **`No`** there are **5** numbers that are greater than or equals to **1**\n```\n[1, 2, 5, 3, 4]\n ^\n```\nIs there two numbers, which greater than or equals to **2**, **`No`** there are **4** numbers that are greater than or equals to **2**\n```\n[1, 2, 5, 3, 4]\n ^\n```\nIs there three numbers, which greater than or equals to **3**, **`YES`** there are **3** numbers that are greater than or equals to **3**\n\n> So we going to return **x = 3**\n\nLet\'s understand with one more example!\n```\nInput: nums = [2,3,4,1]\nOutput: 3\n```\nSo, in the starting we will check!\n```\n[2, 3, 4, 1]\n ^\n```\nIs there one number, which are greater than or equals to **1**, **`No`** there are **4** numbers that are greater than or equals to **1**\n```\n[2, 3, 4, 1]\n ^\n```\nIs there two numbers, which are. greater than or equals to **2**, **`No`** there are **3** numbers that are greater than or equals to **2**\n```\n[2, 3, 4, 1]\n ^\n```\nIs there three numbers, which are greater than or equals to **3**, **`No`** there are **2** numbers that are greater than or equals to **3**\n```\n[2, 3, 4, 1]\n ^\n```\nIs there four numbers, which are greater than or equals to **4**, **`No`** there are **1** numbers that are greater than or equals to **4**\n\n> So in this case we going to return **x = -1**\n\nAs you see, if all the numbers are greater then the length! The **length itself is the answer**! And if, not then we will going to **return -1**\n\nLet me explain you the code first and give you the pseudo code too!\n\n```pseudo\nfunction specialArray(nums):\n sort(nums in ascending order)\n n = length of nums\n \n if nums[0] >= n:\n return n\n \n for i from 1 to n:\n if nums[n - i] >= i AND (n - i - 1 < 0 OR nums[n - i - 1] < i):\n return i\n \n return -1\n```\n\n### Explanation:\n\n1. **Sort the Array:**\n - Sort the array `nums` in ascending order.\n\n2. **Check if the first element is greater than or equal to the length of the array:**\n - If the first element `nums[0]` is greater than or equal to `n` (length of the array), return `n`. This handles the edge case where all elements in the array are greater than or equal to the length of the array.\n\n3. **Iterate through the array to find the special number `x`:**\n - Iterate `i` from 1 to `n`.\n - For each `i`, check if the element at index `n - i` is greater than or equal to `i` AND either there is no previous element (`n - i - 1 < 0`) or the previous element is less than `i`.\n - If both conditions are true, return `i` as the special number.\n\n4. **Return -1 if no special number is found:**\n - If no special number `x` is found in the loop, return -1.\n\n**Now, Let\'s Code it UP :**\n\n**C++**\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end(), greater<int>());\n int n = nums.size();\n \n if (nums[n - 1] > n) return n;\n if (nums[0] == 0) return -1;\n\n int l = 0, r = n - 1, m = 0;\n while (l <= r) {\n m = l + (r - l) / 2;\n if (nums[m] > m) {\n l = m + 1;\n } else if (nums[m] < m) {\n r = m - 1;\n } else {\n return -1;\n }\n }\n return nums[m] > m ? m + 1 : m;\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n \n if (nums[0] >= n) return n;\n \n for (int i = 1; i <= n; i++) {\n if (nums[n - i] >= i && (n - i - 1 < 0 || nums[n - i - 1] < i)) {\n return i;\n }\n }\n \n return -1;\n }\n}\n```\n**PYTHON**\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n \n if nums[-1] > len(nums):\n return len(nums)\n \n if nums[0] == 0:\n return -1\n \n l = 0\n r = len(nums) - 1\n m = 0\n \n while l <= r:\n m = l + (r - l) // 2\n if nums[m] > m:\n l = m + 1\n elif nums[m] < m:\n r = m - 1\n else:\n return -1\n \n return m + 1 if nums[m] > m else m\n```\n\n___\nComplexity Analysis\n\n___\n\n* **Time Complexity :-** BigO(nlogn)\n* **Space Complexity :-** BigO(1)\n\n___\n___\n\n**Approach - 2**\n\n### Simple\n\n1. **Let\'s first Initialize:**\n - Input: `nums = {3, 5}`\n - `bucket` array is initialized with 1001 zeros.\n ```\n bucket: [0, 0, 0, 0, ..., 0]\n ```\nNow why array size is 1001, because it\'s given in constraints :\n\n\n \n2. **Now let\'s Count the Occurrences of each number in the array:**\n - Count occurrences of each number in `nums`.\n - `bucket[3] = 1`, `bucket[5] = 1`\n ```\n bucket: [0, 0, 0, 1, 0, 1, 0, ..., 0]\n ```\n \n3. **Now, lets count the size of array**\n - Set `total` to the length of `nums`.\n ```\n total = 2\n ```\n \n4. **Therefore, we going to Iterate Through Possible Values of `x`:**\n - Iterate `i` from 0 to 1000.\n \n5. **Check if Current `i` is the Special Number:**\n - For `i = 0`: `i != total` (2)\n - For `i = 1`: `i != total` (2)\n - For `i = 2`: `i == total` (2) \u2192 Return `i`\n ```\n if (i == total) return i;\n ```\n \n6. **In the end, before returning the Total, we going to Update it:**\n - Subtract the count of current number `i` from `total`.\n - For `i = 0`: `bucket[0] = 0` \u2192 `total = 2 - 0 = 2`\n - For `i = 1`: `bucket[1] = 0` \u2192 `total = 2 - 0 = 2`\n - For `i = 2`: `bucket[2] = 0` \u2192 `total = 2 - 0 = 2`\n - For `i = 3`: `bucket[3] = 1` \u2192 `total = 2 - 1 = 1`\n - For `i = 4`: `bucket[4] = 0` \u2192 `total = 1 - 0 = 1`\n - For `i = 5`: `bucket[5] = 1` \u2192 `total = 1 - 1 = 0`\n ```\n total -= bucket[i];\n ```\n \n7. **Return -1 if No Special Number is Found:**\n - If the loop completes without finding a special number, return -1.\n ```\n return -1;\n ```\n\n**Let\'s Code it UP:**\n\n**C++**\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int bucket[1001] = {0};\n for (int num : nums) {\n bucket[num]++;\n }\n int total = nums.size();\n for (int i = 0; i < 1001; i++) {\n if (i == total) {\n return i;\n }\n total -= bucket[i];\n }\n return -1;\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int[] bucket = new int[1001];\n for (int num : nums) {\n bucket[num]++;\n }\n int total = nums.length;\n for (int i = 0; i < 1001; i++) {\n if (i == total) {\n return i;\n }\n total -= bucket[i];\n }\n return -1;\n }\n}\n```\n**PYTHON**\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n bucket = [0] * 1001\n for num in nums:\n bucket[num] += 1\n total = len(nums)\n for i in range(1001):\n if i == total:\n return i\n total -= bucket[i]\n return -1\n```\n\n___\nComplexity Analysis\n\n___\n\n* **Time Complexity :-** BigO(N)\n* **Space Complexity :-** BigO(N) | 70 | 1 | ['C', 'Python', 'Java'] | 12 |
special-array-with-x-elements-greater-than-or-equal-x | C++ 6 different Solutions with analysis | c-6-different-solutions-with-analysis-by-hfip | just for fun\n\n// naive brute force O(N^2)\nbool check(int num, vector<int> &nums) { \n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] >= num) | midokura | NORMAL | 2020-10-05T01:57:14.422930+00:00 | 2020-10-05T02:00:51.694583+00:00 | 6,018 | false | just for fun\n```\n// naive brute force O(N^2)\nbool check(int num, vector<int> &nums) { \n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] >= num) \n return (nums.size() - i) == num; \n }\n return false;\n}\nint specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n for (int i = 0; i <= nums.size() ; i++) { // O(N)\n if (check(i, nums)) return i; // O(N)\n }\n return -1;\n}\n\n// just for fun short version O(N^2) O(NlogN + O(N) * (O(LogN) + O(N)))\nint specialArray(vector<int>& nums) {\n multiset<int> s(nums.begin(), nums.end()); // O(NlogN)\n for (int i = 1; i <= nums.size(); i++) { // O(N)\n auto itr = s.lower_bound(i); // O(LogN) it\'s sorted \n if (distance(itr, s.end()) == i) return i // O(N)\n // well multiset seems to be a rb tree which makes itr not a random-access iterator and therefore the time complexity for distance is linear \n }\n return -1;\n}\n \n// improved version, O(NlogN) (O(NLogN) + O(NLogN))\nint specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // O(NlogN)\n for (int i = 1; i <= nums.size(); i++) { // O(N)\n auto itr = lower_bound(nums.begin(), nums.end(), i); // O(LogN)\n if (distance(itr, nums.end()) == i) return i; // O(1)\n }\n return -1;\n}\n\n// improved version pro max O(NlogN) (O(NLogN) + (O(LogN) * O(LogN)) )\nint specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // O(NlogN)\n int l = 1, r = nums.size();\n while (l <= r) {\n int m = l + (r - l) / 2;\n auto itr = lower_bound(nums.begin(), nums.end(), m); // O(logN)\n int c = distance(itr, nums.end()); // O(1)\n if (c == m) return m;\n else if (c > m) l = m + 1;\n else r = m - 1;\n }\n return -1;\n}\n\n// my friend\'s solution @jmfer52 O(NLogN) (NlogN + OLogN)\nint specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // O(NlogN)\n const int N = nums.size();\n if (nums[0] >= N) return N;\n int l = 1, r = N - 1;\n while (l <= r) { // O(LogN) * O(1)\n int m = l + (r - l) / 2;\n if (nums[m] >= (N - m) && nums[m - 1] < (N - m)) return (N - m);\n else if (nums[m] >= (N - m)) r = m - 1;\n else l = m + 1;\n }\n return -1;\n\n// counting sort, O(N) 2 pass\nint specialArray(vector<int>& nums) {\n int count[102] = { 0 }, N = nums.size();\n for (int n : nums) count[min(n, N)]++;\n for (int i = N; i >= 0; i--) {\n count[i] = count[i + 1] + count[i];\n if (count[i] == i) return i;\n }\n return -1;\n}\n``` | 61 | 1 | [] | 8 |
special-array-with-x-elements-greater-than-or-equal-x | c++ use counting sort 0ms | c-use-counting-sort-0ms-by-escrowdis-ce35 | count the amount of numbers\n2. add the amount backward so we can know how many numbers are no less than the current index.\n\nExample:\n\ninput [0, 4, 3, 0, 4] | escrowdis | NORMAL | 2020-10-04T04:02:32.816846+00:00 | 2020-10-17T21:06:23.809202+00:00 | 8,910 | false | 1. count the amount of numbers\n2. add the amount backward so we can know how many numbers are no less than the current index.\n\nExample:\n```\ninput [0, 4, 3, 0, 4]\n\nindex 0 1 2 3 4 0 ... 1000 // the range defined in the question\nv [2, 0, 0, 1, 2, 0, ..., 0]\n# after accumulation\nv [5, 3, 3, 3, 2, 0, ..., 0]\n ^ // 3 numbers are no less than 3\n```\n\n\nImplementation:\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int v[102];\n memset(v, 0, sizeof v);\n for (const auto &n : nums) {\n ++v[n > 100 ? 100 : n];\n }\n for (int i = 100; i > 0; --i) {\n v[i] = v[i + 1] + v[i];\n if (v[i] == i)\n return i;\n }\n return -1;\n }\n};\n```\n\n[Update 1004]: change size of vector from ~1000 to ~100 based on the constraint that `1 <= nums.length <= 100`.\n[Update 1017]: Thanks to @aleksey12345 to let me know this is counting sort, a kind of sorting tech. | 54 | 2 | ['C', 'C++'] | 11 |
special-array-with-x-elements-greater-than-or-equal-x | Java O(nlogn) with easy explanation | java-onlogn-with-easy-explanation-by-ren-0ckz | Explanation: The number we are searching for is any number from zero to length of array. If we sort the array in ascending order, we can iterate through it from | renato4 | NORMAL | 2020-10-04T04:27:56.170793+00:00 | 2020-10-04T04:31:41.429044+00:00 | 5,950 | false | **Explanation**: The number we are searching for is any number from `zero` to `length of array`. If we sort the array in ascending order, we can iterate through it from left to right checking if the number of elements until the end and the current value meet the conditions of success. Those are:\n1. The number of elements from the current index until the end is less than or equal the current value in the array\n2. The number of elements from the current index until the end is greater than the previous value in the array (if it exists)\n\nWe are, essentially, cleverly checking if the current number of elements until the end is the answer.\n\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n for(int i = 0; i < nums.length; i++) {\n int n = nums.length-i;\n boolean cond1 = n<=nums[i];\n boolean cond2 = (i-1<0) || (n>nums[i-1]);\n if (cond1 && cond2) return n;\n }\n return -1;\n }\n\n}\n``` | 45 | 2 | [] | 7 |
special-array-with-x-elements-greater-than-or-equal-x | C++ Solution Using Binary Search O(n*log1000) Time and O(1) Space | c-solution-using-binary-search-onlog1000-fzgd | Time Complexity: O(n*log1000)\nSpace Complexity:O(1)\n\nclass Solution {\npublic:\n int solve(vector<int>& nums,int val){\n int count=0;\n for( | AvaraKedavra | NORMAL | 2021-06-25T04:03:35.612009+00:00 | 2021-06-25T04:05:30.733044+00:00 | 3,374 | false | **Time Complexity: O(n*log1000)**\n**Space Complexity:O(1)**\n```\nclass Solution {\npublic:\n int solve(vector<int>& nums,int val){\n int count=0;\n for(int i=0;i<nums.size();++i){\n if(nums[i]>=val){\n ++count;\n }\n }\n return count;\n }\n int specialArray(vector<int>& nums) {\n int low=0,high=1000;\n while(low<=high){\n int mid=(low+high)/2;\n int comp=solve(nums,mid);\n if(comp==mid){\n return comp;\n }\n if(comp>mid){\n low=mid+1;\n }\n else{\n high=mid-1;\n }\n }\n return -1;\n }\n};\n``` | 36 | 1 | ['C', 'Binary Tree'] | 4 |
special-array-with-x-elements-greater-than-or-equal-x | Python || Sort + Binary Search | python-sort-binary-search-by-nashvenn-ei47 | Please upvote if it helps. Thank you!\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n l, r = 0, len(nums) | nashvenn | NORMAL | 2022-04-07T08:37:12.060309+00:00 | 2022-04-07T08:38:06.918034+00:00 | 2,263 | false | **Please upvote if it helps. Thank you!**\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n l, r = 0, len(nums) - 1\n while l <= r:\n m = l + (r - l) // 2\n x = len(nums) - m\n if nums[m] >= x:\n if m == 0 or nums[m - 1] < x:\n return x\n else:\n r = m - 1\n else:\n l = m + 1\n return -1\n``` | 31 | 0 | ['Binary Tree', 'Python'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | [Java] Counting Sort - Two Pass Simple Code | java-counting-sort-two-pass-simple-code-z0gg7 | \nclass Solution {\n public int specialArray(int[] nums) {\n int[] count = new int[1001];\n for (int num : nums) {\n count[num]++;\n | markyu | NORMAL | 2020-10-04T04:07:58.177330+00:00 | 2020-10-04T20:16:25.467954+00:00 | 2,373 | false | ```\nclass Solution {\n public int specialArray(int[] nums) {\n int[] count = new int[1001];\n for (int num : nums) {\n count[num]++;\n }\n int number = nums.length;\n\t\t// the size of nums array is 100 at most\n for (int i = 0; i <= 100; i++) {\n if (number == i) {\n return i;\n }\n number -= count[i];\n }\n return -1;\n }\n}\n``` | 29 | 3 | [] | 7 |
special-array-with-x-elements-greater-than-or-equal-x | Sort/Radix sort + 2 binary search||0ms beats 100% | sortradix-sort-2-binary-search0ms-beats-ymr33 | Intuition\n Describe your first thoughts on how to solve this problem. \nSorting at first.\nthen do binary search.\n\n2nd approach uses radix sort with 32 bucke | anwendeng | NORMAL | 2024-05-27T02:04:23.429942+00:00 | 2024-05-27T06:11:38.355008+00:00 | 5,397 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSorting at first.\nthen do binary search.\n\n2nd approach uses radix sort with 32 buckets.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array `nums`. The most contribution to TC, i.e. $O(n\\log n)$. For reducing TC, it can be replaced by other sorting method.\n2. Use binary search to find the function `f(x)`= number of `nums[i]>=x` which has time complexity $O(\\log n)$\n3. Then proceed Binary search in the range [0, n] to find the unique zero for the function `g(x)=f(x)-x` if zero existing. this part computes `g(x)=f(x)-x` $O(\\log n)$ times, so TC= $O(\\log^2 n)$\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n +\\log^2 n )\\to O(n+\\log^2 n )$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)\\to O(|buckets|+n)$$\n# Code\n```\nclass Solution {\npublic:\n int n;\n //Use binary search to find number of nums[i]>=x\n inline int f(int x, vector<int>& nums){\n int i=lower_bound(nums.begin(), nums.end(), x)-nums.begin();\n return n-i;\n }\n inline int g(int x, vector<int>& nums){\n return f(x, nums)-x;\n }\n int specialArray(vector<int>& nums) {\n n=nums.size();\n sort(nums.begin(), nums.end());\n int l=0, r=n, m;\n \n // Binary search in the range [0, n]\n while (l <= r) {\n m = (l+r) / 2;\n int gm = g(m, nums);\n if (gm == 0) return m;\n else if (gm > 0) l = m+1;\n else r = m-1;\n }\n return -1; \n }\n};\n\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ using radix sort& 2 binary search O(n) time\n```\nclass Solution {\npublic:\n vector<int> bucket[32];\n void radix_sort(vector<int>& nums) {\n // 1st round\n for (int x : nums)\n bucket[x&31].push_back(x);\n int i = 0;\n for (auto &B : bucket) {\n for (auto v : B)\n nums[i++] = v;\n B.clear();\n }\n // 2nd round\n for (int x : nums)\n bucket[x>>5].push_back(x);\n i=0;\n for (auto &B : bucket) {\n for (auto v : B)\n nums[i++] = v;\n B.clear();\n }\n }\n int n;\n //Use binary search to find number of nums[i]>=x\n inline int f(int x, vector<int>& nums){\n int i=lower_bound(nums.begin(), nums.end(), x)-nums.begin();\n return n-i;\n }\n inline int g(int x, vector<int>& nums){\n return f(x, nums)-x;\n }\n int specialArray(vector<int>& nums) {\n n=nums.size();\n radix_sort(nums);\n int l=0, r=n, m;\n \n // Binary search in the range [0, n]\n while (l <= r) {\n m = (l+r) / 2;\n int gm = g(m, nums);\n if (gm == 0) return m;\n else if (gm > 0) l = m+1;\n else r = m-1;\n }\n return -1; \n }\n};\n\n\n``` | 28 | 5 | ['Binary Search', 'Sorting', 'Radix Sort', 'C++'] | 9 |
special-array-with-x-elements-greater-than-or-equal-x | [Java] Binary-Search easy solution. 100% faster. | java-binary-search-easy-solution-100-fas-1bnn | [IMP]: In this approach sorting is optional. Dosn\'t affect the time complexity.\nThe least/smallest value can be "0" , eg: [] empty and count==0.\nThe highest | omar_2077 | NORMAL | 2021-09-22T10:25:40.871919+00:00 | 2021-09-26T14:44:08.679444+00:00 | 2,093 | false | [IMP]: In this approach sorting is optional. Dosn\'t affect the time complexity.\nThe least/smallest value can be "0" , eg: [] empty and count==0.\nThe highest/maximum can be the "arr.length" ,e.g:[6,7,8,9] length=4 and >=4 count is also 4.\nElse the values lies in middle.\n\nUpvote if useful.\n\n```\nclass Solution {\n public int specialArray(int[] nums) {\n\t\t//Optional: sorting:\n\t\t//Arrays.sort(nums);\n //The least value can be 0 as the numbers are all 0 \n int start=0;\n //The maximum value can be the length as all numbers are greater than the \n //Length of the array and the value is inclusive\n int end=nums.length;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n int curr=count(nums,mid);\n //The count of ele >=mid and the mid are equal thus;\n if(curr==mid)\n {\n return mid;\n }\n //If the count of >=mid is less than the mid\n else if(curr<mid)\n {\n //decrease it;\n end=mid-1;\n }\n else if(curr>mid)\n {\n //Increase it;as the value count>mid and we need to reduce the count of values ">=" the mid\n start=mid+1;\n }\n }\n return -1;\n }\n public static int count(int[]arr,int t)\n {\n int c=0;\n for(int i:arr)\n {\n if(i>=t)\n {\n c++;\n }\n }\n return c;\n }\n}\n``` | 21 | 1 | ['Binary Tree', 'Java'] | 7 |
special-array-with-x-elements-greater-than-or-equal-x | [Java, Beats 100%] Two Binary Search methods and detailed explanation | java-beats-100-two-binary-search-methods-8i5g | First, we can think out if we sort the array, that will be easier for us to find the X. If the array is sorted, for nums[i] there will be len - i numbers that a | dongxiaoran | NORMAL | 2020-10-07T04:46:20.906191+00:00 | 2020-10-07T05:20:11.226448+00:00 | 3,062 | false | First, we can think out if we sort the array, that will be easier for us to find the X. If the array is sorted, for `nums[i]` there will be `len - i` numbers that are greater or equal to `nums[i]`.\nSo one idea by intution is to enumerate each `X` and find the first position that `nums[i] >= X` . Then check `len - i = X` to see whether it is the correct `X` to return.\n## 1. Binary Search to find the first position `>= nums[i]`\nSince the array is already sorted, we can use binary search instead of for loop.\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int len = nums.length;\n // enumerate all possible number i\n for (int x = 0; x <= nums[len - 1]; x++) {\n // find the first index that nums[idx] >= i\n int idx = findFirstGreaterOrEqual(x, nums);\n if (len - idx == x) {\n return x;\n }\n }\n return -1;\n }\n\n private int findFirstGreaterOrEqual(int target, int[] nums) {\n int left = 0;\n int right = nums.length - 1;\n while (left + 1 < right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] >= target) {\n right = mid;\n } else {\n left = mid;\n }\n }\n\n if (nums[left] >= target) {\n return left;\n }\n return right; // whether right >= target or right > target\n }\n}\n```\nBeats 89.04% time and 93.46% space.\n- Time Complexity: O((N+L)logN) where N is array length, L is data range.\n\t- Sort will take O(NlogN)\n\t- enumerate will have L iterations and O(logN) for each iteration.\n- Space Complexity: O(N)\n\t- Space complexity depending the sorting algorithm. Usually O(n).\n\n## 2. Binary Search to find the first position `nums[i] >= len - i`\nFor the first method we spend a lot of time to enumerate all possible `X` . However, we don\'t need to repeat binary search so many times. We can use another way to solve this problem.\nWe can direactly to find the `nums[i]` not the `X` . In method 1, we try to find the first position that **`nums[i] >= X` and `X = len - i`** . Thus here we can directly find first position `i` that **`nums[i] >= len - i`** .\nSimilar to classical binary search, but we need ensure **first index** by check whether `nums[i - 1] < len - i` when we find the number that `nums[i] >= len - i`.\nExample:\n```txt\nnums = {0, 0, 3, 3, 4}\n i\n\nWe should match this two condition at the same time:\n1. nums[i] >= len - i \u2705\n2. nums[i - 1] < len - i \u2705\n\nOtherwise:\nnums = {3, 3, 3, 4}\n\t\t i\n1. nums[i] >= len - i \u2705\n2. nums[i - 1] >= len - i \u274C\n\nNot first index.\n```\nJava Code:\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int len = nums.length;\n int left = 0;\n int right = len - 1;\n // binary search to find the first position that\n // nums[i] >= len - i and nums[i - 1] < len - i\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] >= len - mid) {\n // treat index 0 to avoid IndexOutOfBoundError\n if (mid == 0 || nums[mid - 1] < len - mid) { // correct index\n return len - mid;\n } else { // not the first position, shrink right bound\n right = mid - 1;\n }\n } else { // otherwisem, shrink the left bound to increase nums[mid]\n left = mid + 1;\n }\n }\n return -1;\n }\n}\n```\nBeats 100% time and 99.63% space.\n- Time Complexity: O(NlogN) where N is array length.\n\t- O(NlogN) for sort\n\t- O(logN) for one binary search.\n- Space Complexity: O(N)\n\t- Space complexity depending the sorting algorithm. Usually O(n).\n | 21 | 1 | ['Binary Tree', 'Java'] | 5 |
special-array-with-x-elements-greater-than-or-equal-x | [c++][faster than100% + brute force][easy understanding] | cfaster-than100-brute-forceeasy-understa-lu0p | TC: O(n^2) [Brute force]\n\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n for(int i=1;i<1000;i++){\n int cnt=0;\n | rajat_gupta_ | NORMAL | 2020-10-21T07:27:52.337668+00:00 | 2020-10-21T07:27:52.337700+00:00 | 1,941 | false | **TC: O(n^2) [Brute force]**\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n for(int i=1;i<1000;i++){\n int cnt=0;\n for(int j=0;j<nums.size();j++){\n if(nums[j]>=i) cnt++;\n }\n if(cnt==i) return i;\n }\n return -1;\n }\n};\n```\n**TC: O(n) [faster than 100.00%]**\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int arr[1001]={0};\n for(int num: nums) arr[num]++;\n int total=nums.size();\n for(int i=0;i<1001;i++){\n if(i==total) \n return i;\n total-=arr[i];\n }\n return -1;\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n | 19 | 0 | ['C', 'C++'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | Pythhon | Easy | pythhon-easy-by-khosiyat-z794 | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len | Khosiyat | NORMAL | 2024-05-27T05:23:20.432420+00:00 | 2024-05-27T05:23:20.432441+00:00 | 1,672 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/submissions/1269077168/?source=submission-ac)\n\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n \n for x in range(n + 1):\n # Count how many numbers are greater than or equal to x\n count = sum(1 for num in nums if num >= x)\n \n if count == x:\n return x\n \n return -1\n\n```\n | 18 | 1 | ['Python3'] | 4 |
special-array-with-x-elements-greater-than-or-equal-x | Its a simple Binary Search!! | its-a-simple-binary-search-by-ikapoor123-dwwa | Please Upvote \n# Intuition\n Describe your first thoughts on how to solve this problem. \nFind the smallest value of x that makes the array special by using bi | Ikapoor123 | NORMAL | 2024-05-27T00:40:54.764564+00:00 | 2024-05-27T06:11:04.791468+00:00 | 6,649 | false | # Please Upvote \n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind the smallest value of x that makes the array special by using binary search on the sorted array, minimizing the search space at each step based on the count of elements greater than or equal to the current midpoint value. This approach significantly reduces the time complexity compared to a linear search through all possible values of x\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The first step is to sort the input array nums. Sorting the array helps in the binary search process.\n- The binary search approach is used to find the value of x. The search is conducted within the range [0, nums.length], as this is the range of possible values for x.\n- Initialize left to 0 and right to nums.length. These represent the boundaries of the search space.\n- While left is less than right, continue the search:\nCalculate the mid index as the average of left and right.\nCount the number of elements in nums that are greater than or equal to the current mid value using the countGreaterOrEqual method.\nIf the count is less than mid, it means that mid is too large, so update right to mid.\nOtherwise, if the count is greater than or equal to mid, update left to mid + 1. This step ensures that we move towards finding the smallest x that satisfies the condition.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` java []\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n\n\n int start = 0;\n int end = nums.length;\n\n while(start<=end){\n\n int mid = start+ (end-start)/2;\n int ans = count(nums, mid);\n \n if(ans == mid) return mid;\n else if(ans>mid) start = mid+1;\n else end = mid-1;\n\n\n }\n \n \n return -1;\n }\n int count(int []nums, int target){\n int ans = 0;\n for(int num : nums){\n if(num>=target) ans++;\n \n }\n return ans;\n }\n\n\n}\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar specialArray = function(nums) {\n nums.sort((a, b) => a - b);\n\n let start = 0;\n let end = nums.length;\n\n while (start <= end) {\n let mid = start + Math.floor((end - start) / 2);\n let ans = count(nums, mid);\n\n if (ans === mid) return mid;\n else if (ans > mid) start = mid + 1;\n else end = mid - 1;\n }\n\n return -1;\n};\n\nfunction count(nums, target) {\n let ans = 0;\n for (let num of nums) {\n if (num >= target) ans++;\n }\n return ans;\n}\n```\n```C++ []\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n\n int start = 0;\n int end = nums.size();\n\n while (start <= end) {\n int mid = start + (end - start) / 2;\n int ans = count(nums, mid);\n\n if (ans == mid) return mid;\n else if (ans > mid) start = mid + 1;\n else end = mid - 1;\n }\n\n return -1;\n }\n int count(vector<int>& nums, int target) {\n int ans = 0;\n for (int num : nums) {\n if (num >= target) ans++;\n }\n return ans;\n }\n};\n```\n | 14 | 2 | ['Array', 'Binary Search', 'Sorting', 'C++', 'Java', 'JavaScript'] | 10 |
special-array-with-x-elements-greater-than-or-equal-x | ✅O(N) Solution || Easy-to-understand || explained | on-solution-easy-to-understand-explained-714a | \nclass Solution {\npublic:\n int specialArray(vector<int>& arr) {\n int n = arr.size();\n vector<int> count(1001,0); // initialize an array w | Arpit507 | NORMAL | 2022-10-07T09:30:33.861525+00:00 | 2023-01-15T10:14:24.027388+00:00 | 1,385 | false | ```\nclass Solution {\npublic:\n int specialArray(vector<int>& arr) {\n int n = arr.size();\n vector<int> count(1001,0); // initialize an array we know there can maximum 1000 elements\n for(int i = 0;i<n;i++){\n count[arr[i]]++; // store which element comes how many times into count at its index like--> if 4 comes 3 times then at the index 4 we store 3 in count array\n }\n int total = n; // total size of array\n for(int i = 0;i<1001;i++){ // traversing the array count which we have created uper (frequency of every number in original array)\n if(i == total) return i; // if we found ok this numberFrequency is equal to total(initially size of original array) of original array else we decrease total by one (because we have to check for smaller element)\n total -= count[i];\n }\n \n // if there are no such number such that number of element greater that is equal to that number then we return -1\n return -1;\n }\n};\n``` | 13 | 1 | ['C', 'C++'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | 100% Faster | Easy to Understand | Brute | 100-faster-easy-to-understand-brute-by-g-y2gb | Intuition\n\nAh, the "brute force" approch, where every problem looks like a nail and your solution is a massive hammer! The intuition here is to hit every poss | gameboey | NORMAL | 2024-03-20T22:19:21.372839+00:00 | 2024-05-27T04:09:44.416036+00:00 | 980 | false | # Intuition\n\nAh, the "brute force" approch, where every problem looks like a nail and your solution is a massive hammer! The intuition here is to hit every possible value of `x` with all your might, hoping to strike gold. It\'s like searching for a needle in a haystack by meticulously examining every blade of grass. Who needs finesse when you\'ve got sheer determiination and a whole lot of iterations right? So, grab your helmet, buckle up, and get ready to bulldoze through those constraints like a wrecking ball LMAO\n\n**In simple words**:\niterate through each possible value `x` from `0` to the length of the array `nums`. For each `x`, it checks if there are exactly `x` numbers in nums that are greater than or equal to `x`. If found, it returns `x`. If no such `x` is found, it returns `-1`.\n\n\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(1)\n\n# Code\n```Java []\nclass Solution {\n public int check(int[] nums, int idx) {\n int count = 0;\n for(int i = 0; i < nums.length; i++) {\n if(idx <= nums[i]) {\n count++;\n }\n }\n\n return count;\n }\n public int specialArray(int[] nums) {\n int count = 0;\n for(int i = 0; i <= nums.length; i++) {\n if(check(nums, i) == i) {\n return i;\n }\n }\n\n return -1;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int check(vector<int>& n, int idx) {\n int count = 0;\n for(int i = 0; i < n.size(); i++) {\n if(idx <= n[i]) {\n count++;\n }\n }\n\n return count;\n }\n int specialArray(vector<int>& nums) {\n int count = 0;\n for(int i = 0; i <= nums.size(); i++) {\n if(check(nums, i) == i) {\n return i;\n }\n }\n\n return -1;\n }\n};\n```\n```python []\nclass Solution:\n def check(self, nums: List[int], idx : int) -> int:\n count = 0\n for num in nums :\n if idx <= num :\n count += 1\n\n return count\n\n def specialArray(self, nums: List[int]) -> int:\n for i in range(len(nums) + 1) :\n if self.check(nums, i) == i :\n return i\n\n return -1\n```\n```JavaScript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar specialArray = function(nums) {\n const check = (nums, idx) => {\n let count = 0;\n for(let num of nums) {\n if(idx <= num) {\n count++;\n }\n }\n\n return count;\n }\n \n for(let i = 0; i <= nums.length; i++) {\n if(check(nums, i) === i) {\n return i;\n }\n }\n\n return -1;\n};\n```\n\n### If the constraints are too low, Brute is the way to go\n\n\n\n\n\n | 12 | 0 | ['Array', 'C++', 'Java', 'Python3', 'JavaScript'] | 5 |
special-array-with-x-elements-greater-than-or-equal-x | Easy Python Solution | easy-python-solution-by-a_bs-73k0 | \nIntuition:\n\nThe problem asks us to find a value x in the array (or potentially outside the array) such that there are exactly x elements in the array that a | 20250406.A_BS | NORMAL | 2024-05-27T02:14:34.142247+00:00 | 2024-05-27T02:14:34.142267+00:00 | 1,172 | false | \n**Intuition:**\n\nThe problem asks us to find a value `x` in the array (or potentially outside the array) such that there are exactly `x` elements in the array that are greater than or equal to `x`. We can solve this intuitively by iterating through possible values of `x` and checking if the condition holds.\n\n**Approach:**\n\n1. **Sort the array in descending order:** This ensures that elements greater than or equal to `x` will be positioned before `x` in the sorted array.\n2. **Iterate through possible values of `x` (from 0 to the length of the array + 1):**\n - Check if `x` is within the array bounds (`x <= len(nums)`).\n - If `x` is the last element (`x == len(nums)`), it automatically satisfies the condition as there are no more elements to compare.\n - Otherwise, compare `nums[x]` with `x`:\n - If `nums[x]` is less than `x`, it means there are more than `x` elements greater than or equal to `x` (violating the condition).\n - If the above conditions are met, check an additional constraint:\n - If `x` is not the first element (`x > 0`), ensure that `nums[x-1]` is still greater than or equal to `x`. This is because `x` shouldn\'t be the first element violating the condition.\n3. **Return `x` if all conditions are met, otherwise return -1.**\n\n**Complexity:**\n\n- **Time complexity:** O(n * log n) due to sorting the array. However, if the array is already sorted or the problem allows for in-place sorting algorithms with a lower average time complexity, the time complexity could be improved.\n- **Space complexity:** O(1) as we use constant additional space beyond the input array.\n\n**Code:**\n\n```python\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True) # Sort in descending order\n\n for x in range(len(nums) + 1):\n if x <= len(nums) and (x == len(nums) or nums[x] < x):\n return x if (x == 0 or nums[x - 1] >= x) else -1\n\n return -1\n```\n\n**Explanation:**\n\n1. We sort the input array `nums` in descending order using `nums.sort(reverse=True)`.\n2. We iterate through possible values of `x` from 0 to `len(nums) + 1` using a `for` loop.\n3. Inside the loop, we check two conditions:\n - `x <= len(nums)`: This ensures we don\'t go out of bounds when accessing elements in the array.\n - `(x == len(nums) or nums[x] < x)`: This combined condition handles both the last element (`x == len(nums)`) and other elements where there are more than `x` elements greater than or equal to `x`.\n4. If both conditions are met, we check an additional constraint using an `if` statement:\n - `(x == 0 or nums[x - 1] >= x)`: This ensures that if `x` is not the first element (`x > 0`), the previous element `nums[x-1]` should still be greater than or equal to `x`.\n5. If all conditions are met, we return `x`. Otherwise, we return -1.\n\n**Improvements:**\n\n- **Sorting:** If the problem allows for in-place sorting algorithms or if the array is already sorted, consider using these for potentially better time complexity.\n- **Alternative approaches:** Explore alternative approaches if the problem permits, such as using a hash table to track element frequencies and iterating through elements to find the desired `x`.\n\n | 11 | 0 | ['Python3'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | 100% C++ || BInary search || O(Nlog(N)) | 100-c-binary-search-onlogn-by-kunal_j-t3qr | Upvote if it helps...\uD83D\uDE43\t\n\t\n\tint specialArray(vector& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n for(in | Kunal_j | NORMAL | 2022-05-09T19:15:34.549475+00:00 | 2022-05-09T19:15:34.549517+00:00 | 857 | false | Upvote if it helps...\uD83D\uDE43\t\n\t\n\tint specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n for(int i = 0; i <= n; i++)\n {\n int temp = n;\n int l=0;\n int h=n-1;\n while(h>=l){\n int mid=l+(h-l)/2;\n if(nums[mid]>=i){\n temp=mid;\n h=mid-1;\n }\n else l=mid+1;\n }\n cout<<temp;\n if((n-temp)==i)return i;\n }\n return -1;\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\n\n | 11 | 0 | ['C', 'Binary Tree'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Binary Search Without Sorting the Array | binary-search-without-sorting-the-array-a5mnd | Shorting the array is unnecessary, as its complexity is nLog(n).\nwe can use binary search to point to a number and use linear search to find how many elements | debasishbsws | NORMAL | 2022-06-23T05:11:28.487283+00:00 | 2022-07-22T05:17:03.273205+00:00 | 935 | false | **Shorting the array is unnecessary**, as its complexity is **nLog(n)**.\nwe can use binary search to point to a number and use linear search to find how many elements are greater or equal to the current element\n#### Time Complexity: \n- O(nlog(n) ) where n is array length, \n- O(logN) for binary search. \n- O(n) for one linear Search.\n \nBeats 100% time\n\n\n \n public static int specialArray(int[] nums) {\n if (nums.length == 1 && nums[0] > 0) {\n return 1;\n }\n int start = 0, end = nums.length;\n while (start <= end) {\n int mid = (start + end) / 2;\n int countG = 0;\n //count how many elements are greater or equal to the current element\n for (int i : nums) {\n if (i >= mid) {\n countG++;\n }\n }\n if (countG > mid) {\n start = mid + 1;\n } else if (countG < mid) {\n end = mid - 1;\n } else {\n return mid;\n }\n }\n return -1;\n } | 10 | 0 | ['Binary Tree', 'Java'] | 4 |
special-array-with-x-elements-greater-than-or-equal-x | Java sort loop | java-sort-loop-by-hobiter-urz5 | \n public int specialArray(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n for (int i = -1; i < n - 1; i++) \n if | hobiter | NORMAL | 2020-10-04T04:03:10.796678+00:00 | 2020-10-11T04:19:37.058897+00:00 | 1,156 | false | ```\n public int specialArray(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n for (int i = -1; i < n - 1; i++) \n if (nums[i + 1] >= n - i - 1) { //possible solution\n if (i == -1 || nums[i] < n - i - 1) return n - i - 1; // n - i - 1 is the number after num[i], match condtion\n return -1; // impossible now. \n } \n return -1;\n }\n``` | 10 | 5 | [] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Binary Search || C++ | binary-search-c-by-hemant_1451-wosd | \n# Code\n\nclass Solution {\npublic:\n\tint specialArray(vector<int>& nums) {\n\t\tint i = 1, j = nums.size();\n\t\twhile(i <= j)\n {\n\t\t\tint mid = i | Hemant_1451 | NORMAL | 2023-01-07T05:37:01.679239+00:00 | 2023-01-07T05:37:01.679266+00:00 | 1,917 | false | \n# Code\n```\nclass Solution {\npublic:\n\tint specialArray(vector<int>& nums) {\n\t\tint i = 1, j = nums.size();\n\t\twhile(i <= j)\n {\n\t\t\tint mid = i + (j - i)/2, count=0;\n\t\t\tfor(int k = 0; k < nums.size(); k++)\n {\n\t\t\t\tif(nums[k] >= mid)\n count++;\t\t\n }\t\n\t\t\tif(count==mid)\n return mid;\n\t\t\telse if(count<mid)\n j = mid - 1;\n\t\t\telse\n i = mid + 1;\n\t\t}\n\t\treturn -1;\n\t}\n};\n``` | 8 | 0 | ['Binary Search', 'C++'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Python | Faster than 94% | 2 methods | O(nlogn) | python-faster-than-94-2-methods-onlogn-b-421o | Method 1 : Without Binary Search 29ms, Using Linear Search. No nested for loop\n\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n | ana_2kacer | NORMAL | 2021-10-18T07:46:53.273491+00:00 | 2022-04-04T20:23:06.348155+00:00 | 1,546 | false | Method 1 : Without Binary Search 29ms, Using Linear Search. No nested for loop\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n\n if n<=nums[0]:\n return n\n \n for i in range(1,n):\n count = n-i #counts number of elements in nums greater than equal i\n if nums[i]>=(count) and (count)>nums[i-1]:\n return count \n return -1\n\n```\nMethod 2: With using Binary Search 40ms.\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n\n if n<=nums[0]:\n return n\n \n #binary search\n start,end = 0,n\n \n while(start<=end):\n mid = (start+end)//2\n #index of middle element\n count = 0\n for i in range(0,n):\n if nums[i]>=mid:\n count = n-i\n #count+=1 could use this but will take more iterations then.\n break\n \n if count==mid:\n return count\n elif count<mid:\n end = mid-1\n else:\n start=mid+1 \n \n return -1\n```\n\n | 8 | 0 | ['Binary Tree', 'Python', 'Python3'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | [Python] Count and binary search | python-count-and-binary-search-by-rudy-rpym | ```python\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n left, mid, right = 0, 0, len(nums)\n while | rudy__ | NORMAL | 2020-10-12T05:50:55.043017+00:00 | 2020-10-12T05:50:55.043049+00:00 | 856 | false | ```python\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n left, mid, right = 0, 0, len(nums)\n while left <= right:\n mid = (left + right) // 2\n loc = bisect_left(nums, mid)\n if len(nums) - loc == mid: return mid\n elif len(nums) - loc > mid: left = mid + 1\n else: right = mid - 1\n return -1\n\t\n```` | 8 | 0 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | ✅ One Line Solution | one-line-solution-by-mikposp-db6v | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1 - Brute Force\nTime complexity: O(n^2) | MikPosp | NORMAL | 2024-05-27T09:12:41.419692+00:00 | 2024-05-27T09:12:41.419708+00:00 | 898 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1 - Brute Force\nTime complexity: $$O(n^2)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def specialArray(self, a: List[int]) -> int:\n return next((x for x in range(len(a)+1) if sum(v>=x for v in a)==x),-1)\n```\n\n# Code #2 - Sorting\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def specialArray(self, a: List[int]) -> int:\n return a.sort() or next((x for l,x,r in zip([-inf]+a,count(len(a),-1),a) if l<x<=r),-1)\n```\nSeen [here](https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1228703/Python-3-one-line)\n\n# Code #3 - Binary Search\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def specialArray(self, a: List[int]) -> int:\n return (f:=lambda x:x-sum(v>=x for v in a))(x:=bisect_left(range(len(a)+1),0,key=f))==0 and x or -1\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better) | 7 | 0 | ['Array', 'Binary Search', 'Sorting', 'Python', 'Python3'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | C++ Solution | Beats 100% users Solution | Easy to understand | Sorting +Binary Search | c-solution-beats-100-users-solution-easy-87zd | Intuition \n1.) Brute Force\n2.) Binary Search\n Describe your first thoughts on how to solve this problem. \n\n# Approach \nWe can do brute force but I have do | professor43236 | NORMAL | 2024-05-27T05:11:06.388855+00:00 | 2024-05-27T05:11:06.388882+00:00 | 1,540 | false | # Intuition \n1.) Brute Force\n2.) Binary Search\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \nWe can do brute force but I have done Binary Search to improve it.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n log n + log n) (sorting + binary search)\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 {\npublic:\n int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int l=1,r=100;\n while(l<=r)\n {\n int mid=(l+r)/2;\n int x=0;\n for(int i=0;i<nums.size();++i)\n x+=(nums[i]>=mid);\n // cout<<mid<<" "<<x<<endl;\n if(x==mid)\n return x;\n if(x>mid)\n l=mid+1;\n else\n r=mid-1;\n }\n return -1;\n }\n};\n``` | 7 | 0 | ['C++'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | Sort and Traverse || Beat 100% | sort-and-traverse-beat-100-by-cs_monks-fds7 | \n\n# Intuition\nTo solve this problem, we need to find a number x such that there are exactly x numbers in the array that are greater than or equal to x. We\'l | CS_MONKS | NORMAL | 2024-05-27T03:17:56.016236+00:00 | 2024-05-27T03:39:54.132840+00:00 | 1,784 | false | \n\n# Intuition\nTo solve this problem, we need to find a number x such that there are exactly x numbers in the array that are greater than or equal to x. We\'ll sort the array in decreasing order and iterate through it. If the element at index i is greater than or equal to i+1, we check if the next element is less than i+1. If it is, then i+1 satisfies the condition and is our answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array nums in decreasing order.\n2. Iterate through the sorted array.\n3. For each element at index i, check if it is greater than or equal to i+1.\n4. If it is, check if the next element is less than i+1.\n5. If the condition satisfies, return i+1 as the answer.\n6. If no such x is found, return -1.\n# Complexity\n- Time complexity:O(nlogn) \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```c++ []\n// 7 7 6 2 0 0 0 0 \n// 0 1 2 3 4 5 6 7\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n sort(rbegin(nums),rend(nums));\n int n = size(nums);\n for(int i=0;i<n;i++){\n if(nums[i]>=(i+1)){\n if(i==n-1 || nums[i+1]<i+1)return i+1;\n }\n }\n return -1;\n }\n};\n\n```\n```java []\n// In java array i sort decreasing order\n// then perform same operations in reverse\n// you can sort arry in non decreasing order using collections\n//Arrays.sort(numsInteger, Collections.reverseOrder())\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int i = 0; i < n; i++) {\n if (nums[i] >= (n - i)) {\n if (i == 0 || nums[i - 1] < (n - i)) {\n return n - i;\n }\n }\n }\n return -1;\n }\n}\n```\n```python3 []\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n n = len(nums)\n for i in range(n):\n if nums[i] >= (i + 1):\n if i == n - 1 or nums[i + 1] < (i + 1):\n return i + 1\n return -1\n```\n | 7 | 0 | ['Python', 'C++', 'Java'] | 4 |
special-array-with-x-elements-greater-than-or-equal-x | Cpp || beats 100 % || binary search | cpp-beats-100-binary-search-by-ribhav_32-oovs | \n# Approach\nUse of binary search\n\n# Complexity\n- Time complexity:\nO(logN)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int m; | ribhav_32 | NORMAL | 2023-01-13T06:39:07.037356+00:00 | 2023-01-13T06:39:07.037425+00:00 | 775 | false | \n# Approach\nUse of binary search\n\n# Complexity\n- Time complexity:\nO(logN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int m; \n int bin(int i, int j, int n, vector<int>&a)\n {\n if(i > j)\n return -1;\n\n m = (i+j)/2;\n\n if(a[m] >= n-m)\n {\n if(m == 0)\n return n;\n \n if(a[m-1] < n-m)\n return n-m;\n }\n\n if(a[m] > n-m)\n return bin(i,m-1,n,a);\n else\n return bin(m+1,j,n,a);\n }\n\n int specialArray(vector<int>& a) {\n int n = a.size();\n sort(a.begin(),a.end());\n return bin(0,n-1,n,a);\n // 0 0 1 4 6 9\n }\n};\n``` | 7 | 0 | ['Array', 'Binary Search', 'Sorting', 'C++'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | [JavaScript] 3 solutions from O(n^2) to O(n) | javascript-3-solutions-from-on2-to-on-by-6ao9 | SOLUTION 1\n\nStraight forward O(n^2) solution:\n\njs\nconst specialArray = (nums) => {\n for (let i = 0; i <= nums.length; ++i) {\n let c = 0;\n for (co | poppinlp | NORMAL | 2020-10-11T07:10:37.066698+00:00 | 2020-10-11T08:02:33.497982+00:00 | 934 | false | ## SOLUTION 1\n\nStraight forward O(n^2) solution:\n\n```js\nconst specialArray = (nums) => {\n for (let i = 0; i <= nums.length; ++i) {\n let c = 0;\n for (const num of nums) {\n num >= i && ++c;\n }\n if (c === i) return i;\n }\n return -1;\n};\n```\n\n## SOLUTION 2\n\nWe sort the `nums` first and add an edge at the end.\nThen, we traversal the array and try to find out the total count for every number.\nIf the count is smaller or equal to the number and bigger than the next number, then that\'s the answer.\n\n```js\nconst specialArray = (nums) => {\n nums.sort((a, b) => b - a);\n nums.push(-1);\n for (let i = 0, prev = 0; i <= nums.length; ++i) {\n if (nums[i] === nums[prev]) continue;\n if (i <= nums[prev] && i > nums[i]) return i;\n prev = i;\n }\n return -1;\n};\n```\n\n## SOLUTION 3\n\nWe use a fixed-length array to save the counting result.\nThen, check every possible number, sum and save the counts from large to small, and if the sum is equal to the number, that\'s the answer.\n\n```js\nconst specialArray = (nums) => {\n const len = nums.length;\n const count = new Uint8Array(len + 1);\n for (const num of nums) {\n ++count[num > len ? len : num];\n }\n for (let i = len, sum = 0; i >= 0; --i) {\n sum += count[i];\n if (sum === i) return i;\n }\n return -1;\n};\n``` | 7 | 0 | ['JavaScript'] | 3 |
special-array-with-x-elements-greater-than-or-equal-x | Javascript C++ | O(n) no sort | javascript-c-on-no-sort-by-shkvorets-frgr | \nvar specialArray = function(nums) {\n const freq = new Array(1001).fill(0);\n for(let n of nums)\n freq[n]++;\n \n for(let i=1000, cnt=0; i | shkvorets | NORMAL | 2020-10-04T04:57:14.101097+00:00 | 2020-10-04T04:57:14.101128+00:00 | 829 | false | ```\nvar specialArray = function(nums) {\n const freq = new Array(1001).fill(0);\n for(let n of nums)\n freq[n]++;\n \n for(let i=1000, cnt=0; i>=0; i--){\n cnt += freq[i];\n if(i==cnt) return i;\n }\n \n return -1;\n};\n```\n\n```\nint specialArray(vector<int>& nums) {\n\tvector<int> freq(1001, 0);\n\tfor(auto n: nums)\n\t\tfreq[n]++;\n\n\tfor(int i=1000, cnt=0; i>=0; i--){\n\t\tcnt+=freq[i];\n\t\tif(i==cnt) return i;\n\t}\n\treturn -1;\n}\n``` | 7 | 0 | ['C', 'JavaScript'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Easy C++ Solution Using Sorting and BS | easy-c-solution-using-sorting-and-bs-by-kgg1w | Video Explanation:\nhttps://youtu.be/gAQe-ODV9Ko?si=-er7wP9Qttm5n-hu\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition b | Atharav_s | NORMAL | 2024-05-27T06:18:33.072804+00:00 | 2024-05-27T06:18:33.072828+00:00 | 833 | false | # Video Explanation:\nhttps://youtu.be/gAQe-ODV9Ko?si=-er7wP9Qttm5n-hu\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this approach is to leverage the sorted order of the array to efficiently determine the count of elements greater than or equal to each possible value of x. By using lower_bound, we can quickly find the starting position of elements that meet or exceed x, and then simply count the number of such elements. This binary search-based method ensures that the solution is both efficient and easy to understand.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the Vector:\nThe first step is to sort the input vector nums. Sorting helps to efficiently find the first position where the value is greater than or equal to a given number using binary search.\n\nIterate Over Possible Values of x:\nIterate through possible values of x from 1 to the size of the vector (nums.size()).\n\nFind the Lower Bound:\nFor each possible value x, use the lower_bound function to find the first position in the sorted vector where the value is greater than or equal to x. lower_bound returns an iterator pointing to this position.\n\nCheck the Condition:\nCalculate the number of elements from this position to the end of the vector. If this number is equal to x, return x as the special integer.\n\nReturn -1 if No Special Integer Found:\nIf the loop completes without finding such an x, return -1, indicating that no special integer exists.\n\n# Complexity\n- Time complexity: $$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\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 int specialArray(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n for(int i=1;i<=nums.size();i++){\n auto it=lower_bound(nums.begin(),nums.end(),i);\n if(nums.end()-it==i) return i;\n }\n return -1;\n }\n};\n\n//3,5\n//i=1,it=3 5-3=2\n//i=2,it=3 5-3=2\n//i=3, it=5\n``` | 6 | 0 | ['C++'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | ✅ Easy Python Solution | With Explanation | easy-python-solution-with-explanation-by-ma2v | To solve this problem, we need to find a number x such that there are exactly x numbers in the array nums that are greater than or equal to x. The unique soluti | KG-Profile | NORMAL | 2024-05-27T03:52:16.234195+00:00 | 2024-05-27T03:52:16.234214+00:00 | 335 | false | To solve this problem, we need to find a number x such that there are exactly x numbers in the array nums that are greater than or equal to x. The unique solution x must satisfy this condition exactly, otherwise, we return \u22121.\n\nHere\'s a step-by-step approach to solve this problem:\n\n1. Sort the Array: Sorting the array makes it easier to count the number of elements greater than or equal to any given x.\n\n2. Check for Each Possible x: After sorting, for each possible x from 0 to the length of the array, we need to count how many elements are greater than or equal to x.\n\n3. Validate the Condition: For each x, verify if there are exactly x elements that are greater than or equal to x.\n\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n for x in range(1, len(nums) + 1):\n if nums[x-1] >= x and (x == len(nums) or nums[x] < x):\n return x\n return -1\n``` | 6 | 0 | ['Python3'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Easy to understand solution/Binary Search (99%/74%) | easy-to-understand-solutionbinary-search-0pcp | Code\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\n\nfunction bs(arr, target){\n let left = 0;\n let right = arr.length - 1;\n\n while(l | kubatabdrakhmanov | NORMAL | 2023-09-06T05:09:35.742023+00:00 | 2023-09-06T05:09:35.742054+00:00 | 559 | false | # Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\n\nfunction bs(arr, target){\n let left = 0;\n let right = arr.length - 1;\n\n while(left < right){\n let mid = Math.floor((left + right) / 2);\n\n if(arr[mid] >= target){\n right = mid;\n }else{\n left = mid+1;\n }\n }\n return left \n}\n\nvar specialArray = function(nums) {\n nums.sort((a,b) => a - b);\n\n for(let i = 0; i <= nums[nums.length-1]; i++){\n let res = bs(nums, i)\n if((nums.length - res) === i) return i\n }\n return -1\n};\n``` | 6 | 0 | ['Array', 'Binary Search', 'Sorting', 'JavaScript'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | [ Python ] ✅✅ Simple Python Solution Using Three Approach 🥳✌👍 | python-simple-python-solution-using-thre-fnad | If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n\t\n# Approach 1 : Using Binary Search\n# Runtime: 52 ms, faster | ashok_kumar_meghvanshi | NORMAL | 2022-07-25T07:05:25.685166+00:00 | 2024-05-27T13:45:57.041515+00:00 | 1,172 | false | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n\t\n# Approach 1 : Using Binary Search\n# Runtime: 52 ms, faster than 62.06% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n# Memory Usage: 13.8 MB, less than 62.52% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n\tclass Solution:\n\t\tdef specialArray(self, nums: List[int]) -> int:\n\n\t\t\tlow = 0\n\t\t\thigh = 100\n\n\t\t\twhile low <= high:\n\n\t\t\t\tmid = ( low + high ) //2\n\n\t\t\t\tcount = 0\n\n\t\t\t\tfor current_number in nums:\n\n\t\t\t\t\tif current_number >= mid:\n\n\t\t\t\t\t\tcount = count + 1\n\n\t\t\t\tif mid == count:\n\t\t\t\t\treturn mid\n\n\t\t\t\telif mid < count:\n\t\t\t\t\tlow = mid + 1\n\n\t\t\t\telif mid > count:\n\t\t\t\t\thigh = mid - 1\n\n\t\t\treturn -1\n\n# Approach 2 : Using Simple Loop\n# Runtime: 44 ms, faster than 50.57% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n# Memory Usage: 13.8 MB, less than 62.52% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n\n\tclass Solution:\n\t\tdef specialArray(self, nums: List[int]) -> int:\n\n\t\t\tnums = sorted(nums)[::-1]\n\n\t\t\tfor num in range(len(nums) + 1):\n\n\t\t\t\tcount = 0\n\n\t\t\t\tfor current_number in nums:\n\n\t\t\t\t\tif current_number >= num:\n\n\t\t\t\t\t\tcount = count + 1\n\n\t\t\t\tif count == num:\n\t\t\t\t\treturn num\n\n\t\t\treturn -1\n\n# Runtime: 54 ms, faster than 9.93% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n# Memory Usage: 16.5 MB, less than 86.58% of Python3 online submissions for Special Array With X Elements Greater Than or Equal X.\n\tclass Solution:\n\t\tdef specialArray(self, nums: List[int]) -> int:\n\n\t\t\tfor x in range(1 , 101):\n\n\t\t\t\tcount = 0\n\n\t\t\t\tfor num in nums:\n\n\t\t\t\t\tif num >= x:\n\n\t\t\t\t\t\tcount = count + 1\n\n\t\t\t\tif count == x:\n\n\t\t\t\t\treturn x\n\n\t\t\treturn -1\n\n\tTime Complexity : O(N^2)\n\tSpace Complexity : O(1)\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 6 | 0 | ['Binary Search', 'Binary Tree', 'Python', 'Python3'] | 2 |
special-array-with-x-elements-greater-than-or-equal-x | ✔ Simple and Easy using Binary Search in C++ | simple-and-easy-using-binary-search-in-c-n15f | \n int specialArray(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n \n for(int i=0;i<=nums.size();i++){\n \n | sarvesh_2-1 | NORMAL | 2021-07-15T09:00:36.887380+00:00 | 2021-07-15T09:00:36.887433+00:00 | 770 | false | ```\n int specialArray(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n \n for(int i=0;i<=nums.size();i++){\n \n int index=lower_bound(nums.begin(),nums.end(),i) - nums.begin();\n \n int count= (nums.size() - index);\n \n if(count==i){\n return i;\n }\n }\n return -1;\n }\n``` | 6 | 0 | ['C', 'Binary Tree', 'C++'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | [Java] Sort | java-sort-by-manrajsingh007-cmd4 | ```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for(int i = n - 1; i >= 0; i | manrajsingh007 | NORMAL | 2020-10-04T04:01:31.045608+00:00 | 2020-10-04T04:01:47.749876+00:00 | 794 | false | ```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for(int i = n - 1; i >= 0; i--) {\n while(i > 0 && nums[i] == nums[i - 1]) i--;\n if(i > 0) {\n if(n - i > nums[i - 1] && n - i <= nums[i]) return n - i;\n }\n }\n if(n == nums[0] || nums[0] > 0 && nums[0] - 1 == n) return n; \n return -1;\n }\n} | 6 | 1 | [] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | JAVA Solution Explained in HINDI(3 Approaches) | java-solution-explained-in-hindi3-approa-9nyh | https://youtu.be/Qnv_9N1aKSk\n\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvot | The_elite | NORMAL | 2024-05-27T16:25:50.101512+00:00 | 2024-05-27T16:25:50.101540+00:00 | 450 | false | https://youtu.be/Qnv_9N1aKSk\n\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\n# Subscribe:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 400\nCurrent Subscriber:- 394\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n \n int n = nums.length;\n int ct = 0;\n int[] freq = new int[n + 1];\n\n for (int el : nums) {\n freq[Math.min(n, el)]++;\n }\n\n for (int i = n; i >= 1; i--) {\n ct += freq[i];\n if (ct == i) {\n return i;\n }\n }\n\n return -1;\n }\n}\n\n```\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n int l = 1, r = n, ans = -1;\n\n while (l <= r) {\n int mid = (l + r) / 2;\n int sz = nums.length - lowerBound(nums, mid);\n\n if (sz == mid) {\n ans = sz;\n l = mid + 1;\n } else if (sz < mid) {\n r = mid - 1;\n } else {\n l = mid + 1;\n }\n }\n return ans;\n }\n\n private int lowerBound(int[] nums, int target) {\n int left = 0, right = nums.length;\n while (left < right) {\n int mid = (left + right) / 2;\n if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return left;\n }\n}\n\n```\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```\nclass Solution {\n public int specialArray(int[] nums) {\n Integer[] numsBoxed = new Integer[nums.length];\n for (int i = 0; i < nums.length; i++) {\n numsBoxed[i] = nums[i];\n }\n \n Arrays.sort(numsBoxed, Collections.reverseOrder());\n\n int ct = 0;\n int n = numsBoxed.length;\n\n for (int i = 0; i < n; i++) {\n if (numsBoxed[i] >= ct) {\n ct++;\n if (ct > numsBoxed[i]) {\n return -1;\n }\n } else {\n return ct;\n }\n }\n return n;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Simple O(N) time and O(1) auxiliary space solution beats 100% | simple-on-time-and-o1-auxiliary-space-so-8xi7 | Intuition\nThe maximum value of x (the return value) is the length of the array.\nThis allows us to refine our search for this return value to the range [0,N]. | MrMag | NORMAL | 2024-05-27T05:03:59.265995+00:00 | 2024-05-27T05:35:44.826102+00:00 | 48 | false | # Intuition\nThe maximum value of x (the return value) is the length of the array.\nThis allows us to refine our search for this return value to the range [0,N]. \n\nUsing this we are able to count the number of values greater or equal to than the each value between 0 and N. We then itterate over these until there is a value P that has P values greater than itself\n\nWe can do this with the original vector as we are able to add some value to the original values (we will be using 1001) such that the original values are able to be obtained but this arbitrary value can be used as a counter.\n\n# Approach\nWe extend the orginal vector by 1 element so that we are able to look at values from 0 to N (N+1 elements).\n\nWe then itterate through the original vector using the mod of the current element with 1001 to obtain the orginal value and adding 1001 to that index. if the original value exceeds the length of the array then 1001 is added to the last element.\n\nWe then reverse itterate through the array and add the previous (i+1)\ncounter value multiplied by 1001 to the current element. If the current index is equal to the current element/1001 then the index is returned.\n\nIf no value is returned at the end of the function we return -1.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1) additional space\n\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n // extend array by 1 element\n nums.push_back(0);\n for (short i = 0; i < nums.size()-1; i++)\n nums[min((int)nums.size()-1, nums[i]%1001)] += 1001;\n \n\n if (nums.size()-1 == nums.back()/1001) return nums.size()-1;\n for (short i = nums.size()-2; i > -1; i--)\n if (i == ((nums[i] += (1001 * (nums[i+1]/1001)))/1001)) return i;\n \n \n return -1;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Single pass check || beats 100% with C++ & 89% with java || python3 || typescript | single-pass-check-beats-100-with-c-89-wi-d7ec | Approach\nSingle pass check\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n# Explanation\n1. Sorting the Array:\n\n- Arrays.sort(nu | SanketSawant18 | NORMAL | 2024-05-27T04:09:20.853893+00:00 | 2024-05-27T04:09:20.853910+00:00 | 1,159 | false | # Approach\nSingle pass check\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n# Explanation\n1. **Sorting the Array:**\n\n- Arrays.sort(nums);\n- The array nums is sorted in ascending order. This step is crucial because it helps us efficiently check how many elements are greater than or equal to a given value.\n2. **Iterating Over Possible Values of x:**\n\n- for (int x = 1; x <= n; x++) {\n- We iterate over all possible values of x from 1 to n (the length of the array). This loop is to check each possible value of x.\n3. **Checking Conditions:**\n\n- if (nums[n - x] >= x && (n - x == 0 || nums[n - x - 1] < x)) {\n- For each x, we check if there are exactly x elements in the array that are greater than or equal to x.\n- nums[n - x] >= x: This checks if the x-th largest element (since the array is sorted in ascending order, the n - x index gives us the x-th largest element) is at least x.\n- (n - x == 0 || nums[n - x - 1] < x): This checks if the element before the x-th largest element is smaller than x or if we are at the start of the array. This ensures that exactly x elements are greater than or equal to x.\n4. **Returning the Result:**\n\n- return x;\n- If both conditions are met, x is returned as the special number.\nreturn -1;\n- If no such x is found after iterating through all possible values, -1 is returned.\n\n---\n\n```java []\nimport java.util.Arrays;\n\npublic class Solution {\n public int specialArray(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n\n for (int x = 1; x <= n; x++) {\n if (nums[n - x] >= x && (n - x == 0 || nums[n - x - 1] < x)) {\n return x;\n }\n }\n return -1;\n }\n}\n```\n```C++ []\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\nclass Solution {\npublic:\n int specialArray(std::vector<int>& nums) {\n std::sort(nums.begin(), nums.end());\n int n = nums.size();\n\n for (int x = 1; x <= n; ++x) {\n if (nums[n - x] >= x && (n - x == 0 || nums[n - x - 1] < x)) {\n return x;\n }\n }\n return -1;\n }\n};\n```\n```python3 []\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n \n for x in range(1, n + 1):\n count = 0\n for num in nums:\n if num >= x:\n count += 1\n if count == x:\n return x\n return -1\n```\n```Typescript []\nfunction specialArray(nums: number[]): number {\n nums.sort((a, b) => a - b);\n const n = nums.length;\n\n for (let x = 1; x <= n; x++) {\n if (nums[n - x] >= x && (n - x === 0 || nums[n - x - 1] < x)) {\n return x;\n }\n }\n return -1;\n}\n```\n | 5 | 0 | ['Array', 'Sorting', 'C++', 'Java', 'TypeScript', 'Python3'] | 4 |
special-array-with-x-elements-greater-than-or-equal-x | Beats 98.53 users.... Please upvote | beats-9853-users-please-upvote-by-aim_hi-xjkn | 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 | Aim_High_212 | NORMAL | 2024-05-27T02:02:39.500470+00:00 | 2024-05-27T02:02:39.500488+00:00 | 44 | 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```\n#lass Solution:\n# def specialArray(self, nums: #List[int]) -> int:\n \nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n \n if nums[-1] > len(nums):\n return len(nums)\n \n if nums[0] == 0:\n return -1\n \n l = 0\n r = len(nums) - 1\n m = 0\n \n while l <= r:\n m = l + (r - l) // 2\n if nums[m] > m:\n l = m + 1\n elif nums[m] < m:\n r = m - 1\n else:\n return -1\n \n return m + 1 if nums[m] > m else m\n \n``` | 5 | 0 | ['C', 'Python', 'Java', 'Python3'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | Java Detailed Binary Search Solution : | java-detailed-binary-search-solution-by-l48wj | Intuition\n First of all we will discuss Why Binary Search, even if the array is not sorted . Look here the array is not sorted but lemme tell you if we have s | hokteyash | NORMAL | 2023-08-07T21:01:40.362973+00:00 | 2023-08-07T21:09:33.414807+00:00 | 551 | false | # Intuition\n First of all we will discuss Why Binary Search, even if the array is not sorted . Look here the array is not sorted but lemme tell you if we have some range so we can definitely apply binary search on range because range is something which will always be in a sorted fashion for example suppose we have the range [5,20] so here 5 to 20 means 5,6,7,8,9,10...till 20 which is sorted in itself. So remember we can apply Binary Search on **range** too.\n\nNow, here the array is not sorted so what left? Can we figure out some range? Yes we definitely can !! Just observe this atleast we will be having 1 such element which will be greater than other elements , right? so our range will definitely start from 1 now what will be the ending point ? It will definitely be the maximum element of an array. Now we have the range [1,max_element] on which we can apply Binary Search.\n\nNow we can apply standard binary search algorithm here which consist of 4 steps :\nStep 1 : Calculate the mid point.\nStep 2 : If the mid meets the desire result we will simply returns it.\nStep 3 : a) If the mid has more greater number than obviously the numbers which are present before to mid will also has the greater numbers so in this situation it would be like a time waste to search in the left half , rather we can reduce our search space and will eliminate the left half and can jump to the right half.\nStep 4 : b) Otherwise we will simply jump to left part instead of searching in right half.\n\n# Approach\n Binary Search Algorithm.\n\n# Complexity\n- Time complexity:\n O(max)*logn\n\n- Space complexity:\n O(1)\n\n# Code\n```\nclass Solution {\n public int countPossibility(int []nums,int x){\n int cnt=0;\n for(int n:nums) if(n>=x) cnt++;\n return cnt;\n }\n public int specialArray(int[] nums) {\n int maxi=Integer.MIN_VALUE,start=1,mid=0;\n for(int x:nums) maxi=Math.max(maxi,x);\n int end = maxi;\n while(start<=end){\n mid = (start+end)/2;\n int check = countPossibility(nums,mid);\n if(check==mid) return mid;\n if(mid<check) start=mid+1;\n else end=mid-1;\n }\n return -1;\n }\n}\n``` | 5 | 0 | ['Array', 'Binary Search', 'Java'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | ✅Well Explained -->2 approaches--> Easy to Understand --> C++ code🔥 | well-explained-2-approaches-easy-to-unde-caku | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can iterate over all possible values of x and check if there are exactly x numbers i | sunny_6289 | NORMAL | 2023-05-12T09:02:14.868444+00:00 | 2023-05-12T10:06:45.093609+00:00 | 1,031 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can iterate over all possible values of x and check if there are exactly x numbers in nums that are greater than or equal to x. If we find such a value of x, we can return it as the answer. If we have checked all possible values of x and none of them satisfy the condition, we can return -1.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort the array in descending order.\n- Iterate over all possible values of x from 1 to n (the length of the array).\n- For each value of x, count the number of elements in the array that are greater than or equal to x. If the count is exactly x, return x as the answer.\n- If we have checked all possible values of x and none of them satisfy the condition, return -1.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Brute force Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(),nums.end(),greater<int>());\n for(int i=1;i<=n;i++){\n int cnt=0;\n for(int j=0;j<n;j++){\n if(nums[j]>=i){\n cnt++;\n }\n }\n if(cnt==i){\n return i;\n }\n }\n return -1;\n }\n};\n```\n# Please Upvote if it was helpful\u2B06\uFE0F\n# Optimized Approach (Using Binary Search)\n# Intuition\n\nwe can optimize the time complexity of the solution from O(n^2) to O(n log n) by using binary search instead of iterating over all possible values of x.\n# Approach\n- Sort the array in non-increasing order.\n- Set the left pointer to 1 and the right pointer to n (the length of the array).\n- While the left pointer is less than or equal to the right pointer:\n - Set the mid pointer to the average of the left and right pointers.\n - Count the number of elements in the array that are greater than or equal to mid. If the count is less than mid, set the right pointer to mid-1. If the count is greater than or equal to mid, set the left pointer to mid+1.\n- If we have checked all possible values of x and none of them satisfy the condition, return -1. Otherwise, return the value of mid.\n\n\nThe key idea behind this algorithm is that the number of elements in the array that are greater than or equal to x is a monotonic function of x. Therefore, we can use binary search to find the smallest value of x such that there are exactly x elements in the array that are greater than or equal to x.\n# Code\n```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(),nums.end(),greater<int>());\n int left=1,right=n;\n \n while(left<=right){\n int mid=(left+right)/2;\n int cnt=0;\n for(int i=0;i<n;i++){\n if(nums[i]>=mid){\n cnt++;\n }else{\n break;\n }\n }\n if(cnt<mid){\n right=mid-1;\n }else{\n left=mid+1;\n }\n }\n \n if(right<1 || nums[right-1]<right){\n return -1;\n }\n int cal=0;\n for(int i=0;i<n;i++){\n if(nums[i]>=right){\n cal++;\n }\n }\n if(cal==right){\n return right;\n }else{\n return -1;\n }\n return right;\n }\n};\n```\n# Time Complexity \n$$O(nlogn)$$\n# Space Complexity\n$$O(1)$$\n\n# One Upvote can be really encouraging\u2B06\uFE0F | 5 | 0 | ['Array', 'Binary Search', 'Sorting', 'C++'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | Java solution in Binary Search | java-solution-in-binary-search-by-kashif-1y9p | \n\n# Code\n\nclass Solution {\n public int specialArray(int[] nums) {\n int high=nums.length;\n int low=0;\n while(low<=high){\n | Kashif_Rahman | NORMAL | 2022-10-15T18:51:35.408642+00:00 | 2022-10-15T18:51:35.408678+00:00 | 580 | false | \n\n# Code\n```\nclass Solution {\n public int specialArray(int[] nums) {\n int high=nums.length;\n int low=0;\n while(low<=high){\n int mid=low+(high-low)/2;\n int count=0;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>=mid) count++;\n }\n if(count==mid) \n return mid;\n if(count>mid)\n low=mid+1;\n else\n high=mid-1;\n }\n return -1;\n }\n}\n``` | 5 | 0 | ['Java'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | [JS] O(1) Space | Binary Search Explained | js-o1-space-binary-search-explained-by-h-kplz | TL-DR: Plain Solution \n\n\nvar specialArray = function(nums) {\n const N = nums.length; let l = 0, r = N-1; \n \n nums.sort((a,b) => a - b);\n \n | hugotannus | NORMAL | 2022-09-03T01:14:49.735224+00:00 | 2022-09-29T17:40:42.129800+00:00 | 470 | false | ## TL-DR: **Plain Solution** \n\n```\nvar specialArray = function(nums) {\n const N = nums.length; let l = 0, r = N-1; \n \n nums.sort((a,b) => a - b);\n \n while(l < r - 1){\n let mid = l + ((r - l) >> 1);\n let x = N - mid;\n \n if(nums[mid] >= x && x > nums[mid-1]) return x;\n \n nums[mid] < x ? l = mid : r = mid;\n }\n \n let x = N - l;\n\treturn nums[l] >= x ? x : -1;\n};\n```\n\n---\n\n## **Explanation**\n\nInstead of counting the amount of *"numbers in nums that are greater than or equal to x"*, once we sort `nums`, we can understand `x` as being the *relative distance* of the **current index** to the end of `nums`, ie `x` equals to `N - index`, where `N` is the length of `nums`.\n\nThen we will assume that if `nums[index]` is greater or equal to `x`, so we have a ***potential solution***, as we can only know that we have **at least** `x` numbers that are greater or equal to `x` until this point; than the next step is to verify if the previous number in `nums` gives us the condition to be sure that `x` is our desired solution.\n\nLet\'s see some edge cases, starting from the **Example 3** of question statement:\n\n```\n[0,4,3,0,4] === sorts to ==> [0,0,3,4,4]\n```\n\nSuppose our algorithm reaches the state where our `index` is equal to `2`; then, as our `N` is `5`, so we have to verify if `3` is a possible solution for `x`; as `nums[2]` equals to `3`, so the value `3` is a *potential solution*; as the previous value `nums[1]` (`0`) is lower than `3`, so now we can say that there is **exaclty 3** numbers in `nums` that is **greater or equal to 3**. So the answer is `3`.\n\nNow, lets try a case where we can not find a solution. Suppose we have the sorted array below:\n\n```\n[0,3,6,7,7]\n```\n\nHere our `N` is also `5`, and the binary search reached the index `2` again. So, we have `3` as being a *potential solution* for `x`, as `nums[2]` (`6`) is greater than `3`. But when we look to the previous number, we have that `nums[1]` is also `3`; therefore, in place of having ***exactly 3 numbers greater or equal to 3***, we have **4 numbers** instead, so `3` is **not** the solution we were looking for!\n\nAnd now, as `3` is at position `1` and would not attend the requirements because it is lower than a `x` with value `4`, we can garantee that any previous number will also not be a potential solution; at same time, we know that for any number after index `2` there\'s always at least one more number that would be greater or equal to any *potential* `x`. So, the answer should be `-1`.\n\nBellow, the solution with comments to elucidate how to build the binary search properly for this problem.\n\n```\nvar specialArray = function(nums) {\n const N = nums.length;\n \n nums.sort((a,b) => a - b);\n \n // `r` should always correspond a valid `nums` index\n let l = 0, r = N-1; \n \n // as we depend of the previous element of the array\n // to take the correct decision, we want to garantee\n // that the search will end with `l` strictly lower\n // than `r`.\n while(l < r - 1){\n let mid = l + ((r - l) >> 1);\n let x = N - mid;\n \n // when we find a number at sorted array that is\n // greater or equal to `x` and `x` is greater than\n // previous value, than we found our answer.\n if(nums[mid] >= x && x > nums[mid-1]) return x;\n \n nums[mid] < x ? l = mid : r = mid;\n }\n \n // at the end of binary search, if the lower value\n // atends to the statement requirements, than we\n // found the `x` we were looking for.\n let x = N - l;\n if(nums[l] >= x) return x;\n \n return -1;\n};\n```\n | 5 | 0 | ['Binary Tree', 'JavaScript'] | 1 |
special-array-with-x-elements-greater-than-or-equal-x | C++ || Sorting | c-sorting-by-aditya_pratap1-h2me | \nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n \n int n = nums.size();\n \n sort(nums.begin(),nums.end()); | aditya_pratap1 | NORMAL | 2022-04-07T17:24:06.731404+00:00 | 2022-04-07T17:24:06.731439+00:00 | 240 | false | ```\nclass Solution {\npublic:\n int specialArray(vector<int>& nums) {\n \n int n = nums.size();\n \n sort(nums.begin(),nums.end());\n \n for(int i=0;i<n;i++){\n int len = n - i; // len gives the number of elements greater than\n\t\t\t\t\t\t\t\t\t\t\t\t // or equal to nums[i]...i.e the number of elements on its right\n if(\n len <= nums[i] && \n (i == 0 || len > nums[i-1])\n ){\n return len;\n }\n }\n \n return -1;\n }\n};\n``` | 5 | 0 | ['C', 'Sorting'] | 0 |
special-array-with-x-elements-greater-than-or-equal-x | [java] brute-force , binary search approach | java-brute-force-binary-search-approach-o757y | IF U DO LIKE SOLUTION PLEASE UPVOTE IT\nHere we can solve this problem using two approaches\n1. brute force approach\n2. binary search\n\nbrute force approach : | salmanshaikssk007 | NORMAL | 2021-11-30T04:13:02.075809+00:00 | 2021-11-30T05:29:05.490212+00:00 | 445 | false | **IF U DO LIKE SOLUTION PLEASE UPVOTE IT**\nHere we can solve this problem using two approaches\n1. brute force approach\n2. binary search\n\nbrute force approach : \n\nHere we point two pointers at start of the array and iterate through the loop for the solution\ntime complexity - O(n2)\n\nBinary search approach\nHere we get left most index of the every number from 1 to 100 with in the array so that we get the optimal solution\nTime complexity - O(nlogn)\n\nBrute force solution \n```\nclass Solution {\n\n public int specialArray(int[] nums) {\n \n int count=0 ; // Intializing count to zero\n for(int i = 0 ; i<= 100 ; i++){\n for(int j = 0 ; j < nums.length ; j++){\n if(i <= nums[j]){ //updating the count\n count++;\n }\n }\n if(count == i) { //check for the condition\n return i;\n }\n count = 0 ;\n }\n return -1;\n }\n}\n```\n\nBinary search solution :\n\n```\nclass Solution {\n\n public int specialArray(int[] nums) {\n \n Arrays.sort(nums);\n for(int i = 0 ; i < 101 ; i++){\n if(i == nums.length-leftMostIndex(nums,i)) return i ;\n }\n return -1;\n }\n\t// function to get left most value\n private int leftMostIndex(int[] nums ,int target){\n int left = 0 , right = nums.length-1;\n while(left<=right){\n int mid = left + (right-left)/2;\n if(nums[mid]>=target){\n right = mid-1;\n }else if(nums[mid]<target){\n left = mid+1;\n }\n }\n return left ; //we can return either left or mid as both pointers point same index\n }\n}\n``` | 5 | 0 | ['Binary Tree', 'Java'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.