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
n-repeated-element-in-size-2n-array
simple c++ solution using maps faster than 93.8%
simple-c-solution-using-maps-faster-than-xg1w
\n\nclass Solution {\npublic:\n int repeatedNTimes(vector& A) {\n unordered_map m;\n int ans;\n int n=A.size();\n for(int i=0; i1
zephyr7047
NORMAL
2020-04-27T15:04:12.700300+00:00
2020-04-27T15:06:37.040413+00:00
356
false
```\n\n```class Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n unordered_map<int ,int> m;\n int ans;\n int n=A.size();\n for(int i=0; i<n ; i++)\n {\n m[A[i]]++;\n if(m[A[i]]>1){\n //see that there are n+1 unique no so only one no is repeated\n ans=A[i];\n break;\n }\n \n }\n return ans;\n }\n};```
3
0
['C', 'C++']
2
n-repeated-element-in-size-2n-array
Use count() | Python3 | Super Easy!
use-count-python3-super-easy-by-gsethi24-z1ma
\n for x in A: \n if A.count(x)>1: \n return x\n
gsethi2409
NORMAL
2020-03-25T18:41:00.708505+00:00
2020-03-25T18:41:00.708550+00:00
497
false
```\n for x in A: \n if A.count(x)>1: \n return x\n```
3
0
['Python', 'Python3']
1
n-repeated-element-in-size-2n-array
[Python] Very simple, 212ms (faster than 92.45%)
python-very-simple-212ms-faster-than-924-zavq
Intuition:\n\nIterate through all numbers and keep track of which ones have been seen.\nAs soon as we encounter a number that has been seen before, return that
j95io
NORMAL
2020-03-09T18:29:49.981095+00:00
2020-03-17T12:28:09.956115+00:00
279
false
**Intuition:**\n\nIterate through all numbers and keep track of which ones have been seen.\nAs soon as we encounter a number that has been seen before, return that number.\n\n**Code:**\n\n```\ndef repeatedNTimes(self, A: List[int]) -> int:\n\n\tseen = set()\n\tfor num in A:\n\t\tif num in seen:\n\t\t\treturn num\n\t\tseen.add(num)\n```\n\n**Complexity:**\n_O_(n), because for each of potentially n/2 iterations:\n- look up in set: O(1)\n- addition to set: O(1)\n\nSource for time complexity of set operations: [Python Wiki](https://wiki.python.org/moin/TimeComplexity)\n\nNote that here the worst case (iterating through half the array until finding a duplicate) is statistically extremely unlikely.\n\n
3
0
['Python', 'Python3']
1
n-repeated-element-in-size-2n-array
Go 94% O(N) time O(1) space solution
go-94-on-time-o1-space-solution-by-tjuco-vvb2
go\nfunc repeatedNTimes(A []int) int {\n for i := 0; i < len(A); i += 2 {\n if A[i] == A[i+1] {\n return A[i]\n }\n }\n if A[0
tjucoder
NORMAL
2020-01-29T08:26:05.154269+00:00
2020-01-29T08:27:30.813066+00:00
245
false
```go\nfunc repeatedNTimes(A []int) int {\n for i := 0; i < len(A); i += 2 {\n if A[i] == A[i+1] {\n return A[i]\n }\n }\n if A[0] == A[2] || A[0] == A[3] {\n return A[0]\n }\n return A[1]\n}\n```
3
0
['Go']
1
n-repeated-element-in-size-2n-array
From O(n) to O(1) Solutions in Rust
from-on-to-o1-solutions-in-rust-by-wfxr-7vcl
Solution 1: O(n) space, O(n) time\nrust\npub fn repeated_n_times(A: Vec<i32>) -> i32 {\n\tlet mut T = [false; 10000];\n\tfor a in A {\n\t\tT[a as usize] ^= true
wfxr
NORMAL
2019-12-27T06:57:35.954299+00:00
2019-12-27T06:58:07.159554+00:00
136
false
**Solution 1: O(n) space, O(n) time**\n```rust\npub fn repeated_n_times(A: Vec<i32>) -> i32 {\n\tlet mut T = [false; 10000];\n\tfor a in A {\n\t\tT[a as usize] ^= true;\n\t\tif !T[a as usize] {\n\t\t\treturn a;\n\t\t}\n\t}\n\tunreachable!()\n}\n```\n\n**Solution 2: O(1) space, O(n) time**\n```rust\npub fn repeated_n_times(A: Vec<i32>) -> i32 {\n\tfor i in 2..A.len() {\n\t\tif A[i] == A[i - 1] || A[i] == A[i - 2] {\n\t\t\treturn A[i];\n\t\t}\n\t}\n\t// Only one case: [x, y, z, x]\n\tA[0]\n}\n```\n\n**Solution 3: O(1) space, O(1) time**\n```rust\npub fn repeated_n_times(A: Vec<i32>) -> i32 {\n\tuse rand::Rng;\n\tlet mut rng = rand::thread_rng();\n\tlet (mut i, mut j) = (0, 0);\n\t// approximately 0.5 * 0.5 probability per round\n\t// so average 4 turns to get the result\n\twhile (i == j || A[i] != A[j]) {\n\t\ti = rng.gen_range(0, A.len());\n\t\tj = rng.gen_range(0, A.len());\n\t}\n\tA[i]\n}\n```
3
0
[]
2
n-repeated-element-in-size-2n-array
No hash/set/count/search. Simple 0ms Java solutions with no allocations (+ a 1-liner).
no-hashsetcountsearch-simple-0ms-java-so-ejws
Since there are so many of the repeated element, it is hard to go too far without a duplicate. There may be sections of the array that have large areas with no
flarbear
NORMAL
2019-04-10T18:49:22.348806+00:00
2019-04-10T18:49:22.348848+00:00
666
false
Since there are so many of the repeated element, it is hard to go too far without a duplicate. There may be sections of the array that have large areas with no duplicates, but that just means that the duplicated elements are even more concentrated in some other section of the array.\n\nAdjacent elements are highly likely to match in most distributions, but if you alternate the elements then you can have a case where no two adjacent elements match. If they are perfectly alternating, then all sets of 3 will have a match. The only case where you can separate matching elements by more than 1 element between them is if you alternate match-unique at the beginning of the array and unique-match at the end of the array, but you can only switch from one form of alternation to the other once in the array without ending up with 2 adjacent elements that match. More specifically, you can have: ```MUMUMUUMUMUM``` (```M``` is the matching element, ```U``` is any of the unique elements), but if you have ```UMUMUMMUMUMU``` then you\'ve caused the two elements in the middle to be matching and adjacent.\n\nSo, the furthest apart any 2 matching elements can be is 3, and that can occur only once in the array, all other matching elements can be separated by at most one unique element.\n\nNote that there is one case where you can have the matching elements 3 apart without any being 2 apart and that is the unique case of 4 elements: ```MUUM```. You can either special case test for this one case, or you can view the array as circular in which case any change in the alternation would appear to place elements adjacent to each other when wrapping around the array. You only need to test one triplet that wraps from the end to the beginning to reduce this case down to one of the formerly analyzed cases.\n\nHere is the algorithm using 2 local variables to hold the two common elements in a rolling list of 3 adjacent elements in processor registers without having to reload data from the array. The single wrap-around triplet is tested by initialing the 2 "hold" variables to element ```[n-1]``` and element ```[0]```\n\n```\n public int repeatedNTimes(int[] A) {\n int a = A[A.length-1];\n int b = A[0];\n if (a == b) return a;\n for (int i = 1; i < A.length; i++) {\n int c = A[i];\n if (c == a || c == b) return c;\n a = b;\n b = c;\n }\n return -1;\n }\n```\n\n# Solution 2\n\nAnother solver pointed out simplifications for 2 of the complications I outlined above in this thread: https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/276466/Java-0ms-faster-than-100-space:-O(1)-run:-O(n)-with-very-low-overhead\n\nFirst, if we have the case of ```MUMU...UMUM``` where the alternation switches from M-first to M-last then I explicitly test for that case by comparing the start of the array to the end of the array.... but we don\'t need the comparison as we can just assume that is what happened if we never found a duplicate until we get to the end of the array. So, rather than requiring a "wrap-around" test to capture that possibility, we just return the last value in the array assuming that it matched a value towards the front of the array.\n\nSecond, once we\'ve tested the first 3 elements against each other, we either find a duplicate and return it, or we know the array did not start with ```MUM``` so it must either be a uniform array of ```UMUM...UM``` or it will have some pair of elements that are adjacent and duplicate each other.\n\nI took the code from that solution and improved it in the following ways:\n\nFirst, we don\'t need to do lots of testing for the first 3 elements. The scan of the array looking for adjacent matching pairs will already compare ```A[0] == A[1]``` and ```A[1] == A[2]```, so the only compare among the first 3 elements that isn\'t automatically done in the loop is ```A[0] == A[2]```.\n\nThus, a scan of the array looking for duplicates in adjacent pairs will only fail to find the duplicate in one of 2 cases:\n\n```MUUMUM...UM``` - in which case the last element is the duplicate\n```UMUM...UM``` - in which case the last element is the duplicate\n```MUMU...MU``` - in which case a comparison of ```A[0] == A[2]``` is the only comparison needed to find this case.\n\nSecond, I use local variables to avoid having to constantly reload data from the array - that\'s a bias that is particular to the way that I solve these problems because I work in a field where reduction in memory accesses is a fairly important factor (imaging where each pixel access costs time multiplied by the huge amount of memory in an image) - so I naturally use and reuse local variables rather than repeated loads from nearby array elements when it is possible.\n\n```\n public int repeatedNTimes(int[] A) {\n int p = A[0];\n if (p == A[2]) return p;\n for (int i = 1; i < A.length; i++) {\n int c = A[i];\n if (c == p) break;\n p = c;\n }\n return p;\n }\n```\n\nAnd if you\'d like a version that is shorter because it just loads from the array rather than trying to save the values in locals, you get an even shorter solution:\n```\n public int repeatedNTimes(int[] A) {\n if (A[0] == A[2]) return A[0];\n for (int i = 1; i < A.length; i++) {\n if (A[i] == A[i-1]) return A[i];\n }\n return A[A.length - 1];\n }\n```\n# And now, for the journal of obfuscated code...\nAnd now, just for grins, a 1-line-of-real-work (not counting variable declarations and return statement), local variable-using solution...\n\n```\n public int repeatedNTimes(int[] A) {\n int c, p;\n if ((p = A[0]) != A[2]) for (int i = 1; i < A.length && ((c = A[i]) != p); i++, p = c);\n return p;\n }\n```
3
0
[]
2
n-repeated-element-in-size-2n-array
Java O(N) time, 0 space, 100%, pigeonhole principle
java-on-time-0-space-100-pigeonhole-prin-3f5g
\n\nclass Solution {\n public int repeatedNTimes(int[] A) {\n if(A[0] == A[A.length-1])\n return A[0];\n \n for(int i = 0; i
miklov
NORMAL
2019-04-04T05:11:35.890514+00:00
2019-04-04T05:11:35.890558+00:00
670
false
\n```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n if(A[0] == A[A.length-1])\n return A[0];\n \n for(int i = 0; i < A.length-1; i++){\n if(i < A.length-2 && A[i] == A[i+2]){\n return A[i];\n }\n if(A[i] == A[i+1])\n return A[i];\n }\n \n return -1;\n }\n}\n```
3
0
[]
1
n-repeated-element-in-size-2n-array
java 4ms faster than 99.96% of Java solutions
java-4ms-faster-than-9996-of-java-soluti-bm4t
The key is that all the numbers are unique except the result. Simply, loop through the original numbers and keep adding numbers to a set, as soon as you see a r
codepower
NORMAL
2019-01-23T09:35:40.480929+00:00
2019-01-23T09:35:40.481015+00:00
448
false
The key is that all the numbers are unique except the result. Simply, loop through the original numbers and keep adding numbers to a set, as soon as you see a repeated number that\'s the result. It\'s an O(n) memory though\n```\npublic int repeatedNTimes(int[] A) {\n Set<Integer> uniqueNums = new HashSet<>();\n int result = 0;\n for (int num : A){\n if (uniqueNums.contains(num)) {\n result = num;\n break;\n }\n uniqueNums.add(num);\n }\n return result;\n }\n```
3
0
[]
0
n-repeated-element-in-size-2n-array
Intuitive Python O(1) Space O(N) Time
intuitive-python-o1-space-on-time-by-jle-nkdv
\nclass Solution:\n def repeatedNTimes(self, A):\n """\n :type A: List[int]\n :rtype: int\n """\n # check the first 4 for
jlepere2
NORMAL
2019-01-10T02:02:47.667880+00:00
2019-01-10T02:02:47.667922+00:00
819
false
```\nclass Solution:\n def repeatedNTimes(self, A):\n """\n :type A: List[int]\n :rtype: int\n """\n # check the first 4 for a duplicate\n for i in range(4):\n for j in range(i+1, 4):\n if A[i] == A[j]:\n return A[i]\n # not found means the repeated number must be continuous somewhere in the array\n for i in range(2, len(A)-1):\n if A[i] == A[i+1]:\n return A[i]\n # should never get here\n return None\n```
3
0
[]
1
n-repeated-element-in-size-2n-array
[JavaScript] O(n) w/Explanation!
javascript-on-wexplanation-by-bundit-gt5u
Given the fact that there are N + 1 unique elements and only one of these elements is repeated N times, we know that there is only one repeated element and the
bundit
NORMAL
2019-01-07T00:53:19.181907+00:00
2019-01-07T00:53:19.181955+00:00
552
false
Given the fact that there are ```N + 1``` unique elements and only one of these elements is repeated ```N``` times, we know that there is only one repeated element and the rest are unique. \n1. We can use a set to store elements that we\'ve seen. This gives us O(1) lookup and O(1) insert.\n2. Once we find an element that is repeated we can return that element right away.\n3. We will have to traverse through half the list at most, giving us O(N) time-complexity.\n```\nvar repeatedNTimes = function(A) {\n let set = new Set();\n \n for(let a of A) {\n if(set.has(a))\n return a;\n \n set.add(a);\n }\n};\n```
3
0
[]
1
n-repeated-element-in-size-2n-array
Python 1-liner
python-1-liner-by-cenkay-4mi9
\nclass Solution:\n def repeatedNTimes(self, A):\n return collections.Counter(A).most_common(1)[0][0]\n
cenkay
NORMAL
2018-12-23T04:04:20.124246+00:00
2018-12-23T04:04:20.124308+00:00
576
false
```\nclass Solution:\n def repeatedNTimes(self, A):\n return collections.Counter(A).most_common(1)[0][0]\n```
3
1
[]
0
n-repeated-element-in-size-2n-array
Easy solution for beginners. Beats 90%.
easy-solution-for-beginners-beats-90-by-6jej3
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
Akshat_04
NORMAL
2024-08-02T08:27:25.308298+00:00
2024-08-02T08:27:25.308324+00:00
226
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 repeatedNTimes(vector<int>& nums) {\n \n for(int i=0;i<nums.size();i++){\n for(int j=i+1;j<nums.size();j++){\n if(nums[i]==nums[j])\n return nums[i];\n }\n }\n return 0;\n \n \n // sort(nums.begin(),nums.end());\n // for(int i=0;i<nums.size()-1;i++){\n // if(nums[i]==nums[i+1])\n // return nums[i];\n // }\n // return 0;\n }\n};\n```
2
0
['C++']
1
n-repeated-element-in-size-2n-array
JAVA Easy Solution
java-easy-solution-by-vaish_na_vi-gtya
Describe your first thoughts on how to solve this problem. \n\n\n\n\n# Complexity\n- Time complexity: 0ms\n\n\n- Space complexity: 44.72\n\n\n# Code\n\nclass
Vaish_na_vi
NORMAL
2024-06-10T09:06:06.364949+00:00
2024-06-10T09:06:06.365001+00:00
255
false
<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 0ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 44.72\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n HashSet<Integer> seen = new HashSet<>();\n for (int num : nums) {\n if (!seen.add(num)) {\n return num;\n }\n }\n return -1;\n }\n}\n```
2
0
['Java']
0
n-repeated-element-in-size-2n-array
Beginners Friendly Solution 🚀🚀| Easy To Understand C++ Users
beginners-friendly-solution-easy-to-unde-1w4h
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
dhiraj_15
NORMAL
2024-02-13T18:51:23.675791+00:00
2024-02-13T18:51:23.675818+00:00
202
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(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![Screenshot (7).png](https://assets.leetcode.com/users/images/f0bcd9ec-a9ba-4494-9428-ecf7e262b0d1_1707850271.0890825.png)\n\n# Code\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n for(int i=0;i<arr.size()-1;i++)\n {\n if(arr[i]==arr[i+1])\n {\n return arr[i];\n }\n }\n return {};\n }\n};\n```
2
0
['Array', 'Sorting', 'C++']
0
n-repeated-element-in-size-2n-array
1-liner counter ez
1-liner-counter-ez-by-randomnpc-qyvj
Code\n\nfrom collections import Counter\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][
RandomNPC
NORMAL
2023-10-25T04:10:54.385962+00:00
2023-10-25T04:10:54.385991+00:00
228
false
# Code\n```\nfrom collections import Counter\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][0]\n```
2
0
['Python', 'Python3']
1
n-repeated-element-in-size-2n-array
Very Easy Approach || Java || GeForceGroot
very-easy-approach-java-geforcegroot-by-ama7d
Intuition\nSort array and if current and next element found same then return that element.\n\n# Approach\nSort the array and find is nums[i]==nums[i+1] and then
GeForceGroot
NORMAL
2023-09-12T06:19:34.230578+00:00
2023-09-12T06:19:34.230598+00:00
265
false
# Intuition\nSort array and if current and next element found same then return that element.\n\n# Approach\nSort the array and find is nums[i]==nums[i+1] and then store nums[i] in and variable and break the loop. return the variable.\n# Complexity\n- Time complexity:\nnlog(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int ans = 0;\n for(int i=0;i<n-1;i++){\n if(nums[i]==nums[i+1]){\n ans = nums[i];\n break;\n }\n }\n return ans;\n }\n}\n```
2
0
['Java']
0
n-repeated-element-in-size-2n-array
✅C++ || Best Solution || Without Extra Space || -100% use of brain✅
c-best-solution-without-extra-space-100-x1x6k
\n# Approach\nAppoach is very simple. As there is only one element that occured n times in (n*2) size array. That\'s why after sorting element will be around mi
shyamal122
NORMAL
2023-09-05T20:55:07.897321+00:00
2023-09-05T20:55:07.897354+00:00
140
false
\n# Approach\nAppoach is very simple. As there is only one element that occured n times in (n*2) size array. That\'s why after sorting element will be around mid position or, left side of mid or, right side of mid. We compare curent value with surrounding value and return the value.\n\n# Complexity\n- Time complexity:\n$$O(nlog(n))$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int mid=nums.size()/2;\n int x=0;\n if(nums[mid]==nums[mid-1] || nums[mid]==nums[mid+1])\n x=nums[mid];\n if(nums[mid-1]==nums[mid-2])\n x=nums[mid-1];\n return x;\n }\n};\n```
2
0
['C++']
0
n-repeated-element-in-size-2n-array
Solution beats 99% in runtime and 93% in memory. Optimized way
solution-beats-99-in-runtime-and-93-in-m-bke7
Intuition\n Describe your first thoughts on how to solve this problem. \nThe unique number is half + 1 of the length of array. \nAnd one number is half of the l
muhammedsheheem
NORMAL
2023-08-25T05:15:58.550744+00:00
2023-08-25T05:18:17.209462+00:00
301
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe unique number is half + 1 of the length of array. \nAnd one number is half of the length of array.\nWhich means the half of the array is unique and the rest is same number. So we just have to find the duplicate from the array.\n\nEg :-\nnums = [2,1,2,5,3,2] \n\nnums.length = 6 \nn = 3 ( nums.length == 2 * n )\n\nHere uniques are 1, 2, 3, 5 => length = 4\n\n\n```\nunique = [ 1, 2, 3, 5 ] length = 4\nrestOfArray = [ 2, 2 ] length = 2\n\n```\nAs per question a single element repeats 3 times \n```\nrestOfArray = [ 2, 2 ]\n```\nHere 2 repeats two times and unique array have the another 2 \nwhich means 2 is coming three times\n\n**This may feels Complicated**\n\n**The conclusion is :**\n1 numer repeats n times \nLook at the array mentioned above \nHalf of the array do not repeat and the other half will be the same number\n\n**So we just have to find the repeating element** \n**Note that there will be only one element that repeats!!!** \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst I did normal nested loop to find the duplicate. if one number matches the other, i returned the number. because there will be only one number that repeats.\n\nThen I optimised it with Set()\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```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar repeatedNTimes = function(nums) {\n const arrSet = new Set();\n for (const item of nums) {\n if (arrSet.has(item)) {\n return item;\n }\n arrSet.add(item);\n }\n};\n```
2
0
['JavaScript']
1
n-repeated-element-in-size-2n-array
Moore's Voting Algorithm
moores-voting-algorithm-by-chandravaibha-ta5m
Intuition\nMany so called O(1) solutions have been published but the thing is they are hard to think of during an interview. If the inteviewer allows extra spac
chandravaibhav65
NORMAL
2023-08-02T15:53:09.749041+00:00
2023-08-02T15:53:09.749064+00:00
30
false
# Intuition\nMany so called O(1) solutions have been published but the thing is they are hard to think of during an interview. If the inteviewer allows extra space or N^2 time then the question is trivial. But to do this in O(N) time and O(1) space requires some extra thinking.\n\n# Approach\nMoore\'s voting algorithm can be used to solve this problem. The catch is that Moore\'s Algo is generally to find the majority element (frequency > N/2 where N is length of array). In our case, it might happen that a simple Moore\'s pass might erroneously discard our answer. Some examples are:\n\n[2,1,2,3]\n\n[2,2,1,3]\n\nHere Moore\'s algo will consider 3 as a candidate because 2\'s frequency gets "cancelled" by the other N numbers. To counter this, we can employ a rather simple fix. In case Moore\'s candidate element is not our answer, we simply reverse our array and run Moore\'s algo again. \n\n[3,2,1,2]\n\n[3,1,2,2]\n\nNow our algo correctly ascertains 2 as a candidate. I haven\'t come up with a rigorous proof for this. So in future a test case might come up where this might fail. If anyone of you can prove this algorithm as correct or incorrect it would be really nice.\n\n# Complexity\n- Time complexity: 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\n int moore(vector<int>& a){\n int cur=a[0],f=1;\n for(int i=1;i<a.size();i++){\n if(a[i]!=cur) f--;\n else f++;\n if(f==0){\n cur=a[i],f=1;\n }\n }\n f=0;\n for(auto i : a) if(i==cur) f++;\n if(f==a.size()/2) return cur;\n reverse(a.begin(),a.end());\n return moore(a);\n }\n\n int repeatedNTimes(vector<int>& a) {\n return moore(a);\n }\n};\n```
2
0
['C++']
1
n-repeated-element-in-size-2n-array
Easiest solution with just one condition
easiest-solution-with-just-one-condition-nsju
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
anshul2702
NORMAL
2023-07-18T20:29:31.171324+00:00
2023-07-18T20:29:31.171345+00:00
20
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 repeatedNTimes(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int i = nums.size()/2;\n if(nums[i] == nums[i+1]){\n return nums[i];\n }\n else{\n return nums[i-1];\n }\n \n }\n};\n```
2
0
['C++']
0
n-repeated-element-in-size-2n-array
JAVA solution with HashSet 0ms very easy
java-solution-with-hashset-0ms-very-easy-zjot
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
nyutonov_sh
NORMAL
2023-07-02T11:22:13.892861+00:00
2023-07-02T11:22:13.892879+00:00
166
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 repeatedNTimes(int[] nums) {\n HashSet<Integer> set = new HashSet<>();\n\n for (int el : nums) {\n if (!set.add(el)) return el;\n }\n\n return -1;\n }\n}\n```
2
0
['Java']
2
n-repeated-element-in-size-2n-array
Simple JAVA Solution for beginners. 0ms. Beats 100%.
simple-java-solution-for-beginners-0ms-b-tw5w
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
sohaebAhmed
NORMAL
2023-05-19T10:24:00.314183+00:00
2023-05-19T10:24:00.314226+00:00
412
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Set<Integer> set = new HashSet();\n for(int x : nums) {\n if(set.contains(x)) {\n return x;\n }\n set.add(x);\n } \n return 0;\n }\n}\n```
2
0
['Array', 'Hash Table', 'Java']
0
n-repeated-element-in-size-2n-array
Solution
solution-by-deleted_user-x3ty
C++ []\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums)\n {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n
deleted_user
NORMAL
2023-05-16T12:40:12.887165+00:00
2023-05-16T13:35:49.322731+00:00
351
false
```C++ []\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums)\n {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n map<int, int> count;\n for(int i=0; i<nums.size()/2+2; i++)\n {\n if(count[nums[i]] == 1) return nums[i];\n count[nums[i]]++;\n }\n return 0;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n seen = set()\n for n in nums:\n if n in seen: return n\n seen.add(n)\n```\n\n```Java []\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Set<Integer> elems = new HashSet<>();\n for (int elem : nums) {\n if (!elems.add(elem)) {\n return elem;\n }\n }\n return -1;\n }\n}\n```\n
2
0
['C++', 'Java', 'Python3']
0
n-repeated-element-in-size-2n-array
✌✌HashSet Solution||Easy
hashset-solutioneasy-by-tamosakatwa-289j
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
tamosakatwa
NORMAL
2023-03-19T03:35:10.872112+00:00
2023-03-19T03:35:10.872143+00:00
282
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 repeatedNTimes(int[] nums) {\n HashSet<Integer>set=new HashSet<>();\n for(int n:nums){\n if(!set.contains(n)){\n set.add(n);\n }else{\n return n;\n }\n }\n return 0;\n }\n}\n```
2
0
['Java']
1
n-repeated-element-in-size-2n-array
C++ || easy || Explained ||Map || ✅
c-easy-explained-map-by-tridibdalui04-09vu
Store Frequencies of all digit in a map\n2. itarate over the map if the freq is >= size/2 then return that\n\n\nclass Solution {\npublic:\n int repeatedNTime
tridibdalui04
NORMAL
2022-10-20T13:16:12.063559+00:00
2022-10-20T13:16:12.063599+00:00
1,272
false
1. Store Frequencies of all digit in a map\n2. itarate over the map if the freq is >= size/2 then return that\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& a) {\n int n=a.size();\n unordered_map<int,int>mp;\n for(int i=0;i<n;i++)\n mp[a[i]]++;\n for(auto i:mp)\n {\n if(i.second>= n/2)\n return i.first;\n }\n return 0;\n }\n};\n```
2
0
['C']
0
n-repeated-element-in-size-2n-array
Very Easy Javascript Solution faster than 90%!!!!
very-easy-javascript-solution-faster-tha-ik4b
\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar repeatedNTimes = function(a) {\n let d = []\n for(let i of a){\n if(d.includes(i)){
harsh_sutaria_25
NORMAL
2022-09-30T05:42:11.064902+00:00
2022-09-30T05:42:11.064927+00:00
709
false
```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar repeatedNTimes = function(a) {\n let d = []\n for(let i of a){\n if(d.includes(i)){\n return i \n }else{\n d.push(i)\n }\n }\n \n \n};\n```
2
0
['JavaScript']
0
n-repeated-element-in-size-2n-array
Java Solution.
java-solution-by-harsh6645-d5k1
class Solution {\n public int repeatedNTimes(int[] nums) {\n\t\n Arrays.sort(nums);\n for(int i = 0 ; i<nums.length-1; i++){\n if(nu
Harsh6645
NORMAL
2022-09-25T06:34:41.996811+00:00
2022-09-25T06:34:41.996853+00:00
686
false
class Solution {\n public int repeatedNTimes(int[] nums) {\n\t\n Arrays.sort(nums);\n for(int i = 0 ; i<nums.length-1; i++){\n if(nums[i] == nums[i+1]){\n return nums[i];\n } \n }\n return nums[nums.length-1];\n }\n}
2
0
['Java']
0
n-repeated-element-in-size-2n-array
Java 0ms, 100% fast, pigeon hole
java-0ms-100-fast-pigeon-hole-by-dmproni-85zg
In some bucket of every 3 numbers there should be a repeated num by definition of a problem, so we need to compare only every 3 numbers:\n\nclass Solution {\n
dmproni
NORMAL
2022-09-20T17:11:38.634392+00:00
2022-09-20T17:11:38.634438+00:00
340
false
In some bucket of every 3 numbers there should be a repeated num by definition of a problem, so we need to compare only every 3 numbers:\n```\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n for (int i = 0; i < nums.length - 3; i += 3) {\n if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2])\n return nums[i];\n if (nums[i + 1] == nums[i + 2])\n return nums[i + 1];\n }\n return nums[nums.length - 1];\n }\n}\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
easy solution
easy-solution-by-mohit_gusain-4dz4
\nclass Solution {\npublic:\nint repeatedNTimes(vector<int>& nums) {\nsort(nums.begin(),nums.end());\nfor(int i=0;i<nums.size();i++)\n{\nif(nums[i]==nums[i+1])/
Mohit_gusain
NORMAL
2022-05-19T17:16:07.576302+00:00
2022-05-20T07:26:32.258390+00:00
142
false
```\nclass Solution {\npublic:\nint repeatedNTimes(vector<int>& nums) {\nsort(nums.begin(),nums.end());\nfor(int i=0;i<nums.size();i++)\n{\nif(nums[i]==nums[i+1])//all element are distincct and only one element is repeating\n{\nreturn nums[i];\n}\n}\nreturn 0;\n}\n};\n```
2
0
['C']
0
n-repeated-element-in-size-2n-array
C++ | 2 Approaches | O(n) Run Time.
c-2-approaches-on-run-time-by-pankajtanw-0hkb
For a detailed explanation - https://www.pankajtanwar.in/code/n-repeated-element-in-size-2n-array \n\nFirst Appraoch -\n\n\nclass Solution {\npublic:\n int r
pankajtanwar
NORMAL
2021-10-06T17:06:07.176468+00:00
2021-10-06T17:06:07.176547+00:00
179
false
* For a detailed explanation - https://www.pankajtanwar.in/code/n-repeated-element-in-size-2n-array \n\n**First Appraoch** -\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) {\n map<int,int> list;\n \n for(int num: nums) {\n list[num]++;\n }\n \n for(auto val: list) {\n if(val.second == nums.size()/2) return val.first;\n }\n return -1;\n }\n};\n```\n\n**Second Appraoch** -\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums) {\n for(int i=0;i<nums.size()-2;i++) {\n if(nums[i] == nums[i+1] || nums[i] == nums[i+2]) return nums[i];\n }\n return nums[nums.size()-1];\n }\n};\n```
2
0
['C']
0
n-repeated-element-in-size-2n-array
Python: faster than 88%, less memory than 94%
python-faster-than-88-less-memory-than-9-e4ef
\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n for tup in enumerate(nums):\n if tup[1] in nums[tup[0]+1:]:\n
travanj05
NORMAL
2021-09-23T17:51:26.479501+00:00
2021-09-23T17:51:26.479539+00:00
58
false
```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n for tup in enumerate(nums):\n if tup[1] in nums[tup[0]+1:]:\n return tup[1]\n ```\n\t\t
2
0
[]
0
n-repeated-element-in-size-2n-array
JavaScript Solution using hashmap - beats 97.78%
javascript-solution-using-hashmap-beats-egifi
Using hashmap\n\n\n\nvar repeatedNTimes = function(nums) {\n let map = {};\n for (let i = 0; i < nums.length; i++) {\n if(!map[nums[i]]) {\n
cchukwuka
NORMAL
2021-08-10T08:50:20.192329+00:00
2021-08-10T09:07:36.801375+00:00
213
false
Using hashmap\n\n```\n\nvar repeatedNTimes = function(nums) {\n let map = {};\n for (let i = 0; i < nums.length; i++) {\n if(!map[nums[i]]) {\n const element = nums[i];\n map[element] = true;\n } else {\n return nums[i];\n }\n }\n};\n\n```\n
2
0
['JavaScript']
0
n-repeated-element-in-size-2n-array
Java | simple 1-pass solution(100%) | O(n) time O(1) space
java-simple-1-pass-solution100-on-time-o-13q0
Since, the half of the array contains duplicate elements, in most on the test cases at least two subsequent numbers will be same and checking nums[i] == nums[i-
kaushaldokania
NORMAL
2021-07-29T18:17:27.293469+00:00
2021-07-29T18:17:27.293533+00:00
124
false
Since, the half of the array contains duplicate elements, in most on the test cases at least two subsequent numbers will be same and checking `nums[i] == nums[i-1]` will do.\n\nBut, in worst case, when the duplicates are evenly distributed like [1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0], we can compare last and 2nd last element.\n\n```\npublic int repeatedNTimes(int[] nums) {\n for (int i=2; i<nums.length;++i) {\n if (nums[i] == nums[i-1] || nums[i] == nums[i-2])\n return nums[i];\n }\n return nums[0];\n }\n```
2
1
['Java']
0
n-repeated-element-in-size-2n-array
Java O(1), no use extra space, beats 100% solution
java-o1-no-use-extra-space-beats-100-sol-mx1g
java\n// AC:\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for N-Repeated Element in Size 2N Array.\n// Memory Usage: 39.8 MB, less than 57.
ly2015cntj
NORMAL
2021-05-14T11:48:16.930424+00:00
2021-05-14T11:50:35.202527+00:00
252
false
```java\n// AC:\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for N-Repeated Element in Size 2N Array.\n// Memory Usage: 39.8 MB, less than 57.40% of Java online submissions for N-Repeated Element in Size 2N Array.\n// \n// \u601D\u8DEF\uFF1A\u8003\u8651\u4E0D\u4F7F\u7528 O(n) \u7A7A\u95F4\u7684\u505A\u6CD5\u3002\u60F3\u5230\u4F4D\u8FD0\u7B97\u4E2D\u7684\u5F02\u6216\u8FD0\u7B97\uFF1A\u53EA\u6709\u5F53 a = b \u65F6\uFF0C a^b == 0\uFF0C\u5229\u7528\u8FD9\u70B9\u53EF\u4EE5\u89E3\u51B3\u6B64\u9898\u3002\n// \u7531\u4E8E \u4E00\u534A\u4EE5\u4E0A\u90FD\u662F \u91CD\u590D N \u6B21\u7684\u6570\u5B57\uFF0C\u6211\u4EEC\u6BCF\u6B21\u968F\u673A\u53D6\u4E24\u4E2A\u6570\u8FDB\u884C\u5224\u65AD\uFF0C\u7406\u8BBA\u4E0A\u5E73\u5747\u53EA\u9700\u8981 4 \u6B21\u5C31\u80FD\u627E\u5230\u8FD9\u4E2A\u6570\n// \u590D\u6742\u5EA6\uFF1AT\uFF1Aavg:O(1) max:\u65E0\u9650\u5927\uFF0C S:O(1)\n// \nclass Solution {\n public int repeatedNTimes(int[] nums) {\n int size = nums.length, rand1, rand2;\n Random rand = new Random();\n while (true) {\n rand1 = rand.nextInt(size);\n rand2 = rand.nextInt(size);\n if (rand1 != rand2 && (nums[rand1] ^ nums[rand2]) == 0) {\n return nums[rand1];\n }\n }\n }\n}\n```
2
0
['Java']
0
n-repeated-element-in-size-2n-array
python | faster than 97.20%
python-faster-than-9720-by-prachijpatel-vv3l
\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d = {}\n for i in A:\n if i not in d:\n d[i] = 1
prachijpatel
NORMAL
2021-04-29T11:40:22.376821+00:00
2021-05-11T03:33:25.643607+00:00
192
false
```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d = {}\n for i in A:\n if i not in d:\n d[i] = 1\n else:\n return i\n```
2
0
['Python', 'Python3']
2
n-repeated-element-in-size-2n-array
Javascript 99% speed one-liner
javascript-99-speed-one-liner-by-saynn-rcle
\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n return A.find(a => A.filter(n => n === a).length > 1)\n};\n
saynn
NORMAL
2021-03-21T12:40:58.963073+00:00
2021-03-21T12:40:58.963115+00:00
140
false
```\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n return A.find(a => A.filter(n => n === a).length > 1)\n};\n```
2
0
['JavaScript']
0
n-repeated-element-in-size-2n-array
Java solution - O(n) time O(1) space
java-solution-on-time-o1-space-by-akiram-ryjm
\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int n = A.length;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;
akiramonster
NORMAL
2021-03-02T04:51:25.167932+00:00
2021-03-02T04:51:55.078149+00:00
82
false
```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int n = A.length;\n for (int i = 0; i < n; i++) {\n int j = (i + 1) % n;\n int k = (j + 1) % n;\n if (A[i] == A[j] || A[i] == A[k]) return A[i];\n if (A[j] == A[k]) return A[j];\n }\n return 0;\n }\n}\n```\n\nBecause there are n/2 elements have the same value, there exists a pair which are same in 3 continous elements.
2
0
[]
0
n-repeated-element-in-size-2n-array
Easy to understand || Two approach || C++
easy-to-understand-two-approach-c-by-cod-ctn7
1)Map Based approach\n\n//Because Size is 2N and (N+1) elements are distinct\n//exactly one element is repeating N times\nclass Solution {\npublic:\n int re
code1511
NORMAL
2020-12-13T14:26:24.820278+00:00
2020-12-13T14:39:48.075107+00:00
159
false
**1)Map Based approach**\n```\n//Because Size is 2N and (N+1) elements are distinct\n//exactly one element is repeating N times\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n unordered_map<int,int>u;\n for(int i=0;i<A.size();i++){\n u[A[i]]++;\n }\n int n=A.size();\n int res;\n for(auto i:u)\n if(i.second==n/2)\n res=i.first;\n return res;\n }\n};\n```\n**2) Sorting Based Approach**\n```\nclass Solution {\npublic:\n//Because (N+1) elements are distinct\n// exactly one of these elements is repeated N times\n//so when we\'ll sort them ,that one repeated element would be at one place \n//after sorting we can easily compare them and find .\n\n int repeatedNTimes(vector<int>& A) {\n sort(A.begin(),A.end());\n for(int i=0;i<A.size();i++){\n if(A[i]==A[i+1])\n return A[i];\n }\n return 0;\n }\n};\n```\n
2
0
['C', 'C++']
0
n-repeated-element-in-size-2n-array
Python Beats 97%
python-beats-97-by-ikm98-h194
\n def repeatedNTimes(self, A: List[int]) -> int:\n \n counts = [0]*10001\n \n for val in A:\n if counts[val] == 1:\n
IKM98
NORMAL
2020-11-28T20:21:41.239843+00:00
2020-11-28T20:21:41.239872+00:00
218
false
```\n def repeatedNTimes(self, A: List[int]) -> int:\n \n counts = [0]*10001\n \n for val in A:\n if counts[val] == 1:\n return val\n counts[val] += 1\n```
2
0
['Counting Sort', 'Python', 'Python3']
1
n-repeated-element-in-size-2n-array
Clean JavaScript Solution
clean-javascript-solution-by-shimphillip-ebjb
\n// time O(n log n) space O(1)\nvar repeatedNTimes = function(A) {\n A.sort((a, b) => a - b)\n \n for(let i=0; i<A.length; i++) {\n if(A[i] ===
shimphillip
NORMAL
2020-11-03T03:30:51.666760+00:00
2020-11-30T21:45:59.764837+00:00
219
false
```\n// time O(n log n) space O(1)\nvar repeatedNTimes = function(A) {\n A.sort((a, b) => a - b)\n \n for(let i=0; i<A.length; i++) {\n if(A[i] === A[i+1]) {\n return A[i]\n }\n }\n};\n\n// time O(n) space O(n)\nvar repeatedNTimes = function(A) {\n const map = {}\n \n for(const number of A) {\n if(map[number]) {\n return number\n }\n \n map[number] = true\n }\n};\n```
2
0
['JavaScript']
0
n-repeated-element-in-size-2n-array
CPP | Faster than 100% | Easy
cpp-faster-than-100-easy-by-pranjalb-fhpz
A very simple approach using arrays.\nSince the maximum size of the vector is 10000, and 0 < A[i] < 10000.\n\nWe use the indexes as the count of the number in t
pranjalb
NORMAL
2020-08-29T08:34:47.738370+00:00
2020-08-29T08:34:47.738417+00:00
275
false
A very simple approach using arrays.\nSince the maximum size of the vector is 10000, and 0 < A[i] < 10000.\n\nWe use the indexes as the count of the number in the array.\n\nThen we check is the Arr[i] is greater than 0 and is equal to the half of the size of the vector, if yes, we return the value.\n\n```\n\tConsider the following test case :-\n\t\t\t\n\t\t\tA = {1,2,3,3}\n\t\t\t\n\t\t\t\tAfter first loop:\n\t\t\t\t\tArr = {0,1,1,2,0,0,0,0,0,0,.........0,0,0,0}\n\t\t\t\t\t\n\t\t\t\tSize of vector --> 4/2 = 2.\n\t\t\t\t\n\t\t\t\tAfter second loop, we find :-\n\t\t\t\t\t\t\n\t\t\t\t\t\tArr[3] == 2 == A.size()/2\n\n\t\t\t\t\t\tReturn i --> return 3;\n\t\t\t\n```\n\n```\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& A) {\n int arr[10000] {0};\n for(int i : A){\n arr[i]++;\n }\n for(int i = 0;i < 10000;i++){\n if(arr[i] > 0 && arr[i] == (A.size()/2)){\n return i;\n }\n }\n return 0;\n }\n};\n```
2
0
['C', 'C++']
0
n-repeated-element-in-size-2n-array
Java shortest solution and without HashMap
java-shortest-solution-and-without-hashm-egi4
If all elements but one are unique, just order the array and find the repeated value.\n\n\nclass Solution {\n public int repeatedNTimes(int[] A) {\n A
kedakai
NORMAL
2020-06-06T15:56:33.305525+00:00
2020-06-06T15:56:33.305553+00:00
52
false
If all elements but one are unique, just order the array and find the repeated value.\n\n```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n Arrays.sort(A);\n \n for(int i = 0; i < A.length; ++i) {\n if(A[i] == A[i+1]) {\n return A[i];\n }\n }\n return -1;\n }\n}\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
Simple JS Solution: faster than 100%
simple-js-solution-faster-than-100-by-hb-x4r1
\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n let m = new Map();\n for (let x of A) {\n if (!m.has(
hbjorbj
NORMAL
2020-03-29T23:06:13.764727+00:00
2020-03-29T23:06:13.764761+00:00
253
false
```\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar repeatedNTimes = function(A) {\n let m = new Map();\n for (let x of A) {\n if (!m.has(x)) m.set(x,1);\n else return x;\n }\n};\n```
2
0
['JavaScript']
0
n-repeated-element-in-size-2n-array
python, explained
python-explained-by-rmoskalenko-rs71
The questions is basically asking to find a non-unique value. There are many ways to do it, but how to decide which one works best?\n\nFrom the performance poin
rmoskalenko
NORMAL
2020-03-22T01:05:32.292589+00:00
2020-03-22T01:05:32.292631+00:00
198
false
The questions is basically asking to find a non-unique value. There are many ways to do it, but how to decide which one works best?\n\nFrom the performance point of view, you can use https://wiki.python.org/moin/TimeComplexity as a reference. \n\nSo for example, if we try something like:\n\n- Let\'s sort the values ... Sort alone is O(nlogn)\n- Let\'s take values one by one and count how many times they are present ... that would be a for loop (for every value) inside another for loop (if that value is in the list)\n\nSo those approaches may work fine on short lists, but as the input data list increases, they start slowing down.\n\nWhat works well? Python has some built-in tools using hashes. Operations like Is this value in a given dictionary or in a given set are generally O(1) with the worst case scenario (if hash produces a lot of collisions) is O(N). So if we try:\n\nfor every value:\n if that value in the dictionary (or in the set) - return\n else - add that value\n \nThat logic would have very good O(N) complexity. How can it be implented?\n\nDictionary based:\n\n```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d={}\n for a in A:\n if a in d:\n return a\n else:\n d[a]=1\n```\n\nSet based:\n\n```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n d=set()\n for a in A:\n if a in d:\n return a\n else:\n d.add(a)\n```\n\nBut if you don\'t care about performance and looking for some really short one-liner, here is an example:\n\ncollections.counter will create a dictionary (that\'s not bad, O(N)), and most_common() will sort the values (not good performance wise, but keeps the good short):\n\n```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n\t\treturn collections.Counter(A).most_common()[0][0]\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
Java novel O(n) time and O(1) space solution, very easy to follow
java-novel-on-time-and-o1-space-solution-2pc9
\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int majority = 0;\n int vote = 1;\n for(int i=1; i<A.length-1; i++) { //tr
tgaurav10
NORMAL
2020-02-09T11:41:23.482877+00:00
2020-02-09T12:08:24.528564+00:00
144
false
```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int majority = 0;\n int vote = 1;\n for(int i=1; i<A.length-1; i++) { //try to find the majority, note that we\'re ignoring the last element\n\t\t// so that we can get a majority (more than 50%)\n if(A[majority] == A[i]) {\n vote++;\n \n } else {\n vote--;\n }\n if(vote==0) {\n majority = i;\n vote++;\n } \n }\n int count = 0;\n for(int i=0; i<A.length-1; i++) { //confirm that it\'s majority\n if(A[majority] == A[i]) {\n count++; \n }\n }\n if(count==A.length/2) {\n return A[majority]; //it\'s confirmed!\n } else {\n //for the case when the majority is just short by 1 count in the previous for loop\n //means that the last element was the majority element\n return A[A.length-1]; \n }\n \n }\n}\n```
2
0
[]
1
n-repeated-element-in-size-2n-array
Java solution using set beats 100% runtime and memory
java-solution-using-set-beats-100-runtim-4xwt
\n//we only need find the number which has count not equal to one\n//so when we add number into set, if it is already there, set.add(number) will return false\n
tigerforrest
NORMAL
2019-12-25T02:17:59.824949+00:00
2019-12-25T02:17:59.825033+00:00
94
false
```\n//we only need find the number which has count not equal to one\n//so when we add number into set, if it is already there, set.add(number) will return false\nclass Solution {\n public int repeatedNTimes(int[] A) {\n Set<Integer> set = new HashSet<>(); \n for(int a: A){\n if(set.add(a)==false) return a;\n }\n return -1; \n }\n}\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
Java 0ms beats 100% memory
java-0ms-beats-100-memory-by-gaofan104-bidy
\nclass Solution {\n public int repeatedNTimes(int[] A) {\n for (int i=0; i<A.length-2; i++){\n // there must exist two repeated numbers wh
gaofan104
NORMAL
2019-09-20T12:31:15.901969+00:00
2019-09-20T12:31:15.902020+00:00
113
false
```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n for (int i=0; i<A.length-2; i++){\n // there must exist two repeated numbers who are separated by at most 1 unique number\n if (A[i] == A[i+1] || A[i] == A[i+2])\n return A[i];\n }\n return A[A.length-1];\n }\n}\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
JAVA 0ms 100.0%
java-0ms-1000-by-voidcake-s69j
\n public int repeatedNTimes(int[] A) {\n List list = new ArrayList();\n for(int n:A){\n if(list.contains(n))\n retur
voidcake
NORMAL
2019-09-20T02:10:44.201807+00:00
2019-09-20T02:10:44.201854+00:00
313
false
```\n public int repeatedNTimes(int[] A) {\n List list = new ArrayList();\n for(int n:A){\n if(list.contains(n))\n return n;\n list.add(n);\n }\n return -1;\n }\n```
2
0
['Java']
0
n-repeated-element-in-size-2n-array
JAVA too fast solution O(n/2) :), constant memory
java-too-fast-solution-on2-constant-memo-zxke
IDEA: No three elements can have unique values except when array size is 4.\n\n```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int a =
rostau3
NORMAL
2019-06-15T07:41:20.386810+00:00
2019-06-15T07:41:20.386865+00:00
193
false
IDEA: No three elements can have unique values except when array size is 4.\n\n```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n int a = A[0];\n int b = A[1];\n int c = A[2];\n int i = 3;\n if (A.length == 4 && A[0] == A[3])\n return A[0];\n \n do {\n if (a == b || a == c)\n return a;\n if (b == c)\n return b;\n a = b;\n b = c; \n c = A[i];\n i++;\n } while (i <= A.length);\n \n return -1;\n }\n}
2
0
[]
1
n-repeated-element-in-size-2n-array
Java 1 line !!
java-1-line-by-stachi-ariw
```\n public int repeatedNTimes(int[] A) {\n Set set = new HashSet<>();\n\n for(int n : A) if(!set.add(n)) return n;\n\n throw null;\n
stachi
NORMAL
2019-06-03T19:21:36.461677+00:00
2019-06-03T19:22:17.870526+00:00
157
false
```\n public int repeatedNTimes(int[] A) {\n Set<Integer> set = new HashSet<>();\n\n for(int n : A) if(!set.add(n)) return n;\n\n throw null;\n }\n
2
0
[]
0
n-repeated-element-in-size-2n-array
Python Solution Faster than 96.11%
python-solution-faster-than-9611-by-neoh-ppp1
\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n lst = []\n for i in range(len(A)):\n if A[i] not in lst:\n
neoh0030
NORMAL
2019-06-02T09:16:49.213571+00:00
2019-06-02T09:16:49.213636+00:00
155
false
```\nclass Solution:\n def repeatedNTimes(self, A: List[int]) -> int:\n lst = []\n for i in range(len(A)):\n if A[i] not in lst:\n lst.append(A[i])\n else:\n return(A[i])\n```
2
0
[]
0
n-repeated-element-in-size-2n-array
Java - 0ms - 100% - Very Straightforward. Use an array to act as collision
java-0ms-100-very-straightforward-use-an-avx4
\nclass Solution {\n public int repeatedNTimes(int[] A) {\n boolean[] numbers = new boolean[10000];\n\t\tfor (int i = 0; i < A.length; i++) {\n\t\t\ti
anthonychin
NORMAL
2019-04-11T21:00:05.875154+00:00
2019-04-11T21:00:05.875229+00:00
235
false
```\nclass Solution {\n public int repeatedNTimes(int[] A) {\n boolean[] numbers = new boolean[10000];\n\t\tfor (int i = 0; i < A.length; i++) {\n\t\t\tif (numbers[A[i]] == true) {\n\t\t\t\treturn A[i];\n\t\t\t} else {\n\t\t\t\tnumbers[A[i]] = true;\n\t\t\t}\n }\n return -1; \n }\n}\n```
2
0
[]
2
n-repeated-element-in-size-2n-array
[Python] Using pandas can do it very fast but I just cant import the module
python-using-pandas-can-do-it-very-fast-gczjc
\'\'\'\nclass Solution:\n \n def repeatedNTimes(self, A: List[int]) -> int:\n import pandas as pd\n lb = {\'values\': A}\n a= pd.Data
huanzhen
NORMAL
2019-03-30T05:44:42.622812+00:00
2019-03-30T05:44:42.622857+00:00
1,370
false
\'\'\'\nclass Solution:\n \n def repeatedNTimes(self, A: List[int]) -> int:\n import pandas as pd\n lb = {\'values\': A}\n a= pd.DataFrame(lb)\n \n return(a[\'values\'].value_counts().idxmax())\n\'\'\'\nTraceback:\nModuleNotFoundError: No module named \'pandas\'\nLine 4 in repeatedNTimes (Solution.py)\nLine 26 in main (Solution.py)\nLine 34 in <module> (Solution.py)\n
2
0
[]
1
n-repeated-element-in-size-2n-array
C# code
c-code-by-fadi17-0hzs
\npublic int RepeatedNTimes(int[] A) {\n var set = new HashSet<int>();\n foreach(int x in A)\n {\n if(set.Contains(x))\n
fadi17
NORMAL
2019-03-30T03:24:51.497450+00:00
2019-03-30T03:24:51.497489+00:00
261
false
````\npublic int RepeatedNTimes(int[] A) {\n var set = new HashSet<int>();\n foreach(int x in A)\n {\n if(set.Contains(x))\n return x;\n else\n {\n set.Add(x);\n }\n }\n \n return -1;\n }\n````
2
0
[]
2
minimum-amount-of-time-to-collect-garbage
[Java/C++/Python] Explanation with Observations
javacpython-explanation-with-observation-macz
Intuition\nObservation 1:\n"While one truck is driving or picking up garbage, the other two trucks cannot do anything."\nWe can simply sum up the total running
lee215
NORMAL
2022-08-28T04:01:37.770501+00:00
2022-08-28T04:01:37.770532+00:00
14,984
false
# **Intuition**\nObservation 1:\n"While one truck is driving or picking up garbage, the other two trucks cannot do anything."\nWe can simply sum up the total running time for each truck,\nthey don\'t affect each other.\n\n\nObservation 2:\n"Picking up one unit of any type of garbage takes 1 minute."\nWe don\'t care how many units for each type,\nwe only care the total amount.\n\nObservation 3:\n"however, they do not need to visit every house."\nWe only care the position of the last garbage for each type\n<br>\n\n# **Explanation**\n1. Firstly sum up the amount of gabages in total.\n2. Second find up the last position for each type.\n3. Calculate the prefix sum array of the travel distance.\n3. Sum up the distance for each type of garbage.\n<br>\n\n# **Complexity**\nTime `O(garbage + travel)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int garbageCollection(String[] garbage, int[] travel) {\n int last[] = new int[128], res = 0;\n for (int i = 0; i < garbage.length; ++i) {\n res += garbage[i].length();\n for (int j = 0; j < garbage[i].length(); ++j)\n last[garbage[i].charAt(j)] = i;\n }\n for (int j = 1; j < travel.length; ++j)\n travel[j] += travel[j - 1];\n for (int c : "PGM".toCharArray())\n if (last[c] > 0)\n res += travel[last[c] - 1];\n return res;\n }\n```\n\n**C++**\n```cpp\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int last[128] = {}, res = 0;\n for (int i = 0; i < garbage.size(); ++i) {\n res += garbage[i].size();\n for (char c : garbage[i])\n last[c] = i;\n }\n for (int j = 1; j < travel.size(); ++j)\n travel[j] += travel[j - 1];\n for (int c : "PGM")\n if (last[c])\n res += travel[last[c] - 1];\n return res;\n }\n```\n\n**Python**\n```py\n def garbageCollection(self, A: List[str], travel: List[int]) -> int:\n last = {c: i for i,pgm in enumerate(A) for c in pgm}\n dis = list(accumulate(travel, initial = 0))\n return sum(map(len, A)) + sum(dis[last.get(c, 0)] for c in \'PGM\')\n```\n
179
2
['C', 'Python', 'Java']
26
minimum-amount-of-time-to-collect-garbage
✅✅✅ Simple sum - O(N) time & O(1) space
simple-sum-on-time-o1-space-by-kreakemp-fatv
Up Vote if you like the solution \n\n1. Count all the garbage size irrespective of type - as each garbage is taking 1min\n2. Keep tracking last g, p, m visited
kreakEmp
NORMAL
2022-08-28T04:02:49.335354+00:00
2023-11-20T21:41:34.415269+00:00
5,670
false
<b> Up Vote if you like the solution </b>\n\n1. Count all the garbage size irrespective of type - as each garbage is taking 1min\n2. Keep tracking last g, p, m visited house - as we do not need to move further. Here we are tracking sum up to last occurance and not the index.\n\n### C++\n```\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int sum = 0, count = 0; \n unordered_map<char, int> last;\n for(int i = 0; i < garbage.size(); ++i){\n count += garbage[i].size();\n for(auto c: garbage[i]) last[c] = sum;\n if(i < travel.size()) sum += travel[i];\n }\n return count + last[\'M\'] + last[\'P\'] + last[\'G\'];\n }\n```\n\n\n### Java \n```\npublic int garbageCollection(String[] garbage, int[] travel) {\n int sum = 0, count = 0; \n Map<Character, Integer> last= new HashMap<>();\n for(int i = 0; i < garbage.length; ++i){\n count += garbage[i].length();\n for(char c: garbage[i].toCharArray()) last.put(c, sum);\n if(i < travel.length) sum += travel[i];\n }\n return count + last.getOrDefault(\'M\', 0) + last.getOrDefault(\'P\', 0) + last.getOrDefault(\'G\', 0);\n}\n```\n---\n\n<b>Here is an article of my interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n---
76
1
['C++', 'Java']
8
minimum-amount-of-time-to-collect-garbage
【Video】Give me 10 minutes - Beats 98% - How we think about a solution
video-give-me-10-minutes-beats-98-how-we-xofw
Intuition\nIterate through from the last index.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/GZWR5cWZ3pw\n\n\u25A0 Timeline\n0:05 Talk about time to pick up a
niits
NORMAL
2023-11-20T05:28:59.012663+00:00
2023-11-21T08:53:16.725742+00:00
3,884
false
# Intuition\nIterate through from the last index.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/GZWR5cWZ3pw\n\n\u25A0 Timeline\n`0:05` Talk about time to pick up all garbages \n`1:44` Talk about time to travel to the next house\n`5:37` Demonstrate how it works\n`8:00` Coding\n`11:12` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,165\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nFirst of all, we have two types of time.\n\n---\n\n\u2B50\uFE0F Points\n\n- Time to pick up garbages\n- Time to travel to the next house\n\n---\n\nWe need to calculate total time of those two times.\n\n### Time to pick up garbages\n\nLet\'s think about this input.\n```\nInput: garbage = ["MMM","PGM","GP"], travel = [3,10]\n```\n\nThis is very simple. The description says "Picking up one unit of any type of garbage takes 1 minute", so total time to pick up all garbages is total number of `M`, `P` and `G`.\n\nIn this case,\n```\n4(= M) + 2(= P) + 1(= G) = 8 minutes\n```\n\n### Time to travel to the next house\n\nTravel time is a little bit tricky. The description says "Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house".\n\nIn other words, the trucks don\'t have to go to the next house if they already picked up all garbages. On the other hand, they must visit all houses even if one particular garbage is only in the last house.\n\n(Seem like English test lol)\uD83D\uDE05\n\n\n---\n\nProblem\n\nProblem here is that we don\'t know where each truck can finish picking up all garbages.\n\n---\n\nTo solve this problem, my idea is to iterate through from the last house, because we can know where the last house is for each garbage.\n\nTo understand easily, I added extra garbage to the input. Let\'s think about `M` garbage.\n```\nInput: garbage = ["MMM","PGM","GP","M"], travel = [3,10,5]\n```\n\nThe last house has `M` garbage. At index 2 house, there is no `M`. At index 1 and 0 houses, there are `M`.\n\nIf we iterate through from the beginning, it\'s hard to know whether the `M` truck should go to `index 2` or not. But if we iterate through from the last, we are sure that the `M` truck must go to `index 2` because we know that there is `M` garbage in the last house. (As I explain eariler, each truck must visit each house **in order**, so the `M` truck must go to `index 2`).\n\n\n---\n\n\u2B50\uFE0F Points\n\nIterate through from the end, so that we are sure whether each truck goes next or not.\n\n---\n\nLet\'s see one by one.\n\n```\nInput: garbage = ["MMM","PGM","GP","M"], travel = [3,10,5]\n```\nCount number of garbages.\n```\nres = 9\n```\nIterate `travel` from the end (= iterate garbage from the end). The reason why we iterate `travel` is that we want to iterate `travel` and `garbage` at the same time but travel is always shorter than `garbage`, so we don\'t have to care about out of bounds.\n\nBetween the `index 3` and `index 2`, travel time is `5` and there is only `M`, so\n\n```\n["MMM","PGM","GP","M"]\n \u2191(= i)\n[3,10,5]\n \u2191(= i - 1)\nres += travel time * (M + P + G)\nres += 5 * (1 + 0 + 0)\nres = 14 (= 9 + 5)\n```\n`(M + P + G)` is number of each truck, `0` or `1`. In this case, Only `M` truck needs to go to the last house.\n\nTravel time index should be current index(i) - 1, because number of travel time is total number of houses - 1.\n\n```\n["MMM","PGM","GP","M"]\n 3 10 5\n```\n\nMove previous house. Travel time is `10`. There is `G` and `P`.\n\n```\n["MMM","PGM","GP","M"]\n \u2191(= i)\n[3,10,5]\n \u2191(= i - 1)\n\nres += travel time * (M + P + G)\nres += 10 * (1 + 1 + 1)\nres = 44\n```\nThere is no `M` garbage at `index 2`, but we know that `M` truck must go to the last house, so `M` truck is always `1`. More precisely, once the flags turn true, the flags are always true, because the trucks must go to the next house.\n\nMove previous house. Travel time is `3`. There are garbages of `P`, `G`, `M`.\n\n```\n["MMM","PGM","GP","M"]\n \u2191(= i)\n[3,10,5]\n \u2191(= i - 1)\n\nres += travel time *(M + P + G)\nres += 3 * (1 + 1 + 1)\nres = 53\n```\nThen finish iteration. We don\'t have to go to the first house because we already added number of garbages at `index 0` and travel time `3` * `3` trucks which is between `index 0` and `index 1`.\n\n```\nOutput: 53\n```\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n\n### Algorithm Overview:\n\nAt first, add number of garbages to result, then iterate through from the last index.\n\n### Detailed Explanation:\n\n1. **Initialization**: \n```\nres = 0\n```\nStart with initializing the total time (`res`) to 0.\n\n2. **Process Garbage Sizes**:\n```\nfor g in garbage:\n res += len(g)\n```\nFor each house, add the length of the garbage string to `res`. This step accounts for the time spent picking up garbage at each house.\n\n3. **Initialize Garbage Type Flags**:\n```\ng, p, m = False, False, False\n```\nSet boolean flags to track the presence of different types of garbage.\n\n4. **Update Garbage Type Flags**:\n```\nfor i in range(len(travel), 0, -1):\n m = m or \'M\' in garbage[i]\n p = p or \'P\' in garbage[i]\n g = g or \'G\' in garbage[i]\n\n res += travel[i-1] * (m + p + g)\n```\nBegin traversing the houses backward, starting from the last one. Check each garbage string for the presence of \'M\',\'P\', or \'G\', and update the corresponding boolean flags. For each house, calculate its contribution to the total time based on the travel time and the sum of boolean flags. Accumulate the calculated contribution to the total time.\n\n5. **Return Result**:\n```\nreturn res\n```\nOnce all houses are processed, return the final total time as the minimum number of minutes needed to pick up all the garbage.\n\nThis algorithm efficiently calculates the minimum time required for garbage collection based on the given conditions.\n\n\n# Complexity\n- Time complexity: $$O(T * G)$$\n`T` is length of `travel` variable and `G` is average time to find garbage in garbage string. But once we found the garbage, it will be $$O(T)$$. In reality, I think it\'s faster than this time complexity. In fact, this code beats more than 98%.\n\n- Space complexity: $$O(1)$$\n\n```python []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n res = 0\n \n for g in garbage:\n res += len(g)\n\n m, p, g = False, False, False\n\n for i in range(len(travel), 0, -1):\n m = m or \'M\' in garbage[i]\n p = p or \'P\' in garbage[i]\n g = g or \'G\' in garbage[i]\n\n res += travel[i-1] * (m + p + g)\n \n return res\n```\n```javascript []\n/**\n * @param {string[]} garbage\n * @param {number[]} travel\n * @return {number}\n */\nvar garbageCollection = function(garbage, travel) {\n let res = 0;\n\n for (const g of garbage) {\n res += g.length;\n }\n\n let [m, p, g] = [false, false, false];\n\n for (let i = travel.length; i > 0; i--) {\n m = m || garbage[i].includes(\'M\');\n p = p || garbage[i].includes(\'P\');\n g = g || garbage[i].includes(\'G\');\n\n res += travel[i - 1] * (m + p + g);\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int res = 0;\n\n for (String g : garbage) {\n res += g.length();\n }\n\n boolean m = false, p = false, g = false;\n\n for (int i = travel.length; i > 0; i--) {\n m = m || garbage[i].contains("M");\n p = p || garbage[i].contains("P");\n g = g || garbage[i].contains("G");\n\n res += travel[i-1] * ((m ? 1 : 0) + (p ? 1 : 0) + (g ? 1 : 0));\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int garbageCollection(std::vector<std::string>& garbage, std::vector<int>& travel) {\n int res = 0;\n\n for (const string& g : garbage) {\n res += g.length();\n }\n\n bool m = false, p = false, g = false;\n\n for (int i = travel.size(); i > 0; i--) {\n m = m || garbage[i].find("M") != string::npos;\n p = p || garbage[i].find("P") != string::npos;\n g = g || garbage[i].find("G") != string::npos;\n\n res += travel[i-1] * ((m ? 1 : 0) + (p ? 1 : 0) + (g ? 1 : 0));\n }\n\n return res;\n }\n};\n```\n\n---\n\n##### Python Tips\n\n`m`, `p` and `g` are boolean flags. Python considers `True` as `1` and `False` as `0`, so please execute this if you want to check.\n\n```\nprint(True + 1) # 2\nprint(False + 1) # 1\n```\nThat\'s why we can calculate like this.\n\n```\nres += travel[i-1] * (m + p + g)\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/count-nice-pairs-in-an-array/solutions/4312501/video-give-me-6-minutes-hashmap-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/424EOdu4TeY\n\n\u25A0 Timeline\u3000of the video\n\n`0:04` Think about how we calculate the answer\n`0:58` Demonstrate how it works\n`3:58` Coding\n`5:53` Time Complexity and Space Complexity\n`6:11` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/solutions/4306758/video-give-me-9-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/Tf69tOpE4GE\n\n\u25A0 Timeline of the video\n\n`0:05` Try to find a solution pattern\n`1:44` What if we have the same numbers in input array?\n`5:37` Why it works when we skip reduction\n`7:22` Coding\n`8:52` Time Complexity and Space Complexity
53
0
['C++', 'Java', 'Python3', 'JavaScript']
5
minimum-amount-of-time-to-collect-garbage
find last index, java
find-last-index-java-by-clasiqh-em3o
Solution:\n for every character add 1 to your sum for pickup time.\n find the last index of each type of garbage, use prefix sum to find travel time till that i
clasiqh
NORMAL
2022-08-28T04:00:28.796050+00:00
2022-08-30T08:58:24.810044+00:00
2,502
false
**Solution:**\n* for every character add 1 to your sum for pickup time.\n* find the last index of each type of garbage, use prefix sum to find travel time till that index.\n\n**Code:**\n\n public int garbageCollection(String[] gar, int[] travel) {\n int p=0, m=0, g=0, sum=0;\n\n for(int i=0; i<gar.length; i++){\n for(char ch : gar[i].toCharArray()){\n if(ch==\'P\') p = i;\n else if(ch==\'M\') m = i;\n else if(ch==\'G\') g = i;\n sum++; // add 1 min for every pick-up\n }\n }\n \n for(int i=1; i<travel.length; i++)\n travel[i] = travel[i]+travel[i-1];\n \n\t\tif(p!=0) sum+= travel[p-1]; // travel time till last P\n if(m!=0) sum += travel[m-1]; // travel time till last M\n if(g!=0) sum += travel[g-1]; // travel time till last G\n return sum;\n }
43
5
['Prefix Sum', 'Java']
5
minimum-amount-of-time-to-collect-garbage
🚀 Easy Iterative Approach || Explained Intuition🚀
easy-iterative-approach-explained-intuit-kttb
Problem Description\n\nGiven an array garbage representing the types of garbage at each house (M for metal, P for paper, G for glass), and an array travel repre
MohamedMamdouh20
NORMAL
2023-11-20T02:29:36.800858+00:00
2023-11-20T04:14:39.950118+00:00
6,498
false
# Problem Description\n\nGiven an array `garbage` representing the types of garbage at each house (`M` for metal, `P` for paper, `G` for glass), and an array `travel` representing the travel time between consecutive houses, **determine** the **minimum** number of minutes needed for three garbage trucks to pick up all the garbage. Each truck is responsible for **one** type of garbage, and they must visit the houses **in order**, with only **one** truck operating at a time.\n\nThe time required to pick up `one` unit of any type of garbage is `1` minute. The trucks start at house `0` and move sequentially, but they don\'t need to visit every house. While one truck is in operation, the other two trucks are **idle**.\n\nReturn the **minimum** total time required to collect all the garbage, considering the travel time between houses and the time required to pick up the garbage at each house.\n\n- **Constraints:**\n - Only one truck operates at a time. \n - $2 <= garbage.length <= 10^5$\n - garbage[i] consists of only the letters \'M\', \'P\', and \'G\'.\n - $1 <= garbage[i].length <= 10$\n - $travel.length == garbage.length - 1$\n - $1 <= travel[i] <= 100$\n\n\n\n---\n\n\n\n# Intuition\n\nHi there, \uD83D\uDE04\n\nLet\'s dive\uD83E\uDD3F deep into our today\'s problem.\nIn today\'s problem we have array of `N` houses\uD83C\uDFE0 in the same town and we are required to collect garbage from all these houses. There are **three** types of garbages: `Metal`, `Paper` and `Glass`. Each type has its own truck and oen truck\uD83D\uDE9A\uD83D\uDE9B is operating at a time.\n\nSeems neat problem.\uD83D\uDE00\nHow can we start with this problem ?\uD83E\uDD14\nWe can notice that we have two arrays `garbage` which indicate sgarbages in each house and `travel` which indicates the required time to travel two consecutive houses.\n\n- There two important things we want to take care of:\uD83E\uDD28\n - a truck **do not need** to visit all houses.\uD83E\uDD2F\n - Let\'s say there is glass garbage in house 6, then glass truck must also visit house 0, 1, 2....5 until it reaches 6.\uD83D\uDE14\n\nFirst thing that we can think about is why not we see how far can each truck go?\uD83E\uDD14\nFor example for Glass truck if we have 10 houses and houses from 6 to 10 don\'t have glass garbage then this truck will stop at house 5 and not continue.\uD83E\uDD29\n\nGood what then ? \uD83E\uDD14\nWe can **accumulate** time needed to reach each house using the `travel` array and for each maximum house for each truck we add it to our total answer.\n\nWhat about the real garbage collecting ?\uD83E\uDD28\nWe didn\'t talk about this since it is the **easiest** part\uD83E\uDD29. Only **sum** number of garbage in each house. We don\'t have to handle it in special way since all the garbage are similar and it takes take one second to collect one unit.\n\nLet\'s see some examples.\n```\ngarbage = ["G","P","GP","GG"], travel = [2,4,3]\n\nTime to collect all garbage = 1 + 1 + 2 + 2 = 6\n\nMaximum distance for each truck:\nG -> 3\nP -> 2\nM -> 0\n\nTime for each truck to reah its maximum house:\nG -> 2 + 4 + 3 = 9\nP -> 2 + 4 = 6\nM -> 0\n\nTotal time = 6 + 9 + 6 + 0 = 21\n```\n\n\n```\ngarbage = ["P","M","G","GG","MM"], travel = [2,4,3,5]\n\nTime to collect all garbage = 1 + 1 + 1 + 2 + 2 = 7\n\nMaximum distance for each truck:\nG -> 3\nP -> 0\nM -> 4\n\nTime for each truck to reah its maximum house\nG -> 2 + 4 + 3 = 9\nP -> 0\nM -> 2 + 4 + 3 + 5 = 14\n\nTotal time = 9 + 14 + 0 + 7 = 30\n\n```\n\n### Note\nFor **determining** the time for each truck to reach its **maximum** house we can use **prefix sum** array and get the index for each house for each truck but since there are only **three** trucks, In my code implementation I didn\'t make an array and just **looped** over all the travel array to get the **maximum** time for each house which resulted in space complexity of `O(1)`. \uD83E\uDD29\nIf we had **large** number of trucks instead of `3` then it would be better to implement real prefix sum array.\uD83D\uDE03\n\nAnd this is the solution for our today\'S problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n---\n\n\n\n# Approach\n\n1. **Initialize Variables:**\n - `totalMinutes`: Set to `0`, representing the **total** minutes needed for garbage collection.\n - `lastGarbageIndices`: Initialize a vector of size `3` with values `-1`, tracking the last occurrence indices of `M`, `P`, and `G` garbage types.\n2. **Calculate Initial Time:**\n - Add the size of the garbage at the first house to `totalMinutes` Since all the truck are at the first house initially.\n3. **Update Last Occurrence Indices:**\n - Iterate through each house starting from the second house.\n - Add the size of garbage at the current house to `totalMinutes`.\n - Update the last occurrence indices for \'M\', \'P\', and \'G\' garbage types based on their presence in the current house.\n4. **Travel Time Calculation:**\n - Iterate through each travel segment in the `travel` vector.\n - Add the current travel time to `currentTravelTime` as a **Prefix Sum**.\n - For each garbage truck type (`M`, `P`, `G`), check if its last occurrence index matches the current travel index.\n - If there is a match, add the current travel time to `totalMinutes`, representing the time spent collecting garbage during travel.\n6. **Return Result:**\n - Return the final value of `totalMinutes`, representing the minimum total time needed to pick up all the garbage.\n\n\n# Complexity\n- **Time complexity:** $O(N)$\nSince we are iterating over our garbage array to get last index of each garbage type then it takes `O(N)` then we are iterating over our travelling array which take also `O(N)` so total complexity is `2N` which is `O(N)`.\nWhere N is number of houses in garbage array.\n**FirstNote:** Complexity of first for-loop is `N*house_size` and since the house size is `10` then its complexity is `10*N` which is `O(N)`.\n**SecondNote:** Complexity of second for-loop is `N*garbage_type` and since the garpage type is `3` then its complexity is `3*N` which is `O(N)`.\n\n- **Space complexity:** $O(1)$\nSince we are only using constant space variables that doesn\'t depend on the input size.\n\n\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n long long totalMinutes = 0; // Total minutes needed for garbage collection\n long long currentTravelTime = 0; // Current travel time\n\n // Add the initial minutes required to collect garbage at the first house\n totalMinutes += garbage[0].size();\n\n vector<int> lastGarbageIndices(3, -1); // Keep track of the last occurrence of each type of garbage\n\n // Iterate through each house starting from the second house\n for (int houseIndex = 1; houseIndex < garbage.size(); houseIndex++) {\n // Add the minutes required to collect garbage at the current house\n totalMinutes += garbage[houseIndex].size();\n\n // Update the indices of the last occurrence of each type of garbage\n if (garbage[houseIndex].find("M") != garbage[houseIndex].npos) \n lastGarbageIndices[0] = houseIndex - 1;\n if (garbage[houseIndex].find("P") != garbage[houseIndex].npos) \n lastGarbageIndices[1] = houseIndex - 1;\n if (garbage[houseIndex].find("G") != garbage[houseIndex].npos) \n lastGarbageIndices[2] = houseIndex - 1;\n }\n\n // Iterate through each travel segment\n for (int travelIndex = 0; travelIndex < travel.size(); travelIndex++) {\n // Add the current travel time\n currentTravelTime += travel[travelIndex];\n\n // Add the minutes required to collect garbage if a garbage truck is at the corresponding house\n for (int truckIndex = 0; truckIndex < 3; truckIndex++) {\n if (lastGarbageIndices[truckIndex] == travelIndex) {\n totalMinutes += currentTravelTime;\n }\n }\n }\n\n return totalMinutes;\n }\n};\n```\n```Java []\npublic class Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n long totalMinutes = 0; // Total minutes needed for garbage collection\n long currentTravelTime = 0; // Current travel time\n\n // Add the initial minutes required to collect garbage at the first house\n totalMinutes += garbage[0].length();\n \n // Keep track of the last occurrence of each type of garbage\n List<Integer> lastGarbageIndices = new ArrayList<>(List.of(-1, -1, -1)); \n\n // Iterate through each house starting from the second house\n for (int houseIndex = 1; houseIndex < garbage.length; houseIndex++) {\n // Add the minutes required to collect garbage at the current house\n totalMinutes += garbage[houseIndex].length();\n\n // Update the indices of the last occurrence of each type of garbage\n if (garbage[houseIndex].contains("M")) {\n lastGarbageIndices.set(0, houseIndex - 1);\n }\n if (garbage[houseIndex].contains("P")) {\n lastGarbageIndices.set(1, houseIndex - 1);\n }\n if (garbage[houseIndex].contains("G")) {\n lastGarbageIndices.set(2, houseIndex - 1);\n }\n }\n\n // Iterate through each travel segment\n for (int travelIndex = 0; travelIndex < travel.length; travelIndex++) {\n // Add the current travel time\n currentTravelTime += travel[travelIndex];\n\n // Add the minutes required to collect garbage if a garbage truck is at the corresponding house\n for (int truckIndex = 0; truckIndex < 3; truckIndex++) {\n if (lastGarbageIndices.get(truckIndex) == travelIndex) {\n totalMinutes += currentTravelTime;\n }\n }\n }\n\n return (int) totalMinutes;\n }\n}\n```\n```Python []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n total_minutes = 0 # Total minutes needed for garbage collection\n current_travel_time = 0 # Current travel time\n\n # Add the initial minutes required to collect garbage at the first house\n total_minutes += len(garbage[0])\n\n last_garbage_indices = [-1, -1, -1] # Keep track of the last occurrence of each type of garbage\n\n # Iterate through each house starting from the second house\n for house_index in range(1, len(garbage)):\n # Add the minutes required to collect garbage at the current house\n total_minutes += len(garbage[house_index])\n\n # Update the indices of the last occurrence of each type of garbage\n if "M" in garbage[house_index]:\n last_garbage_indices[0] = house_index - 1\n if "P" in garbage[house_index]:\n last_garbage_indices[1] = house_index - 1\n if "G" in garbage[house_index]:\n last_garbage_indices[2] = house_index - 1\n\n # Iterate through each travel segment\n for travel_index in range(len(travel)):\n # Add the current travel time\n current_travel_time += travel[travel_index]\n\n # Add the minutes required to collect garbage if a garbage truck is at the corresponding house\n for truck_index in range(3):\n if last_garbage_indices[truck_index] == travel_index:\n total_minutes += current_travel_time\n\n return total_minutes\n```\n```C []\nint garbageCollection(char** garbage, int garbageSize, int* travel, int travelSize) {\n long long totalMinutes = 0; // Total minutes needed for garbage collection\n long long currentTravelTime = 0; // Current travel time\n\n // Add the initial minutes required to collect garbage at the first house\n totalMinutes += strlen(garbage[0]);\n\n int lastGarbageIndices[3] = {-1, -1, -1}; // Keep track of the last occurrence of each type of garbage\n\n // Iterate through each house starting from the second house\n for (int houseIndex = 1; houseIndex < garbageSize; houseIndex++) {\n // Add the minutes required to collect garbage at the current house\n totalMinutes += strlen(garbage[houseIndex]);\n\n // Update the indices of the last occurrence of each type of garbage\n if (strchr(garbage[houseIndex], \'M\') != NULL)\n lastGarbageIndices[0] = houseIndex - 1;\n if (strchr(garbage[houseIndex], \'P\') != NULL)\n lastGarbageIndices[1] = houseIndex - 1;\n if (strchr(garbage[houseIndex], \'G\') != NULL)\n lastGarbageIndices[2] = houseIndex - 1;\n }\n\n // Iterate through each travel segment\n for (int travelIndex = 0; travelIndex < travelSize; travelIndex++) {\n // Add the current travel time\n currentTravelTime += travel[travelIndex];\n\n // Add the minutes required to collect garbage if a garbage truck is at the corresponding house\n for (int truckIndex = 0; truckIndex < 3; truckIndex++) {\n if (lastGarbageIndices[truckIndex] == travelIndex) {\n totalMinutes += currentTravelTime;\n }\n }\n }\n\n return (int)totalMinutes;\n}\n```\n\n\n\n![HelpfulJerry.jpg](https://assets.leetcode.com/users/images/c5999377-ae2e-409e-a4ed-0e47dfe85b72_1700445947.4942496.jpeg)\n
42
1
['Array', 'String', 'C', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3']
2
minimum-amount-of-time-to-collect-garbage
C++/Python loop & accumulate||94ms Beats 100%
cpython-loop-accumulate94ms-beats-100-by-tos7
Intuition\n Describe your first thoughts on how to solve this problem. \n\ntotal time=time for collecting garbage + time for traveling\n\nDivide the questions i
anwendeng
NORMAL
2023-11-20T01:27:22.917143+00:00
2023-11-20T23:30:01.278342+00:00
3,554
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\ntotal time=time for collecting garbage + time for traveling\n```\nDivide the questions into 2 parts; it might make the solution easier.\ntime for collecting garbage is very easy; other is also not difficult.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach item costs 1 unit time to collect it. Count them.\nDuring the iteration find the last indices for items G, P, M.\nUsing accumulate/sum to sum up the travel time.\n\nThe instruction\n```\nif (tG==0 && x.find(\'G\')!=-1) tG=i;\n```\nchecks whether `tG==0`, if not, it does nothing; when `tG==0` then it checks whether ` x.find(\'G\')!=-1`, if yes, set `tG=i`.\n\nSince the iteration is backward, if the \'G\', \'P\', \'M\' are already found, the `x.find` will not proceed & it saves time.\n\nPython code is also provided in the same manner.\n\n[Please turn on English subtitles if necessary]\n[https://youtu.be/TveVxO7mdsI?si=ELYhMCD0em8d-BZk](https://youtu.be/TveVxO7mdsI?si=ELYhMCD0em8d-BZk)\n\nRevised code is faster & runs in 94ms beats 100%. The computing part for travel time uses a loop by one pass.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# C++ Code 107ms beats 100%\n```C++ []\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) \n {\n int n=garbage.size();\n int tG=0, tP=0, tM=0;\n int time=0; \n #pragma unroll\n for(int i=n-1; i>=0; i--){//time for collecting garbage\n string x=garbage[i];\n time+=x.size();\n if (tG==0 && x.find(\'G\')!=-1) tG=i;\n if (tP==0 && x.find(\'P\')!=-1) tP=i;\n if (tM==0 && x.find(\'M\')!=-1) tM=i;\n }\n // Add travel time\n time+=accumulate(travel.begin(), travel.begin()+(tG),0)\n +accumulate(travel.begin(), travel.begin()+(tP),0)\n +accumulate(travel.begin(), travel.begin()+(tM),0);\n return time;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n```python []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n n=len(garbage)\n tG, tP, tM=0, 0, 0\n Time=0\n for i in range(n-1, -1, -1):\n x=garbage[i]\n Time+=len(x)\n if tG==0 and x.find(\'G\')!=-1: tG=i \n if tP==0 and x.find(\'P\')!=-1: tP=i\n if tM==0 and x.find(\'M\')!=-1: tM=i\n Time+=sum(travel[:tG])+sum(travel[:tP])+sum(travel[:tM])\n return Time\n\n \n```\n![2391.jpg](https://assets.leetcode.com/users/images/1d844fbc-f0c2-45d0-b66b-f460b9ca39c5_1700449351.0522468.jpeg)\n\n# Revised code runs in 94ms & beats 100% \n```\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) \n {\n const int n=garbage.size();\n const char* GPM="GPM";\n int time=0, t[3]={0}; \n #pragma unroll\n for(int i=n-1; i>=0; i--){//time for collecting garbage\n string& x=garbage[i];\n time+=x.size();\n #pragma unroll\n for(int j=0; j<3; j++)\n if (t[j]==0 && x.find(GPM[j])!=-1) t[j]=i;\n \n }\n sort(t, t+3);\n // Add travel time\n #pragma unroll\n for(int i=0; i<t[2]; i++){\n int c=(i<t[0])?3:((i<t[1])?2:1);\n time+=c*travel[i];\n }\n return time;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n\n```
22
2
['Array', 'String', 'C++', 'Python3']
3
minimum-amount-of-time-to-collect-garbage
[Python3] Greedy + prefix sum || beats 100%
python3-greedy-prefix-sum-beats-100-by-y-biwm
Intuition\n- Find last position (the most right house) for each type of garbage.\n- Find distance for every house using prefix sum (use itertools.accumulate to
yourick
NORMAL
2023-11-20T02:09:10.608908+00:00
2023-11-20T02:17:04.353646+00:00
958
false
# Intuition\n- Find last position (the most right house) for each type of garbage.\n- Find distance for every house using prefix sum (use [`itertools.accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate) to simplify code).\n- Don\'t forget to count the garbage (1 sek to peek 1 unit of any garbage).\n\n```The code below are almost the same, a difference only in type of iteration (while or for loops).```\n```python3 []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n peekGarbageTime = endM = endP = endG = 0\n i = len(garbage) - 1\n\n while i >=0:\n peekGarbageTime += len(garbage[i])\n if not endM and \'M\' in garbage[i]: endM = i\n if not endP and \'P\' in garbage[i]: endP = i\n if not endG and \'G\' in garbage[i]: endG = i\n i -= 1\n\n dist = list(accumulate(travel, initial = 0))\n\n return dist[endM] + dist[endP] + dist[endG] + peekGarbageTime\n```\n```python3 []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n peekGarbageTime = endM = endP = endG = 0\n\n for i, g in reversed(list(enumerate(garbage))):\n peekGarbageTime += len(g)\n if not endM and \'M\' in g: endM = i\n if not endP and \'P\' in g: endP = i\n if not endG and \'G\' in g: endG = i\n\n dist = list(accumulate(travel, initial = 0))\n\n return dist[endM] + dist[endP] + dist[endG] + peekGarbageTime\n```\n![Screenshot 2023-11-20 at 04.56.19.png](https://assets.leetcode.com/users/images/1cf682f9-295b-40d7-968e-86e41c9c3591_1700445830.6312344.png)\n
20
0
['Greedy', 'Prefix Sum', 'Python', 'Python3']
3
minimum-amount-of-time-to-collect-garbage
Beats 100% | time O(n) | space O(n)
beats-100-time-on-space-on-by-dee_coder0-k95d
Code\n\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int totalTime = 0;\n int len = garbage.length;\n
dee_coder01
NORMAL
2022-12-25T06:28:35.687690+00:00
2022-12-25T06:29:05.865741+00:00
2,322
false
# Code\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int totalTime = 0;\n int len = garbage.length;\n totalTime+=1*garbage[0].length();\n for(int i = 1; i<len; i++){\n totalTime+=1*garbage[i].length();\n totalTime+=3*travel[i-1]; \n }\n boolean foundG = garbage[len-1].contains("G");\n boolean foundP = garbage[len-1].contains("P");\n boolean foundM = garbage[len-1].contains("M");\n for(int i = len-1; i>=1; i--){\n if(!foundG)foundG = garbage[i].contains("G");\n if(!foundP)foundP = garbage[i].contains("P");\n if(!foundM)foundM = garbage[i].contains("M");\n if(foundP && foundG && foundM)break;\n if(!foundG)totalTime-=travel[i-1];\n if(!foundP)totalTime-=travel[i-1];\n if(!foundM)totalTime-=travel[i-1];\n }\n return totalTime;\n }\n}\n```
15
0
['Java']
4
minimum-amount-of-time-to-collect-garbage
python explained solution easy
python-explained-solution-easy-by-nitish-yx5h
Calculate count of paper,glass and metal and total time taken to collecte each one of them. \nTotal time taken can be calculated by the index of the last house
nitish3170
NORMAL
2022-08-28T05:20:54.855453+00:00
2022-09-01T19:27:46.422002+00:00
1,461
false
Calculate count of paper,glass and metal and total time taken to collecte each one of them. \nTotal time taken can be calculated by the index of the last house with that item and adding the total time taken to reach that house.\nAdd all value and return.\n\n**CODE:**\n```\ndef garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n count_paper,count_glass,count_metal=0,0,0\n paper_idx,glass_idx,metal_idx=-1,-1,-1\n\n for i in range(len(garbage)):\n if \'P\' in garbage[i]:\n # update index and count of paper\n paper_idx=i\n count_paper+=garbage[i].count(\'P\')\n if \'G\' in garbage[i]:\n # update index and count of glass\n glass_idx=i\n count_glass+=garbage[i].count(\'G\')\n if \'M\' in garbage[i]:\n # update index and count of metal\n metal_idx=i\n count_metal+=garbage[i].count(\'M\')\n\n # calculate cumulative time\n time=[]\n time.append(0)\n for i in range(len(travel)):\n time.append(time[-1]+travel[i])\n\n res=0\n res+=(time[paper_idx] if paper_idx!=-1 else 0) +(time[glass_idx] if glass_idx!=-1 else 0) + (time[metal_idx] if metal_idx!=-1 else 0)\n \n res+=count_paper+count_glass+count_metal\n return res\n```\n**Time Complexity:- O(N)**\n\n```\ntime=[]\ntime.append(0)\nfor i in range(len(travel)):\n\t\ttime.append(time[-1]+travel[i])\nres=0\nfor type in ["P","G","M"]:\n\tcnt=0\n\tidx=0\n\tfor i in range(len(garbage)):\n\t\tif type in garbage[i]:\n\t\t\t# update index and count\n\t\t\tidx=i\n\t\t\tcnt+=garbage[i].count(type)\n\tres+=cnt+time[idx]\nreturn res\n```\n\n
14
0
['Prefix Sum', 'Python']
1
minimum-amount-of-time-to-collect-garbage
✅C++ | ✅Count | ✅Easy & efficient solution
c-count-easy-efficient-solution-by-yash2-qbc5
\nclass Solution \n{\npublic:\n int garbageCollection(vector<string>& gar, vector<int>& tra) \n {\n int cnt=0;\n int last_g=0, last_p=0, las
Yash2arma
NORMAL
2022-08-28T04:46:27.278125+00:00
2022-08-28T05:05:37.224469+00:00
1,552
false
```\nclass Solution \n{\npublic:\n int garbageCollection(vector<string>& gar, vector<int>& tra) \n {\n int cnt=0;\n int last_g=0, last_p=0, last_m=0;\n \n for(int i=0; i<gar.size(); i++)\n {\n for(auto it:gar[i])\n {\n //finding last index of a type of garbage\n if(it==\'M\') last_m=i;\n else if(it==\'P\') last_p=i;\n else last_g=i;\n cnt++; //for any type of garbage it take 1 unit time\n }\n }\n \n int tot=cnt;\n \n //use the prefix sum to find time taken in traveling\n int sum=0;\n for(int i=0; i<tra.size(); i++)\n {\n sum += tra[i];\n if(last_g==i+1) tot += sum;\n if(last_p==i+1) tot += sum;\n if(last_m==i+1) tot += sum; \n }\n return tot;\n \n \n }\n};\n```
14
2
['C', 'Prefix Sum', 'C++']
1
minimum-amount-of-time-to-collect-garbage
Adhoc 2 Pass || with explanation || O(1) Space
adhoc-2-pass-with-explanation-o1-space-b-qias
Intuition\n Just a adhoc problem by seeing how the test cases are working.\n \nObservation\n \n 1. We have to take either all \'M\' or all \'P\' or al
xxvvpp
NORMAL
2022-08-28T04:03:23.220782+00:00
2022-08-29T07:40:17.430516+00:00
939
false
**Intuition**\n Just a adhoc problem by seeing how the test cases are working.\n \n**Observation**\n \n 1. We have to take either all **\'M\'** or all **\'P\'** or all **\'G\'** together at one iteration.\n 2. The **time of travel after the last position of each character from left will not be counted in total cost**.\n \n They just confused by saying it a **minimum time**, there is no **minimum**.\n They just told to **follow the algorithm** and return the **total cost by following given rules.**\n \n For fullfilling the second point, I used 3 variables to keep a mark of last occurence from **left**.\n This mark for each will **prevent us from increasing cost of pick after the last occurence of a character is reached**.\n \n Now we just have to do 3 iteration each for **\'M\'**, **\'P\'** and **\'G\'** and collect total cost\n \n **Time** - O(`n * 10`) [In worst case]\n **Space** - O(`1`)\n<iframe src="https://leetcode.com/playground/cs6xPPHJ/shared" frameBorder="0" width="800" height="500"></iframe>
14
6
['C', 'Java']
3
minimum-amount-of-time-to-collect-garbage
Easy C++ code with intuition, optimization, complexity analysis
easy-c-code-with-intuition-optimization-udryg
\n# Intuition\n\nLet\'s say we find time taken for one type. \n- We start from first house, then check if this house has that grabage or not. If it has we picku
sachuverma
NORMAL
2022-08-28T04:01:15.289235+00:00
2022-08-28T04:01:48.717094+00:00
1,277
false
\n# Intuition\n\nLet\'s say we find time taken for one type. \n- We start from first house, then check if this house has that grabage or not. If it has we pickup the garbage and calculate cost to travel to this house from last house which had same garbage.\n- Otherwise, we just go to next house.\n\nWe repreat this process three times, once for each type, Papre, Glass, and Metal.\n\n<br />\n \n# Some Optimizations:\n\n- Either you can calculate cost to travel from \'ith\' house to \'jth\' house on traversing from \'i\' to \'j\' in travel array every time. Or you can keep **prefix sum array** to find travel cost between two indices in constant time.\n We keep previous house marked and move forward to next house when a house with same type of garbage comes, we calculate travel cost from prev house to current in constant time.\n\n- This is minor optimization, To find if current house has \'X\' type of garbage or not, either you can traverse on string every time in for loop. Or you can keep this result precomputed in a hashmap.\n\n<br />\n \n# Code:\n\n```c++\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int ans = 0;\n int n = garbage.size();\n int m = travel.size();\n \n // Precomputation: To find time to travel from i to j house in O(1).\n vector<int> prefix(m + 1, 0);\n for (int i = 0; i < m; ++i) {\n prefix[i + 1] = prefix[i] + travel[i];\n }\n \n // Precomputation: Mark is a house has that garbage.\n vector<unordered_map<char,int>> have (n, unordered_map<char,int>());\n for (int i = 0; i < n; ++i) {\n for (auto garb : garbage[i]) {\n have[i][garb]++;\n }\n }\n \n // For each type of the truck.\n for (auto type : {\'P\', \'G\', \'M\'}) {\n int prevHouse = 0;\n for (int currHouse = 0; currHouse < n; ++currHouse) {\n // Check is current house has that type of waste.\n if (have[currHouse][type] > 0) {\n // Then we need 1 min for each item of that type to pick up.\n ans += have[currHouse][type];\n \n // If we are at first house we don\'t add time taken to travel from prev location to current location.\n if (currHouse != 0) {\n // Otherwise we add and update prev location variable.\n ans += prefix[currHouse] - prefix[prevHouse];\n prevHouse = currHouse;\n }\n }\n }\n }\n \n return ans;\n }\n};\n```\n\n<br />\n\n### If `N` is size of garbage array, `L` is length of garbage array string, and `M` is length of travel array.\n \n# Time Complexity:\n\n- We traverse on travel array once which takes `O(M)` time.\n- Then, we traverse on garbage array strings once which will take `O(N * L)` time.\n- Then, we traverse on gargabe array 3 times for each type of garbage, which takes `O(3 * N)` time.\n- Thus, overall complexity, `O((M) + (N * L) + (3 * N)) = O(M + NL)`. \n\n<br />\n \n# Space Complexity:\n \n- We have use two arrays `prefix` of size `M + 1` and `have` of size `3 * N`.\n- Thus, overall complexity, `O((M + 1) + (3 * N)) = O(M + N)`.
14
5
[]
5
minimum-amount-of-time-to-collect-garbage
Prefix Sum
prefix-sum-by-votrubac-fxm1
We need to track the distance to the last house with the garbage of each type.\n\nC++\ncpp\nint garbageCollection(vector<string>& garb, vector<int>& travel) {\n
votrubac
NORMAL
2022-08-28T04:02:11.739874+00:00
2022-08-28T05:57:55.900654+00:00
2,190
false
We need to track the distance to the last house with the garbage of each type.\n\n**C++**\n```cpp\nint garbageCollection(vector<string>& garb, vector<int>& travel) {\n int dist[128] = {};\n partial_sum(begin(travel), end(travel), begin(travel));\n for (int i = 1; i < garb.size(); ++i)\n for (auto g : garb[i])\n dist[g] = travel[i - 1];\n return accumulate(begin(garb), end(garb), 0, [](int sz, const auto& g) { return sz + g.size(); })\n + accumulate(begin(dist), end(dist), 0);\n}\n```
12
1
[]
2
minimum-amount-of-time-to-collect-garbage
✅✅C++ Easy and Simple O(N) solution ✅✅
c-easy-and-simple-on-solution-by-parziva-9923
Approach:\n1. We initialize three variables lastM, lastP, lastG to store the last occurences of each type of garbage.\n2. We then calculate the time for picking
Parzival1509
NORMAL
2023-11-20T06:27:37.470878+00:00
2023-11-20T06:27:37.470900+00:00
1,529
false
# Approach:\n1. We initialize three variables ```lastM, lastP, lastG``` to store the last occurences of each type of garbage.\n2. We then calculate the time for picking up the garbages, which is equal to the sum of length of all the strings and store it in ```ans``` variable.\n3. We then calculate the time to travel to the last indices of the garbages and add them to the ans.\n4. Return the ans.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity:\n- **Time complexity: O(N)**\nWe travel the array once to find the last occurences of each type of garbage, which takes O(N) time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity: O(1)**\nWe only use 3 extra variables to store the indices, which is constant space.\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 lastM = -1, lastP = -1, lastG = -1;\n \n // Finding the last house for each type of garbage\n for(int i = n - 1; i >= 0; i--) {\n if(lastM == -1 && garbage[i].find("M") != string::npos)\n lastM = i;\n if(lastP == -1 && garbage[i].find("P") != string::npos)\n lastP = i;\n if(lastG == -1 && garbage[i].find("G") != string::npos)\n lastG = i;\n\n // To avoid unnecessaray iterations\n if(lastM != -1 && lastP != -1 && lastG != -1)\n break;\n }\n \n int ans = 0;\n // Time to pick up garbage\n for(auto g: garbage)\n ans += g.size();\n\n // Time to travel\n if(lastM != -1)\n ans = accumulate(travel.begin(), travel.begin() + lastM, ans);\n if(lastP != -1)\n ans = accumulate(travel.begin(), travel.begin() + lastP, ans);\n if(lastG != -1)\n ans = accumulate(travel.begin(), travel.begin() + lastG, ans);\n\n return ans;\n }\n};\n```
11
0
['C++']
2
minimum-amount-of-time-to-collect-garbage
Easy javascript solution (16 lines)
easy-javascript-solution-16-lines-by-com-q192
\nconst garbageCollection = (garbage, travel) => {\n let travelTime = 0\n garbage = garbage.reverse()\n \n for (const type of [\'G\', \'P\', \'M\']) {\n
ComsiComsa
NORMAL
2022-09-18T15:26:30.016951+00:00
2022-09-18T15:41:56.924384+00:00
583
false
```\nconst garbageCollection = (garbage, travel) => {\n let travelTime = 0\n garbage = garbage.reverse()\n \n for (const type of [\'G\', \'P\', \'M\']) {\n const lastHouseWithGarbage = garbage.findIndex(house => house.includes(type))\n \n if (lastHouseWithGarbage === -1) {\n continue\n }\n\n travelTime += travel.slice(0, garbage.length - lastHouseWithGarbage - 1).reduce((acc, num) => acc + num, 0)\n }\n\n return garbage.join(\'\').length + travelTime\n}\n```
10
0
['JavaScript']
1
minimum-amount-of-time-to-collect-garbage
[Java/Python 3] Prefix sum of travel time.
javapython-3-prefix-sum-of-travel-time-b-u7wf
The time cost of each truck includes the following 2 parts:\n1. Gabage pick up time: depends on the total units of the specific type of gabage at all houses;\n2
rock
NORMAL
2022-08-28T04:06:18.816845+00:00
2022-08-28T14:52:39.341703+00:00
1,529
false
The time cost of each truck includes the following `2` parts:\n1. Gabage pick up time: depends on the total units of the specific type of gabage at all houses;\n2. Travel time: depends on the time cost from house `0` to the last house that has the type of gabage corresponding to the truck. We can use prefix sum to compute it.\n\n\n```java\n public int garbageCollection(String[] garbage, int[] travel) {\n int n = garbage.length, k = 0, pickupTime = 0;\n int[] prefixSum = new int[n];\n for (int t : travel) {\n prefixSum[k + 1] = prefixSum[k++] + t;\n }\n Map<Character, Integer> truckToTime = new HashMap<>();\n for (int i = 0; i < n; ++i) {\n pickupTime += garbage[i].length();\n for (char c : garbage[i].toCharArray()) {\n truckToTime.put(c, prefixSum[i]);\n }\n }\n return pickupTime + truckToTime.values().stream().mapToInt(i -> i).sum();\n }\n```\n\n```python\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n prefix_sum = [0]\n for t in travel:\n prefix_sum.append(prefix_sum[-1] + t)\n truck_to_time = {}\n for i, g in enumerate(garbage):\n for c in g:\n truck_to_time[c] = prefix_sum[i]\n return sum(truck_to_time.values()) + sum(map(len, garbage))\n```\n\n**Analysis:**\n\nTime & space: `O(n)`, where `n = garbage.length`.
10
0
['Java', 'Python3']
2
minimum-amount-of-time-to-collect-garbage
✔C++|Prefix Sum |O(N)| Easy✔
cprefix-sum-on-easy-by-xahoor72-yr6b
Intuition\n Describe your first thoughts on how to solve this problem. \nConcept is to use prefix sum as we have given time from one to another house instead xo
Xahoor72
NORMAL
2023-02-01T16:11:38.238651+00:00
2023-02-01T16:11:38.238683+00:00
837
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConcept is to use prefix sum as we have given time from one to another house instead xounting one by one from one to other house just find the last index at which certain type of grabage is present and count all the units of garbage presnt while traversing . \nAt last or answer will be total garbage units + time of each grabage upto its last index i.e where its lastly presnt. \nSo have prefix sum of time and when u find the last occurece of a agrbage just add that time upto that index in our answer.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPrefix Sum\n# Complexity\n- Time complexity:$$O(N*10)$$\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>& garb, vector<int>& trav) {\n int sum=0;\n int k=0;\n int mi=-1,gi=-1,pi=-1;\n for(int i=1;i<trav.size();i++)trav[i]=trav[i-1]+trav[i];\n for(auto x:garb){\n for(auto c:x){\n sum++;\n if(c==\'M\')mi=k;\n if(c==\'P\')pi=k;\n if(c==\'G\')gi=k;\n }\n k++;\n }\n sum+= ((mi>0)?trav[mi-1]:0);\n sum+= ((gi>0)?trav[gi-1]:0);\n sum+= ((pi>0)?trav[pi-1]:0);\n return sum;\n \n }\n};\n```
8
0
['Array', 'Prefix Sum', 'C++']
2
minimum-amount-of-time-to-collect-garbage
✅😍100% Beats Google Approach🔥🔥🔥
100-beats-google-approach-by-sourav_n06-lktj
Intuition\n Describe your first thoughts on how to solve this problem. \nI saw it on Instagram\n# Approach\n Describe your approach to solving the problem. \nIn
sourav_n06
NORMAL
2023-11-20T05:14:26.375605+00:00
2023-11-20T05:14:26.375633+00:00
1,731
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI saw it on Instagram\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInput: garbage = ["MMM","PGM","GP"], travel = [3,10]\nOutput: 37\nExplanation:\nThe metal garbage truck takes 7 minutes to pick up all the metal garbage.\nThe paper garbage truck takes 15 minutes to pick up all the paper garbage.\nThe glass garbage truck takes 15 minutes to pick up all the glass garbage.\nIt takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.\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 n = garbage.size();\n int G_idx = 0;\n int P_idx = 0;\n int M_idx = 0;\n int TimeToTake = 0;\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < garbage[i].size(); j++)\n {\n if(garbage[i][j] == \'M\')\n M_idx = i;\n else if(garbage[i][j] == \'P\')\n P_idx = i;\n else\n G_idx = i;\n TimeToTake++;\n }\n }\n\n for(int i = 1; i < travel.size(); i++)\n {\n travel[i] += travel[i - 1];\n }\n\n TimeToTake += (M_idx > 0) ? travel[M_idx-1] : 0;\n TimeToTake += (P_idx > 0) ? travel[P_idx-1] : 0;\n TimeToTake += (G_idx > 0) ? travel[G_idx-1] : 0;\n\n return TimeToTake;\n }\n};\n```
7
1
['Python', 'C++', 'Java', 'JavaScript']
2
minimum-amount-of-time-to-collect-garbage
Easy Python Solution using Prefix Sum
easy-python-solution-using-prefix-sum-by-1wqw
Important observation:\nAs For commute time, we only care about when a specific kind of garbage last appears. Because we can skip the remaining if that kind of
siyu_
NORMAL
2022-09-10T00:14:10.202018+00:00
2022-09-10T00:14:36.280251+00:00
526
false
Important observation:\nAs For commute time, we only care about when a specific kind of garbage **last appears**. Because we can skip the remaining if that kind of garbage doesn\'t appear anymore.\nTo make things easier, we will use **prefix sum** to help us do the calculation.\n\nTherefore, the algorithm is very intuitive: \n1) Go through the garbage list\na. Increment the res by the size of the garbage, because a unit will cost 1 minute\nb. Update indexes. After traversal, the indexes should be where each garbage last appears\n2) increment the res by calculating the commute time using prefix sum and indexes\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n\t\t\t# add 0 to prefix because for the first house the commute time is 0\n prefix = [0]\n cur = 0\n for time in travel:\n cur += time\n prefix.append(cur)\n\t\t\t# the default index is zero\n\t\t\t# it does not mean each grabage appears in the first house, only for calculation convenience\n M_idx, G_idx, P_idx = 0, 0, 0\n res = 0\n for i in range(len(garbage)):\n res += len(garbage[i])\n if "M" in garbage[i]:\n M_idx = i\n if "G" in garbage[i]:\n G_idx = i\n if "P" in garbage[i]:\n P_idx = i\n res += prefix[M_idx]\n res += prefix[G_idx]\n res += prefix[P_idx]\n \n return res\n\n```
7
0
['Counting', 'Prefix Sum', 'Python', 'Python3']
1
minimum-amount-of-time-to-collect-garbage
implementation + hashmap
implementation-hashmap-by-harshitmaurya-5pbm
\n\nSimply Find the limit for every \'P\',\'M\' and \'G\'\n\nthen loop for every garbage of type \'P\',\'M\' and \'G\' and add count of the garbage of current s
HarshitMaurya
NORMAL
2022-08-28T04:01:37.837179+00:00
2022-08-28T04:01:37.837222+00:00
794
false
\n\nSimply Find the limit for every \'P\',\'M\' and \'G\'\n\nthen loop for every garbage of type \'P\',\'M\' and \'G\' and add count of the garbage of current string and time cost till current house \n\n\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n long ans=0;\n \n int limit_m=-1,limit_p=-1,limit_g=-1;\n \n for(int i=garbage.length-1; i>=0; i--){\n \n if(limit_m>-1 && limit_g>-1 && limit_p>-1) break;\n \n for(char ch:garbage[i].toCharArray()){\n if(ch==\'M\' && limit_m==-1) limit_m=i;\n \n if(ch==\'P\' && limit_p==-1) limit_p=i;\n \n if(ch==\'G\' && limit_g==-1) limit_g=i;\n }\n }\n \n \n for(int i=0; i<=limit_m; i++){\n HashMap<Character,Integer> map=getCount(garbage[i]);\n \n int trcl=(i==0)?0:travel[i-1];\n \n if(map.containsKey(\'M\')){\n ans+=map.get(\'M\');\n }\n ans+=trcl;\n }\n \n for(int i=0; i<=limit_p; i++){\n HashMap<Character,Integer> map=getCount(garbage[i]);\n \n int trcl=(i==0)?0:travel[i-1];\n \n\n \n if(map.containsKey(\'P\')){\n ans+=map.get(\'P\');\n }\n \n\n \n ans+=trcl;\n }\n \n for(int i=0; i<=limit_g; i++){\n HashMap<Character,Integer> map=getCount(garbage[i]);\n \n int trcl=(i==0)?0:travel[i-1];\n \n if(map.containsKey(\'G\')){\n ans+=map.get(\'G\');\n }\n \n ans+=trcl;\n }\n \n return (int)ans;\n }\n \n HashMap<Character,Integer> getCount(String str){\n HashMap<Character,Integer> map=new HashMap<>();\n \n for(char ch:str.toCharArray()){\n map.put(ch,map.getOrDefault(ch,0)+1);\n }\n \n return map;\n }\n}\n```
7
1
['Java']
2
minimum-amount-of-time-to-collect-garbage
Insane Bit Manipulations. No Nested Loops. Top Execution Time (84-97 ms in C++).
insane-bit-manipulations-no-nested-loops-jf0p
Intuition\nWe need to calculate the minimum time to collect all garbage from the houses, spread across the line, so that collection trucks visit them in order.
sergei99
NORMAL
2023-11-20T16:19:35.400252+00:00
2024-02-19T00:33:59.541365+00:00
96
false
# Intuition\nWe need to calculate the minimum time to collect all garbage from the houses, spread across the line, so that collection trucks visit them in order. There are 3 kinds of garbage and 3 trucks each collecting one specific kind. On input we have distances in minutes between the houses and information of garbage assortiment and quantity per house. A truck which doesn\'t have any more garbage to collect may finish early. Trucks move and collect garbage strictly synchronously - when one is working or moving, the others have to wait. It takes 1 minute to pickup 1 unit of garbage.\n\nThere are at least $2$ houses and no more than $10^5$ houses in total, and $10^5-1$ distances between them, each distance belonging to the interval $[1; 100]$. There is at least $1$ unit of garbage per house and could be up to $10$ garbage units identified by letters `M`, `P`, `G`.\n\nThe algorithm itself is pretty simple. We always have to collect all garback packs, so we need to sum lengths of garbage strings up. And each truck is going to move until the last house having garbage for it and then turn back. So we have to analyze strings and keep track of the last house per garbage unit.\n\n# Approach\n\n## Tracking Houses\n\nOne loop over houses, one nested loop over garbage units, right? Well, that\'s too basic. We wouldn\'t publish a solution if this was the case.\n\nFirst of all, we can group garbage characters into larger blocks for processing. The string data pointer is always 8-byte aligned. We can read and process a quadword if any. Then we can see if there is a double (32-bit) word available. Then check out a 16-bit word. And then process the remaining character if the string happens to have an odd length. This produces 4 unrolled iterations, at most 3 of which are executed (instead of 10 if we went for a loop over characters).\n\nWe know that house positions are covered by 17-bit numbers ($2^{17}=131072$). So we can squeeze as many as 3 such numbers into a 64-bit quantity, which corresponds to a machine register. But that would cost us a few bitwise operations per iteration.\n\nThen, how do we process the garbage types? Switch-case? A bunch of if statements? This just seems boring isn\'t it? A failed branch prediction costs hundreds of CPU cycles, so we should avoid branching, especially within small loop bodies. We can calculate bit offset positions right from the garbage letters.\n| Letter | ASCII Code | Distance from `A` | Biased Code | Binary |\n|-|-|-|-|-|\n| `G` | `0x47` | `6` | `0` | `0000` |\n| `M` | `0x4D` | `12` | `6` | `0110` |\n| `P` | `0x50` | `15` | `9` | `1001` |\n\nWe see that if we subtract `G` from a letter and take away its lowest 2 bits, then we end up with either 0, 4 or 8. We can then multiply it by 5 and get an exact bit field position of the relevant counter (0, 20 or 40) within the 64-bit quantity. Then we just put the index of the current house in that bit field. The arithmetic and the bit manipulations can be conducted on the entire block at once, and only when it comes to injecting bit fields, we have to consider each character separately.\n\nConsider we need to process the input data `[GG, GM, MP]`.\nWe don\'t process the first element because we start at the house 0 anyway, and there is no distance to it. Then we capture the last house distances as follows:\n\n| House | Garbage | G bits 0-19 | M bits 20-39 | P bits 40-59 |\n|-|-|-|-|-|\n| `1` | `GM` | `1` | `1` | `0` |\n| `2` | `MP` | `1` | `2` | `2` |\n\nOf course we could create an array of `3` ints and use the transformed letter as an index into it. But such array wouldn\'t fit a register, and there is no runtime indexing across registers, so the array would have to be in memory (in a fast L1 cache, though).\n\nAlso, as we proceed through the houses, we can compute cumulative sums of the travel distances, so that at the end we just pick up 3 relevant sums, add them up and add the total number of garbage units to collect. This would be the return value.\n\n## Tracking Houses 2\n\nWhat are the disadvantages of the described approach? First of all, despite the nice bundled processing of characters, it gives us a headache of applying bit field changes individually. If we have 8 characters, then we do 24 bit shifts, 3 bitwise operations and 1 addition. Do we really have to perform that many computations? Not if we employ `BMI2` intrinsics.\n\nOur new approach is to compute 3 bits corresponding to `G`, `M` and `P` garbage unit types. Then we can use `_pdep_u64` to put those bits to positions 0, 20 and 40. And then we can multiply the current house\'s index by the mask and replace the relevant positions within the 64-bit quantity. Moreover, the multiplications can be moved away from the string processing and carried out once at the end.\n\nConsider the example above. The mask would be calculated as follows:\n\n| House | Garbage | G bits 0-19 | M bits 20-39 | P bits 40-59 |\n|-|-|-|-|-|\n| `1` | `GM` | `1` | `1` | `0` |\n| `2` | `MP` | `0` | `1` | `1` |\n\nMultiplication of such mask by a number produces quantities like this:\n`2 * 0x10000100000 = 0x20000200000`.\n\nAnd we are calculating the bit offsets differently this time. We don\'t subtract the ASCII code of \'G\', but the value `0x40` which is preceding `A`.\n| Letter | ASCII Code | Distance from `A` | Biased Code | Binary |\n|-|-|-|-|-|\n| `G` | `0x47` | `6` | `7` | `00111` |\n| `M` | `0x4D` | `12` | `13` | `01101` |\n| `P` | `0x50` | `15` | `16` | `10000` |\n\nThen we take away the lowest two bits of each letter again. And then we shift the code left by 2 bits, resulting in binary `001`, `011`, `100`, or decimal `1`, `3`, `4`, respectively. If we had it as `1`, `2`, `4`, then we could bitwise-OR characters across each other and get those 3 bits to deposit. So we need to clear the bit below the highest bit, which is achieved by ANDing with the inversion of shift right by 1. The bitwise ORing itself is calculated in $log_2(k)$ operations where $k$ is the bit length of the number. This seems to be a bit faster than the original approach.\n\nThe rest of the logic is left unchanged.\n\n## Backward Iteration\n\nIt\'s easy to notice that at least one vehicle\'s last stop is at the end of the array, and the others are usually close to it. So we can save a significant amount of calculation on average by looking for the last stops from the end of the array rather than from the beginning. Once we have found the last stops for all vehicles, we can stop fetching the string data and proceed only to examining their lengths.\n\nThis approach is not compatible with calculation of distance running sums within the same loop. But since we don\'t use travel distance vector for any other purpose within the loop, we don\'t actually lose anything. We can apply an STL `partial_sum` to it later.\n\n## Tracking Travel Distances\n\nFinally, do we even need to track house positions per garbage type and spoil the array of distances writing all those sums to it, when we need at most 3 of them? Can\'t we just calculate those distances as we go? Yes we can.\n\nHowever, this might be a little bit tricky. Cumulative distances can reach values up to $100 \\times 10^5 = 10^7$, which is covered by a 24-bit integer. But there is no way we can squeeze 3 of 24-bit integers into 64-bit quantity. We now need 72 bits. Therefore we would have to use a 128-bit integer type as an accumulator. And intrinsics would still work with 64-bit types because there are no machine instructions for bit deposit across two registers. How do we overcome that? Remember that we only need intrinsics to construct a mask with no more than three 1-bits corresponding to bit field starting positions, so the highest one of them would be at position 48. And when it comes to multiplication and bitwise ops, we can extend the mask to a 128-bit type.\n\nNow we don\'t write anything to the `travel` array, we accumulate distances in a 128-bit variable which the compiler maps to a couple of registers, and after processing of all the houses we can add 3 distance sums and the number of garbage units up and return it.\n\nThis variation of the algorithm cannot be optimized using backward iteration.\n\n# Complexity\n- Time complexity:\nTracking Houses: $O(n \\times g)$ where $n$ is the number of houses and $g$ is the average number of garbage units per visited house.\nThe other two solutions: $O(n \\times log(max(g)))$ because we never process individual characters except the last odd one if any.\n\n- Space complexity: $O(1)$.\n\n# Measurements\n\n| Language | Solution | Time | Beating | Memory | Beating |\n|-|-|-|-|-|-|\n| C++ | Tracking Houses | 97 ms | 100% | 102.4 Mb | 91.88% |\n| C++ | Tracking Houses 2 | 96 ms | 100% | 102.1 Mb | 99.91% |\n| C++ | Backward Iteration | 84 ms | 100% | 102.2 Mb | 99.60% |\n| C++ | Tracking Travel Distances | 95 ms | 100% | 102 Mb | 100% |\n\nSubmission links:\nhttps://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/submissions/1102721548/\nhttps://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/submissions/1102774415/\nhttps://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/submissions/1102931106/\nhttps://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/submissions/1102820566/\n\nTime varies across submissions, so runtime stats may improve over time.\n\n# Code\n\n## Tracking Houses\n```C++ []\nclass Solution {\nprivate:\n typedef unsigned long long u64_t;\n typedef unsigned int u32_t;\n typedef unsigned short u16_t;\n typedef unsigned char u8_t;\n\n static constexpr u8_t FWIDTH = 20;\n static constexpr u64_t FMASK = (1ull << FWIDTH) - 1u;;\n\n static u64_t setfield(const u64_t v, const u8_t exp, const u32_t value)\n __attribute__((always_inline)) {\n return (v & ~(FMASK << exp)) + (u64_t(value) << exp);\n }\n\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n const u32_t n = travel.size();\n u64_t ends = 0;\n u32_t rtime = 0, count = garbage.front().length();\n for (u32_t i = 1; i <= n; i++) {\n const string &a = garbage[i];\n const char *ac = a.c_str();\n u8_t m = a.length();\n count += m;\n if (m >= 8u) {\n const u64_t vk = *reinterpret_cast<const u64_t*>(ac) - 0x4747474747474747ull,\n vexp = ((vk >> 2) & 0x3F3F3F3F3F3F3F3Full) * 20u;\n ends = setfield(ends, vexp & 0xFFu, i);\n ends = setfield(ends, (vexp >> 8) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 16) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 24) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 32) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 40) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 48) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 56) & 0xFFu, i);\n ac += 8u;\n m -= 8u;\n }\n if (m >= 4u) {\n const u32_t vk = *reinterpret_cast<const u32_t*>(ac) - 0x47474747u,\n vexp = ((vk >> 2) & 0x3F3F3F3Fu) * 20u;\n ends = setfield(ends, vexp & 0xFFu, i);\n ends = setfield(ends, (vexp >> 8) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 16) & 0xFFu, i);\n ends = setfield(ends, (vexp >> 24) & 0xFFu, i);\n ac += 4u;\n m -= 4u;\n }\n if (m >= 2u) {\n const u16_t vk = *reinterpret_cast<const u16_t*>(ac) - 0x4747u,\n vexp = ((vk >> 2) & 0x3F3Fu) * 20u;\n ends = setfield(ends, vexp & 0xFFu, i);\n ends = setfield(ends, (vexp >> 8) & 0xFFu, i);\n ac += 2u;\n m -= 2u;\n }\n if (m >= 1u) {\n const u8_t k = *ac - \'G\', exp = (k & (k - 1u)) * 5u;\n ends = setfield(ends, exp, i);\n ac += 1u;\n m--;\n }\n travel[i-1u] = rtime += travel[i-1u];\n }\n const u32_t ep = ends >> FWIDTH * 2u, em = (ends >> FWIDTH) & FMASK, eg = ends & FMASK;\n return (ep ? travel[ep-1u] : 0u) + (em ? travel[em-1u] : 0u) +\n (eg ? travel[eg-1u] : 0u) + count;\n\n }\n};\n```\n\n## Tracking Houses 2\n``` C++ []\n#pragma GCC optimize ("O3")\n#include <immintrin.h>\n\nclass Solution {\nprivate:\n typedef unsigned long long u64_t;\n typedef unsigned int u32_t;\n typedef unsigned short u16_t;\n typedef unsigned char u8_t;\n\n static constexpr u8_t FWIDTH = 20;\n static constexpr u64_t FMASK = (1ull << FWIDTH) - 1u;;\n\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) __attribute__((__target__("bmi2"))) {\n const u32_t n = travel.size();\n u64_t ends = 0;\n u32_t rtime = 0, count = garbage.front().length();\n for (u32_t i = 1; i <= n; i++) {\n const string &a = garbage[i];\n const char *ac = a.c_str();\n u8_t m = a.length();\n count += m;\n u64_t mask = 0;\n if (m >= 8u) {\n const u64_t vk = (*reinterpret_cast<const u64_t*>(ac) - 0x4040404040404040ull) & 0xFCFCFCFCFCFCFCFCull;\n u64_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 32;\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n mask = _pdep_u64(vexp, 0x0000010000100001ull);\n ac += 8u;\n m -= 8u;\n }\n if (m >= 4u) {\n const u32_t vk = (*reinterpret_cast<const u32_t*>(ac) - 0x40404040u) & 0xFCFCFCFCu;\n u32_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n mask |= _pdep_u64(vexp, 0x0000010000100001ull);\n ac += 4u;\n m -= 4u;\n }\n if (m >= 2u) {\n const u16_t vk = (*reinterpret_cast<const u16_t*>(ac) - 0x4040u) & 0xFCFCu;\n u16_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 8;\n mask |= _pdep_u64(vexp, 0x0000010000100001ull);\n ac += 2u;\n m -= 2u;\n }\n if (m >= 1u) {\n const u8_t k = (*ac - 0x40u) & 0xFCu, exp = (k >> 2) & ~(k >> 3);\n mask |= _pdep_u64(exp, 0x0000010000100001ull);\n ac += 1u;\n m--;\n }\n ends = (ends & ~(mask * FMASK)) | (mask * i);\n travel[i-1u] = rtime += travel[i-1u];\n }\n const u32_t ep = ends >> FWIDTH * 2u, em = (ends >> FWIDTH) & FMASK, eg = ends & FMASK;\n return (ep ? travel[ep-1u] : 0u) + (em ? travel[em-1u] : 0u) +\n (eg ? travel[eg-1u] : 0u) + count;\n\n }\n};\n```\n## Backward Iteration\n``` C++ []\n#include <immintrin.h>\n\nclass Solution {\nprivate:\n typedef unsigned long long u64_t;\n typedef unsigned int u32_t;\n typedef unsigned short u16_t;\n typedef unsigned char u8_t;\n\n static constexpr u8_t FWIDTH = 20;\n static constexpr u64_t FMASK = (1ull << FWIDTH) - 1u;\n static constexpr u64_t DEPMASK = 0x0000010000100001ull;\n\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) __attribute__((__target__("bmi2"))) {\n const u32_t n = travel.size();\n u64_t ends = 0;\n u8_t found = 0;\n u32_t count = 0, i;\n for (i = n; i && found != 7; i--) {\n const string &a = garbage[i];\n const char *ac = a.c_str();\n u8_t m = a.length();\n count += m;\n u64_t mask = 0;\n if (m >= 8u) {\n const u64_t vk = (*reinterpret_cast<const u64_t*>(ac) - 0x4040404040404040ull) & 0xFCFCFCFCFCFCFCFCull;\n u64_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 32;\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n vexp &= ~found;\n mask = _pdep_u64(vexp, DEPMASK);\n found |= vexp & 7;\n ac += 8u;\n m -= 8u;\n }\n if (m >= 4u) {\n const u32_t vk = (*reinterpret_cast<const u32_t*>(ac) - 0x40404040u) & 0xFCFCFCFCu;\n u32_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n vexp &= ~found;\n mask |= _pdep_u64(vexp, DEPMASK);\n found |= vexp & 7;\n ac += 4u;\n m -= 4u;\n }\n if (m >= 2u) {\n const u16_t vk = (*reinterpret_cast<const u16_t*>(ac) - 0x4040u) & 0xFCFCu;\n u16_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 8;\n vexp &= ~found;\n mask |= _pdep_u64(vexp, DEPMASK);\n found |= vexp & 7;\n ac += 2u;\n m -= 2u;\n }\n if (m >= 1u) {\n const u8_t k = (*ac - 0x40u) & 0xFCu, exp = (k >> 2) & ~(k >> 3) & ~found;\n mask |= _pdep_u64(exp, DEPMASK);\n found |= exp & 7;\n ac += 1u;\n m--;\n }\n ends = (ends & ~(mask * FMASK)) | (mask * i);\n }\n partial_sum(travel.begin(), travel.end(), travel.begin());\n const u32_t ep = ends >> FWIDTH * 2u, em = (ends >> FWIDTH) & FMASK, eg = ends & FMASK;\n return (ep ? travel[ep-1u] : 0u) + (em ? travel[em-1u] : 0u) + (eg ? travel[eg-1u] : 0u) +\n transform_reduce(garbage.crbegin() + (n - i), garbage.crend(), count, plus(),\n [](const auto &s) __attribute__((always_inline)) { return s.length(); });\n\n }\n};\n```\n## Tracking Travel Distances\n``` C++ []\n#include <immintrin.h>\n\nclass Solution {\nprivate:\n typedef unsigned __int128 u128_t;\n typedef unsigned long long u64_t;\n typedef unsigned int u32_t;\n typedef unsigned short u16_t;\n typedef unsigned char u8_t;\n\n static constexpr u8_t FWIDTH = 24;\n static constexpr u64_t FMASK = (1ull << FWIDTH) - 1u;\n static constexpr u64_t DEPMASK = 0x1000001000001ull;\n\npublic:\n int garbageCollection(const vector<string>& garbage, const vector<int>& travel) __attribute__((__target__("bmi2"))) {\n const u32_t n = travel.size();\n u128_t rtimes = 0;\n u32_t rtime = 0, count = garbage.front().length();\n for (u32_t i = 1; i <= n; i++) {\n const string &a = garbage[i];\n const char *ac = a.c_str();\n u8_t m = a.length();\n count += m;\n u64_t mask = 0;\n if (m >= 8u) {\n const u64_t vk = (*reinterpret_cast<const u64_t*>(ac) - 0x4040404040404040ull) & 0xFCFCFCFCFCFCFCFCull;\n u64_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 32;\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n mask = _pdep_u64(vexp, DEPMASK);\n ac += 8u;\n m -= 8u;\n }\n if (m >= 4u) {\n const u32_t vk = (*reinterpret_cast<const u32_t*>(ac) - 0x40404040u) & 0xFCFCFCFCu;\n u32_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 16;\n vexp |= vexp >> 8;\n mask |= _pdep_u64(vexp, DEPMASK);\n ac += 4u;\n m -= 4u;\n }\n if (m >= 2u) {\n const u16_t vk = (*reinterpret_cast<const u16_t*>(ac) - 0x4040u) & 0xFCFCu;\n u16_t vexp = (vk >> 2) & ~(vk >> 3);\n vexp |= vexp >> 8;\n mask |= _pdep_u64(vexp, DEPMASK);\n ac += 2u;\n m -= 2u;\n }\n if (m >= 1u) {\n const u8_t k = (*ac - 0x40u) & 0xFCu, exp = (k >> 2) & ~(k >> 3);\n mask |= _pdep_u64(exp, DEPMASK);\n ac += 1u;\n m--;\n }\n rtime += travel[i-1u];\n rtimes = (rtimes & ~(u128_t(mask) * FMASK)) | (u128_t(mask) * rtime);\n }\n return ((rtimes & FMASK) + ((rtimes >> FWIDTH) & FMASK) + (rtimes >> FWIDTH * 2)) + count;\n }\n};\n```
6
0
['Array', 'String', 'Binary Search', 'Bit Manipulation', 'C++']
2
minimum-amount-of-time-to-collect-garbage
Beginner Friendly | Reverse Order Aproach | Simple | Easy To Understand | Java | Python3 |C++ | C#
beginner-friendly-reverse-order-aproach-oqcw9
Intuition\n Describe your first thoughts on how to solve this problem. \nIt iterates through an array of strings (garbage), where each string represents a locat
antovincent
NORMAL
2023-11-20T13:31:44.168638+00:00
2023-11-20T13:31:44.168661+00:00
535
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt iterates through an array of strings (garbage), where each string represents a location, and an array of integers (travel), where each integer represents the travel distance between consecutive locations. Considers the lengths of the strings, the occurrences of \'P\', \'G\', \'M\' in each string, and the travel distances to compute the total distance.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initializes variables (sum, mul, p, g, m) to keep track of the total distance, a multiplier for certain characters, and counts for \'P\', \'G\', \'M\'.\n- Iterates through the garbage array in **REVERSE ORDER**, calculating the sum of string lengths and updating the counts of \'P\', \'G\', \'M\' in each string.\n- Then calculates the contribution of the current step to the total distance by multiplying the multiplier (mul) with the corresponding travel distance.\n- The final result is the sum of all these distances.\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\n```java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int sum=0,mul=0;\n int p=0,g=0,m=0;\n for(int i=garbage.length-1;i>0;i--){\n sum+=garbage[i].length();\n if(mul<3){\n for(int j=0;j<garbage[i].length();j++){\n char ch = garbage[i].charAt(j);\n switch(ch){\n case \'P\' :\n mul = p==0 ? mul+1:mul;\n p++;\n break;\n case \'G\' :\n mul = g==0 ? mul+1:mul;\n g++;\n break;\n case \'M\' :\n mul = m==0 ? mul+1:mul;\n m++;\n break;\n default : \n break;\n }\n }\n }\n sum+=(mul*travel[i-1]);\n }\n sum+=garbage[0].length();\n return sum;\n }\n}\n```\n```python3 []\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n sum_val = 0\n mul = 0\n p = 0\n g = 0\n m = 0\n\n for i in range(len(garbage) - 1, 0, -1):\n sum_val += len(garbage[i])\n\n if mul < 3:\n for j in range(len(garbage[i])):\n ch = garbage[i][j]\n if ch == \'P\':\n mul = mul + 1 if p == 0 else mul\n p += 1\n elif ch == \'G\':\n mul = mul + 1 if g == 0 else mul\n g += 1\n elif ch == \'M\':\n mul = mul + 1 if m == 0 else mul\n m += 1\n\n sum_val += mul * travel[i - 1]\n\n sum_val += len(garbage[0])\n return sum_val\n```\n```C []\nint garbageCollection(char** garbage, int garbageSize, int* travel, int travelSize) {\n int sum = 0, mul = 0;\n int p = 0, g = 0, m = 0;\n\n for (int i = garbageSize - 1; i > 0; i--) {\n sum += strlen(garbage[i]);\n\n if (mul < 3) {\n \n\n for (int j = 0; j < strlen(garbage[i]); j++) {\n char ch = garbage[i][j];\n switch (ch) {\n case \'P\':\n mul = p == 0 ? mul + 1 : mul;\n p++;\n break;\n case \'G\':\n mul = g == 0 ? mul + 1 : mul;\n g++;\n break;\n case \'M\':\n mul = m == 0 ? mul + 1 : mul;\n m++;\n break;\n default:\n break;\n }\n }\n\n \n }\n sum += mul * travel[i - 1];\n }\n sum+=strlen(garbage[0]);\n return sum;\n}\n```\n```C++ []\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int sum = 0, mul = 0;\n int p = 0, g = 0, m = 0;\n\n for (int i = garbage.size() - 1; i > 0; i--) {\n sum += garbage[i].length();\n\n if (mul < 3) {\n for (int j = 0; j < garbage[i].length(); j++) {\n char ch = garbage[i][j];\n switch (ch) {\n case \'P\':\n mul = p == 0 ? mul + 1 : mul;\n p++;\n break;\n case \'G\':\n mul = g == 0 ? mul + 1 : mul;\n g++;\n break;\n case \'M\':\n mul = m == 0 ? mul + 1 : mul;\n m++;\n break;\n default:\n break;\n }\n }\n }\n\n sum += mul * travel[i - 1];\n }\n\n sum += garbage[0].length();\n return sum;\n }\n};\n```\n```Javascript []\n/**\n * @param {string[]} garbage\n * @param {number[]} travel\n * @return {number}\n */\nvar garbageCollection = function(garbage, travel) {\n let sum = 0;\n let mul = 0;\n let p = 0;\n let g = 0;\n let m = 0;\n\n for (let i = garbage.length - 1; i > 0; i--) {\n sum += garbage[i].length;\n\n if (mul < 3) {\n for (let j = 0; j < garbage[i].length; j++) {\n const ch = garbage[i][j];\n switch (ch) {\n case \'P\':\n mul = p === 0 ? mul + 1 : mul;\n p++;\n break;\n case \'G\':\n mul = g === 0 ? mul + 1 : mul;\n g++;\n break;\n case \'M\':\n mul = m === 0 ? mul + 1 : mul;\n m++;\n break;\n default:\n break;\n }\n }\n }\n\n sum += mul * travel[i - 1];\n }\n\n sum += garbage[0].length;\n return sum;\n};\n```\n```Kotlin []\nclass Solution {\n fun garbageCollection(garbage: Array<String>, travel: IntArray): Int {\n var sum = 0\n var mul = 0\n var p = 0\n var g = 0\n var m = 0\n\n for (i in garbage.size - 1 downTo 1) {\n sum += garbage[i].length\n\n if (mul < 3) {\n for (j in garbage[i].indices) {\n val ch = garbage[i][j]\n when (ch) {\n \'P\' -> {\n mul = if (p == 0) mul + 1 else mul\n p++\n }\n \'G\' -> {\n mul = if (g == 0) mul + 1 else mul\n g++\n }\n \'M\' -> {\n mul = if (m == 0) mul + 1 else mul\n m++\n }\n else -> {\n }\n }\n }\n }\n\n sum += mul * travel[i - 1]\n }\n\n sum += garbage[0].length\n return sum\n }\n}\n```\n```typescript []\nfunction garbageCollection(garbage: string[], travel: number[]): number {\n let sum = 0;\n let mul = 0;\n let p = 0;\n let g = 0;\n let m = 0;\n\n for (let i = garbage.length - 1; i > 0; i--) {\n sum += garbage[i].length;\n\n if (mul < 3) {\n for (let j = 0; j < garbage[i].length; j++) {\n const ch = garbage[i][j];\n switch (ch) {\n case \'P\':\n mul = p === 0 ? mul + 1 : mul;\n p++;\n break;\n case \'G\':\n mul = g === 0 ? mul + 1 : mul;\n g++;\n break;\n case \'M\':\n mul = m === 0 ? mul + 1 : mul;\n m++;\n break;\n default:\n break;\n }\n }\n }\n\n sum += mul * travel[i - 1];\n }\n\n sum += garbage[0].length;\n return sum;\n}\n\n```\n```C# []\npublic class Solution {\n public int GarbageCollection(string[] garbage, int[] travel) {\n int sum = 0;\n int mul = 0;\n int p = 0;\n int g = 0;\n int m = 0;\n\n for (int i = garbage.Length - 1; i > 0; i--) {\n sum += garbage[i].Length;\n\n if (mul < 3) {\n for (int j = 0; j < garbage[i].Length; j++) {\n char ch = garbage[i][j];\n switch (ch) {\n case \'P\':\n mul = p == 0 ? mul + 1 : mul;\n p++;\n break;\n case \'G\':\n mul = g == 0 ? mul + 1 : mul;\n g++;\n break;\n case \'M\':\n mul = m == 0 ? mul + 1 : mul;\n m++;\n break;\n default:\n break;\n }\n }\n }\n\n sum += mul * travel[i - 1];\n }\n\n sum += garbage[0].Length;\n return sum;\n }\n}\n\n```\n```php []\nclass Solution {\n /**\n * @param String[] $garbage\n * @param Integer[] $travel\n * @return Integer\n */\n function garbageCollection($garbage, $travel) {\n $sum = 0;\n $mul = 0;\n $p = 0;\n $g = 0;\n $m = 0;\n\n for ($i = count($garbage) - 1; $i > 0; $i--) {\n $sum += strlen($garbage[$i]);\n\n if ($mul < 3) {\n for ($j = 0; $j < strlen($garbage[$i]); $j++) {\n $ch = $garbage[$i][$j];\n switch ($ch) {\n case \'P\':\n $mul = $p == 0 ? $mul + 1 : $mul;\n $p++;\n break;\n case \'G\':\n $mul = $g == 0 ? $mul + 1 : $mul;\n $g++;\n break;\n case \'M\':\n $mul = $m == 0 ? $mul + 1 : $mul;\n $m++;\n break;\n default:\n break;\n }\n }\n }\n\n $sum += $mul * $travel[$i - 1];\n }\n\n $sum += strlen($garbage[0]);\n return $sum;\n }\n}\n\n```\n```ruby []\n# @param {String[]} garbage\n# @param {Integer[]} travel\n# @return {Integer}\ndef garbage_collection(garbage, travel)\n sum = 0\n mul = 0\n p = 0\n g = 0\n m = 0\n\n (garbage.length - 1).downto(1) do |i|\n sum += garbage[i].length\n\n if mul < 3\n garbage[i].each_char do |ch|\n case ch\n when \'P\'\n mul = p == 0 ? mul + 1 : mul\n p += 1\n when \'G\'\n mul = g == 0 ? mul + 1 : mul\n g += 1\n when \'M\'\n mul = m == 0 ? mul + 1 : mul\n m += 1\n end\n end\n end\n\n sum += mul * travel[i - 1]\n end\n\n sum += garbage[0].length\n return sum\nend\n\n```\n\n\n# **UPVOTES ARE ENCOURAGING**\nmy linkdin profile:\n[https://www.linkedin.com/in/antony-vincent-r-86ab611bb/]()\n\n\n
6
0
['Dynamic Programming', 'C', 'PHP', 'Java', 'TypeScript', 'Python3', 'Ruby', 'Kotlin', 'JavaScript', 'C#']
0
minimum-amount-of-time-to-collect-garbage
Idea Explained || Counting and Prefix Sum || C++ Clean Code
idea-explained-counting-and-prefix-sum-c-i3jx
Intuition :\n\n Idea here is simple, we need to count the number of different type of garbages at each house and travel time to reach a house.\n Also, a garbage
i_quasar
NORMAL
2022-08-28T04:08:12.743022+00:00
2022-08-28T04:45:00.005942+00:00
290
false
**Intuition :**\n\n* Idea here is simple, we need to count the number of different type of garbages at each house and travel time to reach a house.\n* Also, a garbage truck of some type will only stop at a house if it has garbage of that type, else move to next house.\n\n* If a truck stops at a particular house, we can use a prefix sum of travel time to get time to reach current house from previous stop. \n\t* Use 3 variables or an array to keep track of previous visited house of each type of garbage.\n* So, time required by truck of a particular type to pick garbage from current house is :\n\t* Time to travel from previous house from which garbage of this type was picked\n\t* And number of garbages of current type i.e type of truck.\n* Sum up the travel time for each type of trucks and return total travel time\n# Code : \n\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int n = travel.size();\n vector<int> prefixSum(n+1, 0);\n \n\t\t// Prefix sum of travel time from [0 to ith] house\n for(int i=0; i<n; i++) {\n prefixSum[i+1] = travel[i] + prefixSum[i];\n }\n \n\t\t// To keep track of previous visited house of each type of garbage\n unordered_map<char, int> prevIdx;\n \n int idx = 0, totalTime = 0;\n\n for(auto& house : garbage) {\n int metalCount = 0, glassCount = 0, paperCount = 0;\n \n\t\t\t// Count the number of garbage of each type\n for(auto& type : house) {\n if(type == \'M\') metalCount++;\n else if(type == \'P\') paperCount++;\n else if(type == \'G\') glassCount++;\n }\n \n\t\t\t// If metal type is present in current house, then only pick else skip\n if(metalCount) {\n\t\t\t\t// Sum of travel time from previous house to current\n\t\t\t\t// And time to pick all metal type garbage\n totalTime += prefixSum[idx] - prefixSum[prevIdx[\'M\']] + metalCount;\n prevIdx[\'M\'] = idx;\n }\n \n\t\t\t// If glass type is present in current house, then only pick else skip\n if(glassCount) {\n\t\t\t\t// Sum of travel time from previous house to current\n\t\t\t\t// And time to pick all glass type garbage\n totalTime += prefixSum[idx] - prefixSum[prevIdx[\'G\']] + glassCount;\n prevIdx[\'G\'] = idx; \n }\n \n\t\t\t// If paper type is present in current house, then only pick else skip\n if(paperCount) {\n\t\t\t\t// Sum of travel time from previous house to current\n\t\t\t\t// And time to pick all paper type garbage\n totalTime += prefixSum[idx] - prefixSum[prevIdx[\'P\']] + paperCount;\n prevIdx[\'P\'] = idx;\n }\n \n idx++;\n }\n \n \n return totalTime;\n }\n};\n```\n\n**Complexity :**\n\n* **TIme :** `O(N)`, to travel over all houses and pick garbage\n* **Space :** `O(N)`, to store prefix sum\n\n***If you find this helful, do give it a like :)***
6
1
['Counting', 'Prefix Sum']
2
minimum-amount-of-time-to-collect-garbage
O(N), O(1) simple solution with clear explanation, single for loop
on-o1-simple-solution-with-clear-explana-nur5
Intuition\nAt first glance and read of the question we would like to calculate the travel time taken by each truck and the time taken by them to process their r
naruto_1994
NORMAL
2023-11-20T03:27:19.342437+00:00
2023-11-20T03:28:42.331946+00:00
64
false
# Intuition\nAt first glance and read of the question we would like to calculate the travel time taken by each truck and the time taken by them to process their respective waste and once we sum it we would have our answer.\n\n# Approach\nThings to observe, that were kind of hidden in the problem description, before reading the solution ( drew the inferences from the examples shared):\n- If a truck does not collect waste their travel time is 0\n- If a character ```G|| M || P``` occurs ```n``` number of times in the ```garbage``` string then it will take ```n * 1``` amount of time to process it\n- No distance has to be travelled by a truck for picking up garbage at house at index 0\n- Garbage truck only has to travel till the house their respective waste is present i.e. if only house at 0 index has metal waste then the metal pickup truck will only travel till house 0, no need to travel to other houses.\n\nBecause of all the above points, the solution reduces down to finding \n- Total processing time of the wastes at each house\n- Maximum time taken by a truck to travel to the last house they need to pick waste from\n\nWe tackle the same by finding a cumulative time taken to reach at a particular house by a truck and assign the same to a truck if their waste is present in a house\nAnd for the waste processing time add the length of the string at index ```i``` of ```garbage```\n\n\n# Complexity\n- Time complexity:\nWe are using two loops, one to traverse each of the houses```(N)``` and one to traverse all the type of waste present at a house ```(K)```\nSo the time complexity becomes $$O(N*K)$$, but since ```K``` is given an additional contstraint of ```1 <= K <= 10``` this reduces down to $$O(N)$$\n\n- Space complexity:\nSince we are only using 4 variables the space complexity comes down to $$O(1)$$\n\n# Code\n```\nfunc garbageCollection(garbage []string, travel []int) int {\n collectionTime := 0\n gTravelTime := 0\n pTravelTime := 0\n mTravelTime := 0\n currCum := 0 // to track cumulative travel time for a truck that has to collect garbage from a house\n\n for i, gCollect := range garbage {\n if i != 0 {\n currCum += travel[i-1] \n }\n collectionTime += len(gCollect) // each unit takes 1 minute to process\n for j := 0 ; j < len(gCollect); j++ {\n if gCollect[j] == \'M\' {\n mTravelTime = currCum\n } else if gCollect[j] == \'P\' {\n pTravelTime = currCum\n } else if gCollect[j] == \'G\' {\n gTravelTime = currCum\n }\n }\n }\n\n return collectionTime + gTravelTime + pTravelTime + mTravelTime\n}\n```
5
0
['Go']
1
minimum-amount-of-time-to-collect-garbage
Easy Approach c++ O(n)
easy-approach-c-on-by-akshat161997-k5gd
\nvoid countFreq(string s, int &G, int &P, int &M){\n for(int i=0;i<s.length();i++){\n if(s[i]==\'G\') G++;\n else if(s[i]==\'M\')
akshat161997
NORMAL
2022-08-28T16:50:02.257056+00:00
2022-08-28T16:50:02.257097+00:00
430
false
```\nvoid countFreq(string s, int &G, int &P, int &M){\n for(int i=0;i<s.length();i++){\n if(s[i]==\'G\') G++;\n else if(s[i]==\'M\') M++;\n else if(s[i]==\'P\') P++;\n }\n }\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n int n=garbage.size();\n int t=travel.size();\n int G=0,P=0,M=0;\n countFreq(garbage[n-1],G,P,M);\n \n for(int i=n-2;i>=0;i--){\n if(G!=0) G += travel[i];\n if(M!=0) M += travel[i];\n if(P!=0) P += travel[i];\n \n countFreq(garbage[i],G,P,M);\n }\n return G+M+P;\n }\n```
5
0
[]
3
minimum-amount-of-time-to-collect-garbage
✅Python || Easy Approach || Prefix Sum || Hashmap
python-easy-approach-prefix-sum-hashmap-vozvi
\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n \n from collections import defaultdict\n\n
chuhonghao01
NORMAL
2022-08-28T04:22:42.627608+00:00
2022-08-28T04:22:42.627633+00:00
706
false
```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n \n from collections import defaultdict\n\n ans = 0\n lastH = {}\n num = defaultdict(int)\n\n for i in range(len(garbage)):\n for char in garbage[i]:\n num[char] += 1\n lastH[char] = i\n \n pref = []\n res = 0\n for x in travel:\n res += x\n pref.append(res)\n\n ans = sum(num.values())\n for k, v in lastH.items():\n if lastH[k] != 0:\n ans += pref[lastH[k] - 1]\n \n return ans\n```
5
0
['Prefix Sum', 'Python', 'Python3']
0
minimum-amount-of-time-to-collect-garbage
✅[C++] (BRUTE FORCE ) full explain Prefix sum + Map , Easy and readable
c-brute-force-full-explain-prefix-sum-ma-j4gr
Please UPVOTE if you like it and thanks\nThe idea is to traverse from right and calculate total time for three of trucks :\nBut How : \ntimem : total time for
Pathak_Ankit
NORMAL
2022-08-28T04:21:25.219533+00:00
2022-08-28T04:56:44.939013+00:00
433
false
Please UPVOTE if you like it and thanks\n**The idea is to traverse from right and calculate total time for three of trucks :**\nBut How : \ntimem : total time for M garbage\ntimem = last occurence of M + no. of M;\nBut why last occurence : becz M\'s truck have to wait for last M garbage using prefix sum of total time array\nand why no. of M : becz how much time to collect = 1* no. of M (1 min-> time to collect one M)\n**Simlarly calc for G and P**\nif calculated particular garbage then not looking for that garbage \n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& t) \n {\n unordered_map<char,int> m;\n for(auto e:garbage)\n {\n for(auto f:e)\n {\n m[f]++;\n }\n }\n \n int timem=0,timeg=0,timep=0;\n int n=garbage.size();\n vector<int> pre(t.size(),0);\n \n pre[0]=t[0];\n for(int i=1;i<t.size();i++)\n {\n pre[i]=pre[i-1]+t[i];\n }\n for(int i=n-1;i>=0;i--)\n {\n for(int j=garbage[i].size()-1;j>=0;j--)\n {\n if(garbage[i][j]==\'P\' && timep==0)\n {\n if(i-1<0)\n {\n timep=m[garbage[i][j]];\n }\n else\n {\n timep=pre[i-1]+m[garbage[i][j]];\n }\n \n }\n else if(garbage[i][j]==\'G\' && timeg==0)\n {\n if(i-1<0)\n {\n timeg=m[garbage[i][j]];\n }\n else\n {\n timeg=pre[i-1]+m[garbage[i][j]];\n }\n }\n else if(garbage[i][j]==\'M\' && timem==0)\n {\n if(i-1<0)\n {\n timem=m[garbage[i][j]];\n }\n else\n {\n timem=pre[i-1]+m[garbage[i][j]];\n }\n }\n }\n }\n return timep+timem+timeg;\n }\n};\n```
5
1
['C', 'Prefix Sum']
2
minimum-amount-of-time-to-collect-garbage
C++||very easy Solution||O(N)||space O(1)
cvery-easy-solutiononspace-o1-by-baibhav-evng
\n//at first just store last index of Metal , paper , glass\n//rest see the code\nclass Solution {\npublic:\n int garbageCollection(vector<string>& gar, vect
baibhavkr143
NORMAL
2022-08-28T04:02:03.583207+00:00
2022-08-28T04:41:38.181749+00:00
157
false
```\n//at first just store last index of Metal , paper , glass\n//rest see the code\nclass Solution {\npublic:\n int garbageCollection(vector<string>& gar, vector<int>& travel) {\n \n int glass=-1,paper=-1,metal=-1; //storing last index of each garbage\n \n for(int i=0;i<gar.size();i++)\n {\n int m=0,p=0,g=0;\n \n for(auto it:gar[i])\n {\n if(it==\'M\')\n m=1;\n \n else if(it==\'P\')\n p=1;\n \n else g=1;\n }\n if(g)\n glass=i;\n \n if(p)\n paper=i;\n \n if(m)\n metal=i;\n }\n \n int ans=0;\n \n \n // for glass\n for(int i=0;i<=glass;i++)\n {\n int g=0;\n for(auto it:gar[i])\n {\n if(it==\'G\')\n g++;\n }\n \n ans+=g;\n if(i>0) //because we start from i=0 so no time spent at i=0\n ans+=travel[i-1]; \n }\n \n // for paper\n for(int i=0;i<=paper;i++)\n {\n int p=0;\n for(auto it:gar[i])\n {\n if(it==\'P\')\n p++;\n }\n \n ans+=p;\n if(i>0)\n ans+=travel[i-1]; \n }\n \n \n // for metal\n for(int i=0;i<=metal;i++)\n {\n int m=0;\n for(auto it:gar[i])\n {\n if(it==\'M\')\n m++;\n }\n \n ans+=m;\n if(i>0)\n ans+=travel[i-1]; \n }\n \n \n return ans;\n \n }\n};\n```
5
2
[]
1
minimum-amount-of-time-to-collect-garbage
O(N) T.C & S.C O(1) SOLUTION BEGINNERS WITHOUT MAP!!!
on-tc-sc-o1-solution-beginners-without-m-222a
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
aero_coder
NORMAL
2023-11-20T16:13:47.755603+00:00
2023-11-23T08:56:18.807125+00:00
225
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\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\n for (int i = 0; i < n; i++) {\n ans = ans + garbage[i].size();\n }\n\n bool flagG = false, flagM = false, flagP = false;\n int indg = -1, indm = -1, indp = -1;\n\n for (int i = n-1; i >=0; i--) {\n if (!flagG && garbage[i].find(\'G\') != string::npos) {\n indg = i;\n flagG = true;\n }\n if (!flagP && garbage[i].find(\'P\') != string::npos) {\n indp = i;\n flagP = true;\n }\n if (!flagM && garbage[i].find(\'M\') != string::npos) {\n indm = i;\n flagM = true;\n }\n }\n if (flagG) {\n ans = ans + accumulate(travel.begin(), travel.begin() + indg , 0);\n } \n if (flagP) {\n ans = ans + accumulate(travel.begin(), travel.begin() + indp , 0);\n }\n if (flagM) {\n ans = ans + accumulate(travel.begin(), travel.begin() + indm , 0);\n }\n return ans;\n }\n};\n```
4
0
['C++']
0
minimum-amount-of-time-to-collect-garbage
Simple and Easy C++ code with Explanation using Single Loop || Prefix Sum || Beats 100% ✅
simple-and-easy-c-code-with-explanation-kudjx
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n1. We need to find the prefix sum of the travel array, to find the minimum time t
Nilogrib
NORMAL
2023-11-20T10:07:04.557568+00:00
2023-11-20T10:07:04.557591+00:00
1,303
false
![image.png](https://assets.leetcode.com/users/images/be7deff9-0718-432b-a202-6d2b6f20f6f8_1700474629.741332.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. We need to find the prefix sum of the `travel` array, to find the minimum time taken by the trucks to travel to the respected cities with their types of garbage. (For example, the minimum time needed for the paper garbage truck to travel to the cities with paper garbage)\n2. We need to calculate the frequency of each type of garbage and thus find out the totsl time needed to collect the garbage\n3. We need to find the the last city in the `garbage` array with a certain type of garbage to find the time needed by that type of truck in travelling.(For example we need to find the last city with Paper garbage and hence the total time needed by the truck in travelling)\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize `m`,`g`&`p` to calculate last occurrence of Metal, Glass and Paper type of garbage and `a`,`b`&`c` to calculate frequency of Metal, Paper and Glass type of garbage respectively. \n2. We create a `v` array to store the prefix sum storing 0 at the first index for the base condition.(In case, a type of garbage is absent)\n3. We iterate through the `garbage` array and store to find values of `m`,`g`&`p` while counting the frequencies in \'a\',\'b\'&\'c\'.\n4. Update the latest index of `v` array storing the prefix sum of `travel` in it.\n5. Return the sum of total frequencies and the time needed to reach city at positions `m`,`g`&`p` separately. \n# Complexity\n- Time complexity: O(n), where n is the number of houses, with only one for loop iterating in the whole algorithm.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n), to create the `v` array for storing the prefix sum of `travel`.\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 ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n int m=0,g=0,p=0,a=0,b=0,c=0;\n vector<int> v(garbage.size(),0);\n v.push_back(0);\n for(int i=travel.size();i>=0;i--){\n for(int j=0;j<garbage[i].length();j++){\n if(garbage[i][j]==\'M\'){\n a++;\n if(i>m)\n m=i;}\n else if(garbage[i][j]==\'P\'){\n b++;\n if(i>p)\n p=i;}\n else{\n c++;\n if(i>g)\n g=i;}\n }\n if(i>0)\n v[travel.size()-i+1]=v[travel.size()-i]+travel[travel.size()-i];\n }\n return a+v[m]+b+v[p]+c+v[g];\n }\n};\n```
4
0
['Array', 'String', 'Prefix Sum', 'C++']
1
minimum-amount-of-time-to-collect-garbage
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
cjavapythonjavascript-2-approaches-expla-5bae
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n#### Approach 1(HashMaps)\n1. Prefix Sum Calculation:\n\n - prefixSum ve
MarkSPhilip31
NORMAL
2023-11-20T07:50:03.364836+00:00
2023-11-20T07:50:03.364859+00:00
642
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(HashMaps)***\n1. **Prefix Sum Calculation:**\n\n - `prefixSum` vector stores the prefix sum of the `travel` vector.\n - It helps in calculating the distance traveled up to a certain point efficiently.\n1. **Garbage Collection Information:**\n\n - `garbageLastPos` is an unordered map that tracks the last house index for each type of garbage.\n - `garbageCount` stores the total count of each type of garbage across all houses.\n1. **Garbage Types:**\n\n - The `garbageTypes` array holds the three types of garbage: `M`, `P`, and `G`.\n1. **Main Calculation (Loop):**\n\n - For each garbage type, if there is at least one unit of this garbage:\n - The calculation involves adding the distance traveled to the last house where this garbage type was found (`prefixSum[garbageLastPos[c]]`) and the total count of this garbage type (`garbageCount[c]`).\n - The sum of these distances and counts is accumulated in `ans`.\n1. **Return:**\n\n - The function returns the final value of `ans`, which represents the calculated total for garbage collection considering the conditions mentioned in the code.\n\n# Complexity\n- *Time complexity:*\n $$O(N*K)$$\n \n\n- *Space complexity:*\n $$O(N)$$\n \n\n\n# Code\n```C++ []\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 // Array to store garbage types.\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\n\n```\n\n```C []\nstruct GarbageInfo {\n char type;\n int count;\n};\n\nint garbageCollection(char** garbage, int* travel, int garbageSize, int travelSize) {\n int prefixSum[travelSize + 1];\n prefixSum[1] = travel[0];\n for (int i = 1; i < travelSize; i++) {\n prefixSum[i + 1] = prefixSum[i] + travel[i];\n }\n \n struct GarbageInfo garbageLastPos[256]; // Assuming ASCII characters\n struct GarbageInfo garbageCount[256]; // Assuming ASCII characters\n \n for (int i = 0; i < garbageSize; i++) {\n for (int j = 0; garbage[i][j] != \'\\0\'; j++) {\n char c = garbage[i][j];\n garbageLastPos[c].type = c;\n garbageLastPos[c].count = i;\n garbageCount[c].count++;\n }\n }\n \n char garbageTypes[3] = {\'M\', \'P\', \'G\'};\n int ans = 0;\n for (int i = 0; i < 3; i++) {\n char c = garbageTypes[i];\n if (garbageCount[c].count > 0) {\n ans += prefixSum[garbageLastPos[c].count] + garbageCount[c].count;\n }\n }\n \n return ans;\n}\n\n```\n\n```Java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n // Array to store the prefix sum in travel.\n int[] prefixSum = new int[travel.length + 1];\n prefixSum[1] = travel[0];\n for (int i = 1; i < travel.length; i++) {\n prefixSum[i + 1] = prefixSum[i] + travel[i];\n }\n\n // Map to store garbage type to the last house index.\n Map<Character, Integer>garbageLastPos = new HashMap<Character, Integer>();\n\n // Map to store the total count of each type of garbage in all houses.\n Map<Character, Integer>garbageCount = new HashMap<Character, Integer>();\n for (int i = 0; i < garbage.length; i++) {\n for (char c : garbage[i].toCharArray()) {\n garbageLastPos.put(c, i);\n garbageCount.put(c, garbageCount.getOrDefault(c, 0) + 1);\n }\n }\n\n String garbageTypes = "MPG";\n int ans = 0;\n for (char c : garbageTypes.toCharArray()) {\n // Add only if there is at least one unit of this garbage.\n if (garbageCount.containsKey(c)) {\n ans += prefixSum[garbageLastPos.get(c)] + garbageCount.get(c);\n }\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\ndef garbage_collection(garbage, travel):\n prefix_sum = [0] * (len(travel) + 1)\n prefix_sum[1] = travel[0]\n for i in range(1, len(travel)):\n prefix_sum[i + 1] = prefix_sum[i] + travel[i]\n\n garbage_last_pos = {}\n garbage_count = {}\n for i in range(len(garbage)):\n for c in garbage[i]:\n garbage_last_pos[c] = i\n garbage_count[c] = garbage_count.get(c, 0) + 1\n\n garbage_types = [\'M\', \'P\', \'G\']\n ans = 0\n for c in garbage_types:\n if garbage_count.get(c):\n ans += prefix_sum[garbage_last_pos[c]] + garbage_count[c]\n\n return ans\n\n\n\n```\n```javascript []\nfunction garbageCollection(garbage, travel) {\n let prefixSum = Array(travel.length + 1).fill(0);\n prefixSum[1] = travel[0];\n for (let i = 1; i < travel.length; i++) {\n prefixSum[i + 1] = prefixSum[i] + travel[i];\n }\n\n let garbageLastPos = {};\n let garbageCount = {};\n for (let i = 0; i < garbage.length; i++) {\n for (let j = 0; j < garbage[i].length; j++) {\n let c = garbage[i][j];\n garbageLastPos[c] = i;\n garbageCount[c] = (garbageCount[c] || 0) + 1;\n }\n }\n\n let garbageTypes = [\'M\', \'P\', \'G\'];\n let ans = 0;\n for (let c of garbageTypes) {\n if (garbageCount[c]) {\n ans += prefixSum[garbageLastPos[c]] + garbageCount[c];\n }\n }\n\n return ans;\n}\n\n\n```\n\n---\n\n#### ***Approach 2(HashMap and In-place Modification)***\n\n1. **Prefix Sum Calculation:**\n - The code utilizes the `travel` vector to calculate the prefix sum by updating each element in the vector. It reassigns each element with the cumulative sum of all the elements up to that index.\n\n1. **Garbage Types and Positions:**\n\n - It uses an unordered map `garbageLastPos` to store the last house index for each garbage type (`M`, `P`, `G`) encountered in the input.\n - Additionally, it accumulates the total count of all characters in the `garbage` vector by iterating through each string in the vector. The variable `ans` stores this count initially.\n1. **Iterating through Garbage Types:**\n\n - Utilizes a string `garbageTypes` containing the characters `M`, `P`, `G`.\n - Iterates through each character in `garbageTypes` and checks the corresponding last house index for that type in the `garbageLastPos` map.\n - If the last house index for a particular garbage type is 0, it implies no travel time is required for that type. Otherwise, it calculates the travel time for that type using the prefix sum.\n1. **Returning the Total Answer:**\n - The function returns the accumulated value in `ans`, which represents the total calculated travel time required for garbage collection.\n\n\n# Complexity\n- *Time complexity:*\n $$O(N*K)$$\n \n\n- *Space complexity:*\n $$O(N)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n // Store the prefix sum in travel itself.\n for (int i = 1; i < travel.size(); i++) {\n travel[i] = travel[i - 1] + travel[i];\n }\n \n // Map to store garbage type to the last house index.\n unordered_map<char, int> garbageLastPos;\n int ans = 0;\n for (int i = 0; i < garbage.size(); i++) {\n for (char c : garbage[i]) {\n garbageLastPos[c] = i;\n }\n ans += garbage[i].size();\n }\n \n string garbageTypes = "MPG";\n for (char c : garbageTypes) {\n // No travel time is required if the last house is at index 0.\n ans += (garbageLastPos[c] == 0 ? 0 : travel[garbageLastPos[c] - 1]);\n }\n \n return ans;\n }\n};\n\n```\n\n```C []\n\n#define MAX_GARBAGE_SIZE 1000\n\nint garbageCollection(char garbage[MAX_GARBAGE_SIZE][MAX_GARBAGE_SIZE], int travel[MAX_GARBAGE_SIZE], int garbageCount) {\n int travelSum[MAX_GARBAGE_SIZE] = {0};\n travelSum[0] = travel[0];\n\n for (int i = 1; i < garbageCount; i++) {\n travelSum[i] = travelSum[i - 1] + travel[i];\n }\n\n int garbageLastPos[256] = {0};\n int ans = 0;\n\n for (int i = 0; i < garbageCount; i++) {\n for (int j = 0; j < strlen(garbage[i]); j++) {\n garbageLastPos[garbage[i][j]] = i;\n }\n ans += strlen(garbage[i]);\n }\n\n char garbageTypes[] = "MPG";\n for (int i = 0; i < strlen(garbageTypes); i++) {\n ans += (garbageLastPos[garbageTypes[i]] == 0 ? 0 : travelSum[garbageLastPos[garbageTypes[i]] - 1]);\n }\n\n return ans;\n}\n\n```\n\n```Java []\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n // Store the prefix sum in travel itself.\n for (int i = 1; i < travel.length; i++) {\n travel[i] = travel[i - 1] + travel[i];\n }\n\n // Map to store garbage type to the last house index.\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 // No travel time is required if the last house is at index 0.\n ans += (garbageLastPos.getOrDefault(c, 0) == 0 ? 0 : travel[garbageLastPos.get(c) - 1]);\n }\n\n return ans;\n }\n}\n\n```\n\n```python3 []\n\ndef garbage_collection(garbage, travel):\n for i in range(1, len(travel)):\n travel[i] += travel[i - 1]\n \n garbage_last_pos = {}\n ans = 0\n for i in range(len(garbage)):\n for c in garbage[i]:\n garbage_last_pos[c] = i\n ans += len(garbage[i])\n \n garbage_types = "MPG"\n for c in garbage_types:\n ans += travel[garbage_last_pos.get(c, 0) - 1] if garbage_last_pos.get(c, 0) != 0 else 0\n \n return ans\n\n\n```\n```javascript []\nfunction garbageCollection(garbage, travel) {\n for (let i = 1; i < travel.length; i++) {\n travel[i] += travel[i - 1];\n }\n\n const garbageLastPos = {};\n let ans = 0;\n for (let i = 0; i < garbage.length; i++) {\n for (const c of garbage[i]) {\n garbageLastPos[c] = i;\n }\n ans += garbage[i].length;\n }\n\n const garbageTypes = "MPG";\n for (const c of garbageTypes) {\n ans += (garbageLastPos[c] === 0 ? 0 : travel[garbageLastPos[c] - 1]);\n }\n\n return ans;\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
4
0
['Array', 'String', 'C', 'Prefix Sum', 'C++', 'Java', 'Python3', 'JavaScript']
0
minimum-amount-of-time-to-collect-garbage
Eay concise Python solution 1 pass O(n) travel backwards
eay-concise-python-solution-1-pass-on-tr-kflu
Observe that every truck will have to travel to the last house that has the garbage of its kind and stop there. Therefore, the original problem is equivalent to
gauau
NORMAL
2023-11-20T01:56:58.971623+00:00
2023-11-20T02:02:04.457657+00:00
183
false
Observe that every truck will have to travel to the last house that has the garbage of its kind and stop there. Therefore, the original problem is equivalent to "each truck starts at its last index and ends at index 0"\n-> We can traverse the input array backwards and solve the problem in 1 pass\n```\ndef garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n\ttime = [0, 0, 0]\n\tdic = {0: \'M\', 1: \'P\', 2: \'G\'}\n\tfor i in range(len(garbage) - 1, -1 , -1):\n\t\tfor j in range(3):\n\t\t\ttime[j] += garbage[i].count(dic[j])\n\t\t\tif i != 0 and time[j] != 0:\n\t\t\t\ttime[j] += travel[i-1]\n\treturn sum(time)\n```
4
0
[]
1
minimum-amount-of-time-to-collect-garbage
C++/CPP : Simple Logic
ccpp-simple-logic-by-piyushghante-hfbr
\n\n# Code\n\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n \n int n=garbage.size();\n\n
piyushghante
NORMAL
2023-09-08T11:40:34.009646+00:00
2023-09-08T12:08:24.479899+00:00
216
false
\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n \n int n=garbage.size();\n\n int p=0;\n int m=0;\n int g=0;\n\n int p_travel_cost=0;\n int m_travel_cost=0;\n int g_travel_cost=0;\n\n int temp=0;\n int temp1=0;\n int temp2=0;\n\n for(int i=0;i<n;i++) \n {\n\n\n for(auto it:garbage[i])\n {\n if(it == \'P\' )\n { \n p++;\n temp=i;\n\n }\n if(it == \'G\' )\n { \n g++;\n temp1=i;\n }\n if(it == \'M\' )\n { \n m++;\n temp2=i;\n }\n }\n\n\n\n\n }\n \n \n \n for(int l=0;l<temp;l++){\n p_travel_cost += travel[l];\n }\n\n \n for(int l=0;l<temp1;l++){\n m_travel_cost += travel[l];\n }\n\n \n \n for(int l=0;l<temp2;l++){\n g_travel_cost += travel[l];\n }\n\n \n\n return (p+p_travel_cost)+(m+m_travel_cost)+(g+g_travel_cost);\n }\n};\n```
4
0
['C++']
0
minimum-amount-of-time-to-collect-garbage
C++||Easy and Simple ||
ceasy-and-simple-by-adil_2024-1hf6
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
adil_2024
NORMAL
2023-04-04T05:49:40.796296+00:00
2023-04-04T05:49:40.796344+00:00
631
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 cnt=0,last_p=0,last_g=0,last_m=0;\n for(int i=0;i<garbage.size();i++){\n for(auto c:garbage[i]){\n // count the all character beacuse it must be take 1 minutes to collect it;\n cnt++;\n// find the last index of \'p\' ;\n// so we move only upto that last character;\n if(c==\'P\') last_p=i;\n// find the last index of \'g\' ;\n// so we move only upto that last character;\n else if(c==\'G\') last_g=i;\n// find the last index of \'m\' ;\n// so we move only upto that last character;\n else last_m=i;\n }\n }\n for(int i=1;i<travel.size();i++){\n// prefixsum of all element of travel (array);\n travel[i]+=travel[i-1];\n }\n int ans=cnt;\n // sum of minute to travel from one house(zero indexing house ) \n// to last indexing of particular types of garbage; \n if(last_p>0) ans+=travel[last_p-1];\n if(last_g>0) ans+=travel[last_g-1];\n if(last_m>0) ans+=travel[last_m-1];\n return ans;\n }\n};\n```
4
0
['C++']
0
minimum-amount-of-time-to-collect-garbage
C++ ||10 lines||most optimized||O(n)||O(1)
c-10-linesmost-optimizedono1-by-sheetal0-s29i
Intuition\nWe start from last house, then check if this house has that grabage or not. If it has we pickup the garbage and calculate cost to travel to this hous
sheetal0797
NORMAL
2023-01-28T07:34:44.037985+00:00
2023-01-28T07:34:44.038029+00:00
308
false
# Intuition\nWe start from last house, then check if this house has that grabage or not. If it has we pickup the garbage and calculate cost to travel to this house which had same garbage. and keep adding cost to travel now onwards to the first house.\nOtherwise, we just go to next house.\n\n\n# Approach\n\n# Complexity\n- Time complexity:O(n) For traversing garbage array only once.\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n bool fg=false,fp=false,fm=false;\n int g=0,p=0,m=0;\n for(int i=garbage.size()-1;i>=0;i--)\n {\n for(char c:garbage[i])\n {\n if(c==\'G\'){g++; fg=true;}\n else if(c==\'P\'){ p++;fp=true;}\n else if(c==\'M\') {m++; fm=true;}\n }\n if (i!=0 && fg==true)g+=travel[i-1];\n if (i!=0 && fp==true)p+=travel[i-1];\n if (i!=0 && fm==true)m+=travel[i-1];\n }\n return g+m+p;\n }\n};
4
0
['C++']
0
minimum-amount-of-time-to-collect-garbage
Simple Java Solution faster than 97%
simple-java-solution-faster-than-97-by-s-rw8f
\n\nclass Solution {\n public int garbageCollection(String[] g, int[] travel) {\n int ans = getTimeForGarbage(g,travel,\'M\')+getTimeForGarbage(g,tr
Sarthak_Singh_
NORMAL
2022-12-25T06:35:52.856445+00:00
2022-12-25T06:35:52.856490+00:00
457
false
\n```\nclass Solution {\n public int garbageCollection(String[] g, int[] travel) {\n int ans = getTimeForGarbage(g,travel,\'M\')+getTimeForGarbage(g,travel,\'G\')+getTimeForGarbage(g,travel,\'P\');\n return ans; \n\n }\n private static int getTimeForGarbage(String[] g, int[] travel, Character gType){\n int n = g.length;\n int lastHouseToVisit = -1;\n int totalTime = 0;\n for(int i =0;i<n;i++){\n if(g[i].indexOf(gType)!=-1){\n lastHouseToVisit = i;\n }\n }\n if(lastHouseToVisit ==-1){\n return 0 ;\n }\n totalTime=0;\n for(int i =0;i<=lastHouseToVisit;i++){\n totalTime += getCount(g[i],gType);\n if(i-1>=0){\n totalTime += travel[i-1];\n }\n }\n return totalTime;\n }\n\n private static int getCount(String s, Character gType){\n int total = 0;\n for(int i=0;i<s.length(); i++){\n if(gType == s.charAt(i)){\n total++;\n }\n }\n return total;\n } \n }\n\n```
4
1
['Java']
1
minimum-amount-of-time-to-collect-garbage
Python Well explained | Simple solution
python-well-explained-simple-solution-by-512n
As mentioned in the hint we fist calculate the maximum index for each catagory where at least 1 unit of garbage of that type is present. \n\n2. Here IN takes O(
vkadu68
NORMAL
2022-11-02T21:06:10.590948+00:00
2022-11-02T21:06:10.590993+00:00
315
false
1. As mentioned in the hint we fist calculate the maximum index for each catagory where at least 1 unit of garbage of that type is present. \n\n2. Here IN takes O(1) because the categopries are constant\nthen we take the sum of the travel array unilt that index for each category and then add it into our result.\n\n3. we will also add the length of every element in the garbage to the result as it take 1 unit of time to \ncollect it. \n\n4. If the any category is only present at the 0th index or doest exist in our garbage list at all we dont need to add the sum of tavel array as the garbage truk wont need any time to travel\n\n***Leve an upvote if this helps!!!***\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n l,m,p,g,res=0,0,0,0,0\n for i in range(len(garbage)):\n if \'M\' in garbage[i] and m<i:\n m=i\n if \'P\' in garbage[i] and p<i:\n p=i\n if \'G\' in garbage[i] and g<i:\n g=i\n l+=len(garbage[i])\n if m!=0:\n res=sum(travel[:m])\n if p!=0:\n res+=sum(travel[:p])\n if g!=0:\n res+=sum(travel[:g])\n return res+l\n```
4
0
['Python']
0
minimum-amount-of-time-to-collect-garbage
✅✅Faster || Easy To Understand || C++ Code
faster-easy-to-understand-c-code-by-__kr-9vxn
Using Prefix Sum\n\n Time Complexity :- O(N)\n\n Space Complexity :- O(1)\n\n\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vec
__KR_SHANU_IITG
NORMAL
2022-08-29T08:11:01.267323+00:00
2022-08-29T08:11:01.267347+00:00
270
false
* ***Using Prefix Sum***\n\n* ***Time Complexity :- O(N)***\n\n* ***Space Complexity :- O(1)***\n\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n \n int n = garbage.size();\n \n // find the last position of each type of garbage\n \n int g_end = -1;\n \n int p_end = -1;\n \n int m_end = -1;\n \n // garbage count will store the no. of garbages\n \n int garbage_count = 0;\n \n for(int i = 0; i < n; i++)\n {\n string str = garbage[i];\n \n // update the garbage count\n \n garbage_count += str.size();\n \n // update the position of each type of garbage\n \n for(auto x : str)\n {\n if(x == \'G\')\n {\n g_end = i;\n }\n else if(x == \'P\')\n {\n p_end = i;\n }\n else if(x == \'M\')\n {\n m_end = i;\n } \n }\n }\n \n // find prefix sum for travel array\n \n for(int i = 1; i < n - 1; i++)\n {\n travel[i] += travel[i - 1];\n }\n \n // find the travel time\n \n int travel_time = 0;\n \n if(g_end > 0)\n {\n travel_time += travel[g_end - 1];\n }\n \n if(p_end > 0)\n {\n travel_time += travel[p_end - 1];\n }\n \n if(m_end > 0)\n {\n travel_time += travel[m_end - 1];\n }\n \n // time to collect the garbage will be equal to garbage_count\n \n // picking up a garbage will take 1 unit of time\n \n // return total_time\n \n return travel_time + garbage_count;\n }\n};\n```
4
0
['C', 'Prefix Sum', 'C++']
1
minimum-amount-of-time-to-collect-garbage
Easy C++ Code || Beats 100% Submission || O(1) Space || Prefix Sum
easy-c-code-beats-100-submission-o1-spac-ht7h
```\nint garbageCollection(vector&v, vector& t) {\n int i,n=v.size(),m=-1,g=-1,p=-1,ans=0;\n for(i=n-1;i>=0;i--){\n for(char c : v[i]){
vidit987
NORMAL
2022-08-28T10:54:48.518067+00:00
2022-08-28T10:56:27.580621+00:00
133
false
```\nint garbageCollection(vector<string>&v, vector<int>& t) {\n int i,n=v.size(),m=-1,g=-1,p=-1,ans=0;\n for(i=n-1;i>=0;i--){\n for(char c : v[i]){\n // storing the last index of each char \'P\',\'M\',\'G\';\n if(c==\'P\' && p==-1)p=i;\n if(c==\'G\' && g==-1)g=i;\n if(c==\'M\' && m==-1)m=i;\n ans++; // incrementing ans by 1 bcoz every garbage needs 1 min to be collected; \n }\n }\n for(i=1;i<n-1;i++){\n t[i]+=t[i-1]; // prefix sum;\n }\n if(p>0)ans+=t[p-1]; \n // truck collecting garbage \'P\' needs to travel till the house number p , so add the time taken to reach that house and do the same thing for other two trucks;\n if(g>0)ans+=t[g-1];\n if(m>0)ans+=t[m-1];\n return ans;\n }
4
0
['C', 'Prefix Sum']
1
minimum-amount-of-time-to-collect-garbage
Java Easy Solution using Map
java-easy-solution-using-map-by-devkd-ooyq
Java Easy Solution using HashMap\n\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans=0;\n //Creating
DevKD
NORMAL
2022-08-28T04:26:44.062159+00:00
2022-08-28T04:26:44.062202+00:00
455
false
# Java Easy Solution using HashMap\n```\nclass Solution {\n public int garbageCollection(String[] garbage, int[] travel) {\n int ans=0;\n //Creating a map to store type of garbage and where it is found\n HashMap<Character,List<Integer>> map=new HashMap<Character,List<Integer>>();\n char[] var=new char[3];\n var[0]=\'M\';\n var[1]=\'P\';\n var[2]=\'G\';\n //Creating an empty arraylist for each type of garbage\n for(int i=0;i<var.length;i++){\n List<Integer> list=new ArrayList<Integer>();\n map.put(var[i],list);\n }\n \n //Itertaing over each position and updating the map\n for(int i=0;i<garbage.length;i++){\n for(int j=0;j<garbage[i].length();j++){\n if(map.containsKey(garbage[i].charAt(j))){\n List<Integer> a=map.get(garbage[i].charAt(j));\n a.add(i);\n }\n else{\n List<Integer> a=new ArrayList<Integer>();\n a.add(i);\n map.put(garbage[i].charAt(j),a);\n }\n }\n }\n \n //Iterating over each type of metal\n for(int i=0;i<var.length;i++){\n //Accesing the list of postiions for that garbage\n List<Integer> list=map.get(var[i]);\n int j=0;\n //Total minutes require for a particular type of garbage is tore in ans1\n int ans1=0;\n int pos=0;\n //Iterating over list\n while(j<list.size()){\n //If different postion so adding the travel time to ans1\n if(list.get(j)!=pos){\n for(int k=pos;k<list.get(j);k++){\n ans1+=travel[k];\n }\n ans1++;\n pos=list.get(j);\n }\n //Adding the garbage collection time to ans\n else{\n ans1++;\n }\n ++j;\n }\n //Adding ans to ans1\n ans+=ans1;\n }\n return ans;\n }\n}\n```
4
0
['Math', 'Java']
1
minimum-amount-of-time-to-collect-garbage
C++ Using hashmap || Beginner friendly & east to understand approach
c-using-hashmap-beginner-friendly-east-t-f18c
\nclass Solution {\npublic:\n int findTime(vector<string>& garbage, vector<int>& travel, char type, unordered_map<char, int> &mpp){\n int minute = 0;\
shm_47
NORMAL
2022-08-28T04:26:12.333147+00:00
2022-08-28T04:28:30.265186+00:00
330
false
```\nclass Solution {\npublic:\n int findTime(vector<string>& garbage, vector<int>& travel, char type, unordered_map<char, int> &mpp){\n int minute = 0;\n \n //every house\n for(int i=0; i<garbage.size(); i++){\n if(mpp[type]>0){ //if that type of garbage remains to collect\n \n //garbage at a particular house\n for(int j=0; j<garbage[i].size(); j++){\n if(garbage[i][j]== type){\n minute++;\n mpp[type]--;\n }\n }\n \n //add travelling cost if same type of garbage yet to collect\n if(mpp[type]>0)\n minute += travel[i];\n } \n }\n \n return minute;\n }\n \n int garbageCollection(vector<string>& garbage, vector<int>& travel) {\n //to track whether all the garbage collected of same type\n unordered_map<char, int> mpp;\n for(auto it: garbage){\n for(auto jt: it)\n mpp[jt]++;\n }\n \n vector<char> type = {\'P\', \'G\', \'M\'}; //paper, glass, metal\n int minutes = 0;\n for(int i=0; i<type.size(); i++){\n minutes += findTime(garbage, travel, type[i], mpp);\n }\n \n return minutes;\n }\n};\n```\n\nPlease do upvote if you like the soln:)
4
0
['C']
1
minimum-amount-of-time-to-collect-garbage
Python explained
python-explained-by-sachin_c-kbw6
Just keep track of last occuarnce of each garbage type.\nSince we know the number of types we can set a multiplier from start.\nAnd since each of garbage takes
sachin_c
NORMAL
2022-08-28T04:21:49.410470+00:00
2022-08-28T04:23:38.634845+00:00
459
false
Just keep track of last occuarnce of each garbage type.\nSince we know the number of types we can set a multiplier from start.\nAnd since each of garbage takes same amount of time and each truck takes same amount of time to travel we can just append our solution and just decrease multiplier if last occurance of garbage is achieved.\n\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n last=["","",""]\n for v,i in enumerate(garbage):\n if \'M\' in i:\n last[0]=v\n if \'P\' in i:\n last[1]=v\n if \'G\' in i:\n last[2]=v\n while \'\' in last:\n last.remove(\'\') \n t=len(last)\n sol=len(garbage[0])\n t-=last.count(0)\n for i in range(1,len(garbage)):\n sol+=len(garbage[i])\n sol+=(t*travel[i-1])\n t-=last.count(i)\n return sol\n```
4
0
['Python']
1
minimum-amount-of-time-to-collect-garbage
CPP | Easy | Prefix sum
cpp-easy-prefix-sum-by-amirkpatna-vkia
Intuition : Just a simple greedy problem my approach was bit different though.\nI calculated prefix sum of travel.\nAnd simply I keep adding number of particula
amirkpatna
NORMAL
2022-08-28T04:02:24.379070+00:00
2022-08-28T04:05:39.342500+00:00
387
false
**Intuition :** Just a simple greedy problem my approach was bit different though.\nI calculated `prefix sum` of `travel`.\nAnd simply I keep adding number of particular garbages occurs for any type in my answer\nand after that I started from back and kept looking which which garbage is occuring where for the first time .\n\n```\nclass Solution {\npublic:\n int garbageCollection(vector<string>& g, vector<int>& t) {\n int n=g.size(),ans=0;\n for(int i=1;i<t.size();i++)t[i]+=t[i-1];\n for(string &s:g){\n ans+=(int)s.length();\n }\n bool taken[3]={false,false,false};\n for(int i=n-1;i>0;i--){\n bool flag[3]={false,false,false};\n for(char c:g[i]){\n if(c==\'M\')flag[0]=true;\n else if(c==\'P\')flag[1]=true;\n else flag[2]=true;\n }\n for(int j=0;j<3;j++){\n if(flag[j] && !taken[j])ans+=t[i-1],taken[j]=true;\n }\n }\n return ans;\n }\n};\n```
4
0
['Prefix Sum', 'C++']
1
minimum-amount-of-time-to-collect-garbage
[Python3] simulation
python3-simulation-by-ye15-rigf
Please pull this commit for solutions of weekly 308.\n\nIntuition\nThe total time can be decomposed into 1) time to collect gargage and 2) time to travel to nex
ye15
NORMAL
2022-08-28T04:01:56.523890+00:00
2022-08-28T04:49:36.481271+00:00
335
false
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/ea6bc01b091cbf032b9c7ac2d3c09cb4f5cd0d2d) for solutions of weekly 308.\n\n**Intuition**\nThe total time can be decomposed into 1) time to collect gargage and 2) time to travel to next stop. \nHere, the first component is simply the sum of length of strings in `garbage`. The second component depends on the last stop for each garbage type. For convenience, I use prefix sum to compute them. \n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n ans = sum(map(len, garbage))\n prefix = list(accumulate(travel, initial=0))\n for ch in "MPG": \n ii = 0 \n for i, s in enumerate(garbage): \n if ch in s: ii = i \n ans += prefix[ii]\n return ans \n```
4
0
['Python3']
1
minimum-amount-of-time-to-collect-garbage
Efficient Garbage Collection with Optimized Travel Time using C++ ✅✅
optimal-solution-beats-100-using-c-by-ha-t6da
IntuitionThe problem involves collecting different types of garbage from several houses and minimizing the total travel time. Each type of garbage is collected
harish_cs2023
NORMAL
2025-02-09T07:11:22.831615+00:00
2025-02-09T12:13:44.406853+00:00
75
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves collecting different types of garbage from several houses and minimizing the total travel time. Each type of garbage is collected by a specific truck. The approach involves first counting the amount of each type of garbage and tracking the last house that contains each type. We then calculate the total time by summing the time taken to collect each type of garbage and the travel time to the last house that contains each type. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize counters for each type of garbage (g, p, m) and variables to track the last house containing each type of garbage (gi, pi, mi). 2. Iterate through the garbage vector: 3. Count the occurrence of each type of garbage. 4. Update the last index where each type of garbage is found. 5. Iterate through the travel vector to calculate the total travel time for each garbage type up to its last house. 6. Return the sum of the total counts and the travel times. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int garbageCollection(vector<string>& garbage, vector<int>& travel) { int g = 0, p = 0, m = 0; int gi = 0, pi = 0, mi = 0; for(int i = 0; i < garbage.size(); i++) { for(char j : garbage[i]) { if(j == 'G') { g+=1; gi = i; } else if(j == 'P') { p+=1; pi = i; } else if(j == 'M') { m+=1; mi = i; } } } for(int i = 0; i < travel.size(); i++) { if (i < gi) g+=travel[i]; if (i < pi) p+=travel[i]; if (i < mi) m+=travel[i]; } return g + p + m; } }; ```
3
0
['C++']
0
minimum-amount-of-time-to-collect-garbage
Python Easy & Brute force Solution
python-easy-brute-force-solution-by-labd-75a8
Approach\nBrute force\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n\n# Code\n\nclass Solution:\n def garbageCollection(self, gar
labdhigathani9999
NORMAL
2023-11-20T12:45:10.111984+00:00
2023-11-20T12:47:20.698205+00:00
39
false
# Approach\nBrute force\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n join_garbage = "".join(garbage)\n count = 0\n for i in join_garbage:\n if i == \'M\':\n count += 1\n\n count_1 = 0\n for j in join_garbage:\n if j == \'P\':\n count_1 += 1 \n\n count_2 = 0\n for k in join_garbage:\n if k == \'G\':\n count_2 += 1 \n\n c = []\n for p in reversed(range(len(garbage))):\n if \'M\' in garbage[p]:\n c = travel[:p]\n break\n c_sum = sum(c) \n\n c_1 = []\n for q in reversed(range(len(garbage))):\n if \'P\' in garbage[q]:\n c_1 = travel[:q]\n break\n c_1_sum = sum(c_1)\n\n c_2 = []\n for r in reversed(range(len(garbage))):\n if \'G\' in garbage[r]:\n c_2 = travel[:r]\n break\n c_2_sum = sum(c_2)\n\n return count + count_1 + count_2 + c_sum + c_1_sum + c_2_sum \n\n\n\n\n\n \n```
3
0
['Python', 'Python3']
0