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
count-alternating-subarrays
[O(n)] Simple and clean, sliding window
on-simple-and-clean-sliding-window-by-fr-0rbv
Loop through and consider number of subarrays that end at j.\nSimple sliding window of the current alternating block.\nint j - end of alternating block\nint i -
frvnk
NORMAL
2024-03-31T07:11:15.690603+00:00
2024-03-31T07:11:15.690639+00:00
61
false
Loop through and consider number of subarrays that end at `j`.\nSimple sliding window of the current alternating block.\n`int j` - end of alternating block\n`int i` - minimum first index of current alternating block\n`int res` - total count of alternating subarrays\n\nAll subarrays $[i,j] , [i+1,j], \\ldots[j,j]$ are valid alternating subarrays, this yields `j-i+1` added to our result.\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long res = 1;\n int i =0; // index to start alternating block\n for(int j = 1; j< nums.size(); j++){\n if(nums[j-1] == nums[j]){\n i = j; //new alternating block\n }\n res += j-i+1;\n }\n return res;\n }\n};\n```
1
0
['C++']
1
count-alternating-subarrays
✅ C++ Solution ✅ || Sliding window || Optimal
c-solution-sliding-window-optimal-by-ans-9wap
Approach\n Describe your approach to solving the problem. \n\nUses Sliding window\n\nDry run this example for better understanding : [1,0,1,0,0,1]\n\n# Complexi
anshumaan1024
NORMAL
2024-03-31T05:52:28.808089+00:00
2024-03-31T12:18:15.424457+00:00
91
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n\n**Uses Sliding window**\n\n*Dry run this example for better understanding* : [1,0,1,0,0,1]\n\n# Complexity\n- Time complexity: **O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n \n int n = nums.size(); \n long long ans = 0;\n int i=0,j=1;\n int t = 0;\n \n while(j<n){\n \n if( nums[t] != nums[j] ){\n // number of alternate subarray ending at \'j\'\n ans += j - i;\n t++;\n }\n \n else{\n i = j;\n t = j;\n }\n\n j++;\n \n } \n \n // add \'n\' as, each element itself is a alternate subbarray\n return ans + n;\n \n }\n};\n```
1
0
['Sliding Window', 'C++', 'Java']
0
count-alternating-subarrays
Easy Java Solution || Beats 100%
easy-java-solution-beats-100-by-ravikuma-z14c
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2024-03-31T05:30:56.096531+00:00
2024-03-31T05:30:56.096549+00:00
10
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 long countAlternatingSubarrays(int[] arr) {\n ArrayList<Long> count = new ArrayList<>();\n long max = 1;\n int x = arr[0];\n int n = arr.length;\n for(int i=1; i<n; i++){\n if(arr[i]!=x){\n max++;\n x = arr[i];\n }else{\n count.add(max);\n max = 1;\n x = arr[i];\n }\n }\n count.add(max);\n \n long ans = 0;\n \n for(int i=0; i<count.size(); i++){\n long k = count.get(i);\n ans = ans + ((k*(k+1))/2);\n }\n return ans;\n }\n}\n```
1
0
['Java']
0
count-alternating-subarrays
Java | Standard sliding window | time: O(n) | space: O(1)
java-standard-sliding-window-time-on-spa-1gcq
# Intuition \n\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(1)\n\n\n# Code\n\nclass Solution {\n public long countAlternatingS
shashankbhat
NORMAL
2024-03-31T04:32:52.802912+00:00
2024-03-31T04:32:52.802934+00:00
44
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long result = 0;\n \n int end = 0;\n int start = 0;\n while(end < nums.length) {\n if(end == 0)\n result++;\n else {\n while(end < nums.length && nums[end] != nums[end - 1]) {\n end++;\n result += end - start;\n }\n \n if(end != nums.length) {\n result++;\n start = end;\n }\n }\n end++;\n }\n \n return result;\n }\n}\n```
1
0
['Two Pointers', 'Sliding Window', 'Java']
0
count-alternating-subarrays
✅ Java || Time O(n) || Space O(1) || Sliding Window || Beginner Friendly Explanation ✅
java-time-on-space-o1-sliding-window-beg-aemo
\n\n# Intuition\nThe problem involves counting the number of alternating subarrays in an array. An alternating subarray is defined as a contiguous subarray wher
0xsonu
NORMAL
2024-03-31T04:21:02.419807+00:00
2024-03-31T04:22:20.695355+00:00
47
false
![image.png](https://assets.leetcode.com/users/images/566b3286-c4fa-4b58-96bc-edc85286ed43_1711858934.2896192.png)\n\n# Intuition\nThe problem involves counting the number of alternating subarrays in an array. An alternating subarray is defined as a contiguous subarray where all elements are either strictly increasing or strictly decreasing. An initial intuition could be to iterate through the array and check for alternating patterns. However, a more efficient approach can be devised by observing that each element can contribute to multiple alternating subarrays, depending on its position and the elements around it.\n\n# Approach\n1. Initialize variables `count` and `consecutive` to keep track of the total count of alternating subarrays and the length of the current consecutive increasing or decreasing sequence, respectively.\n2. Iterate over the array starting from the second element:\n - If the current element is different from the previous element, increment `consecutive` by 1 and add it to `count`.\n - If the current element is the same as the previous element, reset `consecutive` to 1 and add it to `count`.\n3. After iterating through the array, add `consecutive` to `count` to account for the remaining subarrays, if applicable.\n4. Return `count` as the total count of alternating subarrays.\n\n# Complexity\n- Time complexity:\n - The algorithm traverses the array once, resulting in a time complexity of O(n), where n is the length of the input array `nums`.\n- Space complexity:\n - The space complexity is O(1) since the algorithm uses only a constant amount of extra space for variables such as `count`, `consecutive`, and `n`.\n\n# Code\n```java\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n int n = nums.length;\n long count = 0; // Total count of alternating subarrays\n int consecutive = 1; // Length of the current consecutive increasing or decreasing sequence\n \n for (int i = 1; i < n; i++) {\n if (nums[i] != nums[i - 1]) {\n count += consecutive; // Add consecutive to count\n consecutive++; // Increment consecutive for the new sequence\n } else {\n count += consecutive; // Add consecutive to count\n consecutive = 1; // Reset consecutive for the new sequence\n }\n }\n \n count += consecutive; // Add the remaining subarrays if applicable\n \n return count; // Return the total count of alternating subarrays\n }\n}\n```
1
0
['Array', 'Greedy', 'Sliding Window', 'Java']
0
count-alternating-subarrays
Javascript - Easy Solution
javascript-easy-solution-by-vigneshkvm-j3gp
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
Vigneshkvm
NORMAL
2024-03-31T04:11:15.639180+00:00
2024-03-31T04:11:15.639202+00:00
47
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countAlternatingSubarrays = function(nums) {\n let total = nums.length, count = 0;\n \n for(let i = 1; i < nums.length; i++) {\n if(nums[i - 1] !== nums[i]) count++;\n else {\n total = total + count * (count + 1) / 2;\n count = 0;\n }\n }\n \n total = total + count * (count + 1) / 2;\n return total;\n};\n```
1
0
['JavaScript']
0
count-alternating-subarrays
Rust/Python two pointers solution with explanation
rustpython-two-pointers-solution-with-ex-33ly
Intuition\n\nStandard two pointers solution. Have some value which tracks the previous number you have seen. Now move right pointer and check if the value you s
salvadordali
NORMAL
2024-03-31T04:09:31.593537+00:00
2024-03-31T04:09:31.593562+00:00
71
false
# Intuition\n\nStandard two pointers solution. Have some value which tracks the previous number you have seen. Now move right pointer and check if the value you see at this pointer is different from the previous seen. \n\nIf they are the same, you can\'t expand the interval and should update left pointer to right pointer. Update the previous value.\n\nAnd increase the result by `pos_r - pos_l + 1`\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn count_alternating_subarrays(nums: Vec<i32>) -> i64 {\n let (mut res, mut pos_l, mut prev_v) = (0, 0, -1);\n for pos_r in 0 .. nums.len() {\n if nums[pos_r] == prev_v {\n pos_l = pos_r;\n }\n prev_v = nums[pos_r];\n res += (pos_r - pos_l + 1) as i64;\n }\n return res;\n }\n}\n```\n```python []\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n res, pos_l, prev_c = 0, 0, -1\n for pos_r in range(len(nums)):\n if nums[pos_r] != prev_c:\n prev_c = nums[pos_r]\n else:\n pos_l = pos_r\n\n res += pos_r - pos_l + 1\n\n return res\n```
1
0
['Python', 'Rust']
0
count-alternating-subarrays
Optimised Solution
optimised-solution-by-sdkv-u7pz
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int
sdkv
NORMAL
2024-03-31T04:06:01.400049+00:00
2024-03-31T04:06:01.400079+00:00
0
false
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long c=0,s=1,i=1; \n while(i<nums.size())\n {\n if(nums[i]!=nums[i-1]) \n {\n s++;\n } \n else \n {\n c+=s*(s+1)/2;\n s=1; \n }\n i++;\n }\n c+=s*(s+1)/2;\n return\xA0c;\n }\n};\n```
1
0
['C++']
0
count-alternating-subarrays
💡0101... & 1010....
0101-1010-by-jainwinn-rzji
Approach\nFormed two arrays of size n of 0,1,0,1\u2026(say arr1) and 1,0,1,0\u2026.(say arr2).\nNow iterating i(0 to n), find the maximum subarray common betwee
JainWinn
NORMAL
2024-03-31T04:05:15.029480+00:00
2024-03-31T04:05:15.029502+00:00
44
false
# Approach\nFormed two arrays of size n of 0,1,0,1\u2026(say arr1) and 1,0,1,0\u2026.(say arr2).\nNow iterating i(0 to n), find the maximum subarray common between given array nums and arr1 and set i to end of this subarray. Keep adding len*(len+1)/2 for every such subarray length.\nSimilarly do this with arr2 and nums.\n\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n int n=nums.size();\n \n //forming 0,1,0,1....\n vector<int> a(n,0);\n int curr=0;\n for(int i=0 ; i<n ; i++){\n a[i]=curr;\n curr^=1;\n }\n \n //forming 1,0,1,0....\n vector<int> b(n,0);\n curr=1;\n for(int i=0 ; i<n ; i++){\n b[i]=curr;\n curr^=1;\n }\n \n //common subarrays for nums and a\n long long ans=0;\n for(long long i=0 ; i<n ; i++){\n long long j=i;\n while(i<n && nums[i]==a[i]){\n i++;\n }\n long long l=(i-j);\n ans+=(l*(l+1))/(long long)2;\n }\n \n //common subarrays for nums and b\n for(long long i=0 ; i<n ; i++){\n long long j=i;\n while(i<n && nums[i]==b[i]){\n i++;\n }\n long long l=(i-j);\n ans+=(l*(l+1))/(long long)2;\n }\n \n return ans;\n }\n};\n```
1
0
['C++']
0
count-alternating-subarrays
Java/Python Clean Solution
javapython-clean-solution-by-shree_govin-xwsz
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
Shree_Govind_Jee
NORMAL
2024-03-31T04:04:50.881823+00:00
2024-03-31T04:04:50.881846+00:00
316
false
# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count =0;\n int left = 0;\n for(int right = 0; right<nums.length; right++){\n if(right>0 && nums[right]==nums[right-1]){\n left = right;\n }\n count += right-left+1;\n }\n return count;\n }\n}\n```\n```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n count = 0\n left = 0\n for right in range(len(nums)):\n if right>0 and nums[right] == nums[right-1]:\n left = right\n \n count += right-left +1\n return count\n```
1
0
['Array', 'Two Pointers', 'Python', 'Java', 'Python3']
0
count-alternating-subarrays
Sliding (Destructive) Window
sliding-destructive-window-by-rajesh_sv-aiwi
Intuition\nWindow is broken when adjacent nums are not alternating. So set left of window to right.\n\n# Code\n\nclass Solution:\n def countAlternatingSubarr
rajesh_sv
NORMAL
2024-03-31T04:01:27.219755+00:00
2024-03-31T04:01:27.219788+00:00
16
false
# Intuition\nWindow is broken when adjacent nums are not alternating. So set left of window to right.\n\n# Code\n```\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n # Sliding (Destructive) Window\n # Time Complexity: O(n)\n # Space Complexity: O(n)\n ans, i = 1, 0\n for j in range(1, len(nums)):\n if nums[j] ^ 1 != nums[j-1]:\n i = j\n ans += j - i + 1\n return ans\n```
1
0
['Python3']
0
count-alternating-subarrays
LEETCODE CODESTORYWITHMIK SOLUTION
leetcode-codestorywithmik-solution-by-an-sng1
IntuitionApproachComplexity Time complexity: Space complexity: Code
anythingFORSQL
NORMAL
2025-04-09T09:43:15.642066+00:00
2025-04-09T09:43:15.642066+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: long long countAlternatingSubarrays(vector<int>& nums) { long long sum=1; long long count=1; int n=nums.size(); for(int i=1;i<n;i++){ if(nums[i]!=nums[i-1]){ count++; }else{ count=1; } sum+=count; } return sum; } }; ```
0
0
['C++']
0
count-alternating-subarrays
Counting pattern
counting-pattern-by-boiiboii-4i4f
IntuitionApproach Increase and reset to be changed when the condition is met. Complexity Time complexity: O(n) Space complexity: O(1)Code
boiiboii
NORMAL
2025-03-01T05:28:15.241401+00:00
2025-03-01T05:28:15.241401+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> - Increase and reset to be changed when the condition is met. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```cpp [] class Solution { public: long long countAlternatingSubarrays(vector<int>& nums) { // counting method long long result =1, size = 1; for(int i=1;i<nums.size();i++){ if(nums[i-1] != nums[i]){ size++; }else{ size =1; } result +=size; } return result; } }; ```
0
0
['C++']
0
count-alternating-subarrays
0ms Beats100.00% slide window
0ms-beats10000-slide-window-by-dinhson-n-iu42
IntuitionApproachComplexity Time complexity: O(n) Space complexity: Code
sondinh1701_
NORMAL
2025-02-17T04:15:47.215911+00:00
2025-02-17T04:15:47.215911+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: long long countAlternatingSubarrays(vector<int>& nums) { long long ans = 0; int n = nums.size(); int left = 0; for (int right = 0; right < n; right++) { if (right > 0 && nums[right] == nums[right - 1]) { left = right; } ans += (right - left + 1); } return ans; } }; ```
0
0
['C++']
0
count-alternating-subarrays
Best approach for beginners using Java
best-approach-for-beginners-using-java-b-2vl7
IntuitionThe problem requires counting all subarrays where adjacent elements alternate in value. A straightforward way to approach this is to traverse the array
ashu_okk
NORMAL
2025-02-11T13:03:31.353966+00:00
2025-02-11T13:03:31.353966+00:00
2
false
# Intuition The problem requires counting all subarrays where adjacent elements alternate in value. A straightforward way to approach this is to traverse the array and track contiguous alternating sequences. # Approach - Initialize `count` with `n` since each element itself is an alternating subarray. - Use a variable `length` to track the length of the current alternating sequence. - Traverse the array from the second element: - If the current element differs from the previous one, extend the sequence. - Otherwise, reset `length` to 1. - Accumulate `length - 1` to `count` at each step. # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(1)$$ # Code ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { int n = nums.length; long count = n; int length = 1; for (int i = 1; i < n; i++) { if (nums[i] != nums[i - 1]) { length++; } else { length = 1; } count += length - 1; } return count; } } ```
0
0
['Java']
0
count-alternating-subarrays
Explanation in English and Russian
explanation-in-english-and-russian-by-de-siye
ExplanationIn this problem, a pattern can be observed: If the array is fully alternating and has a length of 1, it has only 1 alternating subarray. If the lengt
saparov
NORMAL
2025-02-05T14:17:07.568260+00:00
2025-02-05T14:17:07.568260+00:00
2
false
# Explanation In this problem, a pattern can be observed: - If the array is fully alternating and has a length of 1, it has only 1 alternating subarray. - If the length of the array is 2, the number of such subarrays is 3. - If the length is 3 — 6 subarrays. - If the length is 4 — 10 subarrays, and so on. To find the number of alternating subarrays in a fully alternating array, it is enough to sum the numbers from 1 to 𝑛, where 𝑛 is its length. For example, if the given array is `nums = {0,1,0,1,0}` with a length of 5, then the number of alternating subarrays is: ``` 1 + 2 + 3 + 4 + 5 = 15. ``` However, some test cases contain non-fully alternating arrays. In this case, the array should be split at the points where the alternation is broken, and the number of alternating subarrays should be counted separately for each resulting segment. For example, in `nums = {0,1,0,1,1,0}`, the alternation is broken after the fourth element: Let's split the array: ``` nums1 = {0,1,0,1}, length 4 → 1 + 2 + 3 + 4 = 10 nums2 = {1,0}, length 2 → 1 + 2 = 3 ``` Total number of alternating subarrays: ``` 10 + 3 = 13. ``` # Объяснение В этой задаче можно заметить закономерность: - Если массив полностью чередующийся и имеет длину 1, то у него всего 1 чередующийся подмассив. - Если длина массива 2, то количество таких подмассивов равно 3. - Если длина 3 — 6 подмассивов. - Если длина 4 — 10 подмассивов и так далее. Чтобы найти количество чередующихся подмассивов в полностью чередующемся массиве, достаточно суммировать числа от 1 до **𝑛**, где **𝑛** — его длина. Например, если дан массив `nums = {0,1,0,1,0}` длиной 5, то количество чередующихся подмассивов: ``` 1 + 2 + 3 + 4 + 5 = 15. ``` Однако в тестах встречаются и не полностью чередующиеся массивы. В таком случае необходимо разделить массив в местах, где чередование нарушается, и отдельно подсчитать количество чередующихся подмассивов в каждом из полученных сегментов. Например, для `nums = {0,1,0,1,1,0}` чередование прерывается после четвертого элемента: Разделим массив: ``` nums1 = {0,1,0,1}, длина 4 → 1 + 2 + 3 + 4 = 10 nums2 = {1,0}, длина 2 → 1 + 2 = 3 ``` Общее количество чередующихся подмассивов: ``` 10 + 3 = 13. ``` # Code ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { long res = 1; int k = 1; for (int i = 0; i < nums.length - 1; i++) { if (nums[i] != nums[i + 1]) { res += ++k; } else { k = 0; res += ++k; } } return res; } } ```
0
0
['Java']
0
count-alternating-subarrays
O(1) space and O(n) time - DP Approach Java
o1-space-and-on-time-dp-approach-java-by-roj5
IntuitionApproachDp approach using two variablesComplexity Time complexity: O(n) Space complexity: O(1) Code
dhivya6613
NORMAL
2025-02-03T13:31:34.991535+00:00
2025-02-03T13:31:34.991535+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> Dp approach using two variables # 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 ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { int n = nums.length, incLength = 1; long maxLength = 1; for(int i=1; i<n; i++){ incLength = (nums[i-1]!=nums[i]) ? incLength+1 : 1; maxLength += incLength; } return maxLength; } } ```
0
0
['Dynamic Programming', 'Java']
0
count-alternating-subarrays
Intuition
intuition-by-fustigate-9c0z
Try working out a couple of custom examples on paper first.To start, consider 0101. Brute force it. How many alternating subarrays are there? Well, we can split
Fustigate
NORMAL
2025-01-22T23:57:28.255150+00:00
2025-01-22T23:57:28.255150+00:00
5
false
Try working out a couple of custom examples on paper first. To start, consider 0101. Brute force it. How many alternating subarrays are there? Well, we can split it into different groups of length 1, length 2, length 3, and length 4. Respectively, 4, 3, 2, 1 of each. Therefore the result will be 4 + 3 + 2 + 1. So, we can have an adding_factor, starting at 1, since every element by itself is a valid alternating subarray. When we move the index to the next element, check if it is different than the previous. If it is different, add 1 to the adding factor then add the adding factor to the final answer. When we encounter a same element again on the other hand, we can just reset the adding factor to one, since subarrays have to be contiguous and therefore when we encounter a same element we can just discard the lengths of the previous. ```python class Solution: def countAlternatingSubarrays(self, nums: List[int]) -> int: n = len(nums) i = 1 ans = 1 adding_factor = 1 while i < n: if nums[i] != nums[i - 1]: adding_factor += 1 else: adding_factor = 1 ans += adding_factor i += 1 return ans ```
0
0
['Greedy', 'Python3']
0
count-alternating-subarrays
Easy to understand: O(n) two pointer & cool math trick approach EXPLAINED
easy-to-understand-on-two-pointer-cool-m-6leh
IntuitionAt first, I utilized brute force to solve this problem, where I went through each of the subarrays and checked if they were valid, and if they were, I
rohanmahajan03
NORMAL
2025-01-19T13:12:16.398642+00:00
2025-01-19T13:12:16.398642+00:00
5
false
# Intuition At first, I utilized brute force to solve this problem, where I went through each of the subarrays and checked if they were valid, and if they were, I added them to my "res" variable, which represents result and is what is ultimately returned. However, while this approach worked in principle, it exceeded the alloted time restrictions for this problem. So, this got me thinking about the repeated work that was being done in the brute force solution: this repeated work occured when we have already established that a larger subarray is valid, and then we have to check if a subarray within that larger subarray is valid later. Obviously, that smaller subarray within the larger subarray will be valid due to the larger subarray being valid. To clarify, here is an example: larger valid subarray-- [1,0,1,0]. Smaller subarray-- [1,0,1]. It is clear that the smaller subarray is valid because we know alreday the larger subarray to be valid and the smaller subarray is entirely inside the larger subarray. With this understanding of the repeated work, I started to work on how I could solve this issue and ultimately came to the following solution. # Approach I started by establishing left and right pointers, and instead of iterating through and checking that each subarray was valid (like I did in the brute force solution), so long as a subarray continued to be valid, I continued to extend it by incrementing my right pointer. Finally, when the subarray was no longer valid, I would add (length of subarray)(length of subarray + 1) // 2 to my result. How did I come to this obscure formula? Well, it was through recognition of a very simple pattern that is better explained through example: Let's say we have a subarray [1], we know that there is only one subarray within that subarray, so we would have an output of one. Let's say we have a subarray [1,0]. We know that we would have one subarray of length 2 ([1,0]) and two subarrays of length 1 ([1], [0]), so the output for a subarray of length 2 would be 3. Let's say we have a subarray [1,0,1]. We know that we would have one subarray of length 3 ([1,0,1]), two subarrays of length 2 ([1,0], [0,1]), and three subarrays of legnth 1 ([1], [0], [1]), so for a subarray of length 3, our output would be 6. Following this relation, the mapping of input subarray sizes to their outputs is as follows: 1:1, 2:3, 3:6, 4:10, 5:15. Now that we have the outputs listed, we can notice the following patttern. input n*input n + 1 / 2 is the output for n. ie: (4 * 5 / 2 = 10). Now, we know that when we find the longest valid subarray starting from our left pointer, we can add to "res" all of the valid subarrays within it! # Complexity - Time complexity: O(n)-- iterating through the nums array once - Space complexity: O(1)-- res, l pointer, r pointer. # Code ```python3 [] class Solution: def countAlternatingSubarrays(self, nums: List[int]) -> int: res = 0 l = 0 r = l while l < len(nums): if l == r or (r < len(nums) and nums[r] != nums[r - 1]): r += 1 continue if r == len(nums) or nums[r] == nums[r - 1]: res += ((r - l + 1)*(r - l)) // 2 l = r return res ```
0
0
['Python3']
0
count-alternating-subarrays
Video Explanation Solution easy to understand | Programming with Pirai | Half Moon Coder.
video-explanation-solution-easy-to-under-s37p
Video : Code
Piraisudan_02
NORMAL
2025-01-05T07:42:13.793531+00:00
2025-01-05T07:42:13.793531+00:00
5
false
# Video : https://youtu.be/3Kb-DYfwinY # Code ```python3 [] class Solution: def countAlternatingSubarrays(self, nums: List[int]) -> int: res=c=1 for i in range(1,len(nums)): if nums[i]!=nums[i-1]: c+=1 else: c=1 res+=c return res ```
0
0
['Array', 'Math', 'Python3']
0
count-alternating-subarrays
Easy two line solution
easy-two-line-solution-by-nishantsharma0-p2uu
Intuitionif the current bit is alternate then it can contribute in each subarray so add the length of the current subarray.ApproachComplexity Time complexity: O
nishantsharma0611
NORMAL
2024-12-29T05:22:58.318871+00:00
2024-12-29T05:22:58.318871+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> if the current bit is alternate then it can contribute in each subarray so add the length of the current subarray. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { #define ll long long public: long long countAlternatingSubarrays(vector<int>& nums) { vector<ll>dp(nums.size()); ll sum=1; dp[0]=1; for(int i=1;i<nums.size();i++){ if(nums[i]^nums[i-1]==1)dp[i]=dp[i-1]+1; else dp[i]=1; sum+=dp[i]; } return sum; } }; ```
0
0
['C++']
0
count-alternating-subarrays
very easy beginner friendly solution using common sense
very-easy-beginner-friendly-solution-usi-b0h7
IntuitionApproachComplexity Time complexity: Space complexity: Code
tanish67
NORMAL
2024-12-24T14:45:22.648713+00:00
2024-12-24T14:45:22.648713+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { int j=1; long count =0; long ans=0; for(int i=0;i<nums.length-1;i++){ if(nums[j]==nums[i]){ ans+= count*(count+1)/2; count=0; } else{ count++; } j++; } if(count>0){ ans+= count*(count+1)/2; } return ans+nums.length; } } ```
0
0
['Java']
0
count-alternating-subarrays
O(n) java
on-java-by-vamseedhar8680-qnwy
IntuitionSo for each index if the prev char matches current char subarray count of that element is i+1. if it doesnt match subarray count of cur element is set
Vamseedhar8680
NORMAL
2024-12-24T11:37:41.525007+00:00
2024-12-24T11:37:41.525007+00:00
0
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> So for each index if the prev char matches current char subarray count of that element is i+1. if it doesnt match subarray count of cur element is set to be 1 as it forms new subarray. # Approach <!-- Describe your approach to solving the problem. --> So if there is test case like 101011010 since two 1's are repeating we need to have subarray count of last element set to be subarray count from idx 5 to last element idx which is 8-5+1; So to find idx of prev repeating elemnt we need to declare elemnt last variable and store idx for each and every repeating elemnt and using last element idx we need to calculate subarray count which is i-last+1; total of all subarrays is result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { long tot=1; /* if(nums.length==100000&&nums[0]==1&&nums[1]==0&&nums[2]==0&&nums[3]==1) { tot=5000050000L; return tot; }*/ System.out.println("jj "+nums.length); int f[]=new int[nums.length]; int alt[]=new int[nums.length]; f[0]=1; int last=-1; // long tot=1; alt[0]=1; for(int i=1;i<nums.length;i++) { if(nums[i]!=nums[i-1]) { System.out.println("idx"+i); int j=i-1; /* while(j>=0&&alt[j]==0) { j--; } if(j!=0) { f[i]=i-j+1; tot+=f[i]; } else if(j==0) { f[i]=i+1; tot+=f[i]; }*/ if(last>-1) { f[i]=i-last+1; tot+=f[i]; } else{ f[i]=i+1; tot+=f[i]; } } else{ alt[i]=1; last=i; tot+=1; } } return tot; } } ```
0
0
['Array', 'Math', 'Java']
0
count-alternating-subarrays
O(n) java
on-java-by-vamseedhar8680-2jpq
IntuitionSo for each index if the prev char matches current char subarray count of that element is i+1. if it doesnt match subarray count of cur element is set
Vamseedhar8680
NORMAL
2024-12-24T11:37:37.951320+00:00
2024-12-24T11:37:37.951320+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> So for each index if the prev char matches current char subarray count of that element is i+1. if it doesnt match subarray count of cur element is set to be 1 as it forms new subarray. # Approach <!-- Describe your approach to solving the problem. --> So if there is test case like 101011010 since two 1's are repeating we need to have subarray count of last element set to be subarray count from idx 5 to last element idx which is 8-5+1; So to find idx of prev repeating elemnt we need to declare elemnt last variable and store idx for each and every repeating elemnt and using last element idx we need to calculate subarray count which is i-last+1; total of all subarrays is result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```java [] class Solution { public long countAlternatingSubarrays(int[] nums) { long tot=1; /* if(nums.length==100000&&nums[0]==1&&nums[1]==0&&nums[2]==0&&nums[3]==1) { tot=5000050000L; return tot; }*/ System.out.println("jj "+nums.length); int f[]=new int[nums.length]; int alt[]=new int[nums.length]; f[0]=1; int last=-1; // long tot=1; alt[0]=1; for(int i=1;i<nums.length;i++) { if(nums[i]!=nums[i-1]) { System.out.println("idx"+i); int j=i-1; /* while(j>=0&&alt[j]==0) { j--; } if(j!=0) { f[i]=i-j+1; tot+=f[i]; } else if(j==0) { f[i]=i+1; tot+=f[i]; }*/ if(last>-1) { f[i]=i-last+1; tot+=f[i]; } else{ f[i]=i+1; tot+=f[i]; } } else{ alt[i]=1; last=i; tot+=1; } } return tot; } } ```
0
0
['Array', 'Math', 'Java']
0
count-alternating-subarrays
Easy Python Solution
easy-python-solution-by-sb012-gbvo
Code
sb012
NORMAL
2024-12-18T05:15:37.088982+00:00
2024-12-18T05:18:03.452954+00:00
5
false
# Code\n```python3 []\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n left = right = 0\n answer = 0\n\n while right < len(nums):\n answer += right - left + 1\n right += 1\n\n if right < len(nums) and nums[right] == nums[right - 1]:\n left = right\n \n return answer\n```
0
0
['Python3']
0
count-alternating-subarrays
easy solution using java check it out || <<AWSZOABI>>
easy-solution-using-java-check-it-out-aw-ya7r
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
AWSZ
NORMAL
2024-11-20T23:54:41.968227+00:00
2024-11-20T23:54:41.968250+00:00
0
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```java []\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count = 0; // Initialize count\n \n if (nums.length == 0) {\n return count; // Return 0 for empty array\n }\n\n count += nums.length; // Each element forms a subarray of length 1\n int[] helper = new int[nums.length]; // Helper array to store alternating counts\n\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] != nums[i - 1]) {\n helper[i] = helper[i - 1] + 1; // Extend alternating subarray\n }\n count += helper[i]; // Add to total count\n }\n\n return count; // Return the total count\n }\n}\n\n```
0
0
['Java']
0
count-alternating-subarrays
3101. Count Alternating Subarrays
3101-count-alternating-subarrays-by-kuma-4gcb
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
KumarDev2003
NORMAL
2024-11-20T19:25:42.645760+00:00
2024-11-20T19:25:42.645793+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long cnt = 0;\n int i = 0;\n int n = nums.size();\n int j = 0;\n while(i < n){\n j = i;\n while(j<n-1 && nums[j] != nums[j+1]) j++;\n long long num = j+1-i;\n num = (long long) num * (num+1)/2;\n cnt += num;\n i = j+1;\n }\n return cnt;\n }\n};\n```
0
0
['C++']
0
count-alternating-subarrays
Beats 92.68% Python.
beats-9268-python-by-anthonybaston101-lje9
Intuition\n Describe your first thoughts on how to solve this problem. \n\nImagine creating a boolean array of length n - 1, where the $i^{th}$ element is False
anthonybaston101
NORMAL
2024-11-20T15:45:40.288742+00:00
2024-11-20T15:45:40.288845+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nImagine creating a boolean array of length n - 1, where the $i^{th}$ element is `False` if `nums[i] != nums[i + 1]` and otherwise `True`. \n\nWe can map any subarray of nums to this new boolean array. If such a subarray (when mapped) contains at least one `True` value, then it is not a valid subarray. Therefore subarrays are valid if and only if their mapped subarray of boolean values only contains `False` values.\n\ne.g. \n`[0, 1, 1, 1] -> [False, True, True]`\n`[1, 0, 1, 0] -> [False, False, False]`\n\nSuppose we find a subarray, and map it to this boolean subarray, such that it only contains the value `False` and either side in the boolean array we find the values `True` bounding this subarray. \n\nSo we have the maximum-sized valid subarray as bounded by the `True` values. \n\nIf this is length $p$ (i.e. there are $p$ `False` values in the subarray) then there are $p + 1$ different alternating values in the equivalent subarray of the original array (that maps to this boolean subarrary).\n\nFollowing this there are $T_{p + 1} = p (p + 1) / 2$ valid subarrays in this array, where $T_j$ is the $j^{th}$ triangular number. To see this, think about the number of different ways a window of size $s \\le p + 1$ can be positioned in the subarray of size $p + 1$.\n\nAnswer: $(p + 1) - (s - 1)$, and $s$ can take the value from $1$ to $p + 1$: \n\ni.e. $p + 1, p, p - 1, ..., 1$ \n\nand then we need to sum these up to get \n\n$p * (p + 1) / 2$.\n\nSo we find all the max-size boolean subarrays containing only `False` values and bounded by `True` (or the edges of the boolean subarray) and get their length: $p_j$ for each $j$ in $m$, where $m$ is the number of subarrays.\n\nThen we simply compute $\\sum_{j}^m T_{p_{j} + 1} = \\sum_{j}^{m} p_{j} * (p_j + 1) / 2$.\n\nSince no two subarrays are contiguous (otherwise they would merge into a larger subarray) we can compute each $T_{p_{j} + 1}$ value on the fly whilst iterating through our list and reset the size of a subarray once we reach its end. \n\nThe $p_{j}$ values are captured by the `adjacent` variable in the code below. We don\'t actually form the boolean subarray (this would be $O(n)$ memory) but do so implicity with the check `val == nums[i + 1]`.\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n \n total = len(nums)\n adjacent = 0\n for i, val in enumerate(nums[:-1]):\n \n if val == nums[i + 1]: \n total += adjacent * (adjacent + 1) // 2\n adjacent = 0\n else:\n adjacent += 1\n \n total += adjacent * (adjacent + 1) // 2\n \n return total\n\n\n```
0
0
['Python3']
0
count-alternating-subarrays
3101. Count Alternating Subarrays
3101-count-alternating-subarrays-by-pgmr-c8el
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
pgmreddy
NORMAL
2024-11-03T08:05:50.944401+00:00
2024-11-03T08:05:50.944421+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nvar countAlternatingSubarrays = function (a) {\n\tconst n = a.length;\n\tlet alternatingSubarrayCount = 1;\n\tlet sum = alternatingSubarrayCount;\n\tfor (let i = 1; i < n; i++) {\n\t\tif (a[i - 1] !== a[i]) {\n\t\t\talternatingSubarrayCount += 1;\n\t\t} else {\n\t\t\talternatingSubarrayCount = 1;\n\t\t}\n\t\tsum += alternatingSubarrayCount;\n\t}\n\treturn sum;\n};\n\n```
0
0
['JavaScript']
0
count-alternating-subarrays
[Java] ✅ 3MS ✅ 100% ✅ SLIDING WINDOW ✅ FASTEST ✅ BEST
java-3ms-100-sliding-window-fastest-best-gjot
Approach\n1. Expand a window (left, right) while char[right] != char[right + 1]\n2. Inside this valid window you have n * (n+1) /2 substrings. (1 + right - left
StefanelStan
NORMAL
2024-11-01T01:33:15.659083+00:00
2024-11-01T01:33:15.659110+00:00
10
false
# Approach\n1. Expand a window (left, right) while char[right] != char[right + 1]\n2. Inside this valid window you have n * (n+1) /2 substrings. (1 + right - left)\n3. Adjust left and right to right +1 (window starts at next position where right stopped)\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long count = 0L;\n int left = 0, right = 0;\n while (left < nums.length) {\n while (right < nums.length - 1 && nums[right] != nums[right + 1]) {\n right++;\n }\n count += (long)(1 + right - left) * (2 + right - left) / 2;\n left = ++right;\n }\n return count;\n }\n}\n```
0
0
['Sliding Window', 'Java']
0
count-alternating-subarrays
Python: one for() loop
python-one-for-loop-by-alexc2024-d5ez
\n# Complexity\nBeats 100% (time)\n\n\n\n# Code\npython []\nclass Solution(object):\n\n def countAlternatingSubarrays(self, nums):\n """\n :typ
AlexC2024
NORMAL
2024-10-24T17:10:44.887606+00:00
2024-10-24T17:10:44.887640+00:00
2
false
\n# Complexity\nBeats 100% (time)\n\n\n\n# Code\n```python []\nclass Solution(object):\n\n def countAlternatingSubarrays(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n count = 0\n alt_length = 1\n for i in range(1, len(nums)):\n if nums[i]!=nums[i-1]:\n alt_length+=1\n else:\n count+=(alt_length*(alt_length+1)/2)\n alt_length = 1\n count+=(alt_length*(alt_length+1)/2)\n return count\n```
0
0
['Python']
0
count-alternating-subarrays
Python3 solution with two pointers
python3-solution-with-two-pointers-by-yu-w11o
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
yukikitayama
NORMAL
2024-10-21T12:40:37.504520+00:00
2024-10-21T12:40:37.504545+00:00
2
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```python3 []\n"""\nTwo pointers\nnums = [1,0,1,0]\nexp: 10\n 1 + (1 + 1) + (1 + 1 + 1) + (1 + 1 + 1 +) = 1 + 2 + 3 + 4 = 10\n"""\n\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n """T: O(N)"""\n\n ans = 0\n left = 0\n\n for right in range(len(nums)):\n \n if nums[right] == nums[right - 1]:\n left = right\n\n ans += (right - left + 1)\n\n return ans\n\n def countAlternatingSubarrays1(self, nums: List[int]) -> int:\n """T: O(N^2)"""\n ans = 0\n\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n if i == j:\n ans += 1\n\n else:\n if nums[j] != nums[j - 1]:\n ans += 1\n else:\n break\n\n return ans\n```
0
0
['Python3']
0
count-alternating-subarrays
JAVA easiest O(N) solution - sliding window approach
java-easiest-on-solution-sliding-window-gsi40
Approach\nJust apply the sliding window approach, change the initial pointer to new when a repeated digit is found. Focus on the fact that it is a binary array.
blisss
NORMAL
2024-10-10T23:02:17.761077+00:00
2024-10-10T23:02:17.761111+00:00
0
false
# Approach\nJust apply the sliding window approach, change the initial pointer to new when a repeated digit is found. Focus on the fact that it is a binary array. \nUse mathematical formula to calculate number of possible subsets.\n# Complexity\n- Time complexity: $$O(n)$$ \n\n# Code\n```java []\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long ans=1;\n int j=0;\n for(int i=1;i<nums.length;i++){\n if(nums[i-1]==nums[i]){\n j=i;\n }\n ans+=(long)(i-j+1);\n }\n return ans;\n }\n}\n```
0
0
['Java']
0
count-alternating-subarrays
Add the arithmetic sum of the length of each alternating array
add-the-arithmetic-sum-of-the-length-of-4ckq5
Approach\nThe number of subarrays of any given array can be found by calculating the arithmethic sum of the length of that array (0 + 1 + 2 + 3 ... + n - 1 + n)
bldrnnr0x7ca
NORMAL
2024-10-10T18:10:14.166895+00:00
2024-10-10T18:10:14.166919+00:00
0
false
# Approach\nThe number of subarrays of any given array can be found by calculating the arithmethic sum of the length of that array (0 + 1 + 2 + 3 ... + n - 1 + n), where n is the length of the subarray of alternating numbers.\n\nE.g. the number of subarrays of an array of length 4 = 4 + 3 + 2 + 1 = 10.\n\nSimply calculate the arithmetic sum of each length in which all elements are alternating for that given window.\n\nE.g.:\n[0,1,1,1]\n[0]: length of alternating elements subarray is 1\n[0,1]: length of alternating elements subarray is 2\n[0,1,1]: curr element = prev element. add arithmetic sum of 2 to the res. Length of alternating elements subarray is 1.\n[0,1,1,1]: curr element = prev element. add arithmetic sum of 1 to the res. Length of alternating elements subarray is 1.\n\nAdd arithmetic sum of final length of alternating elements subarray 1 to the res.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```python3 []\nclass Solution:\n def countAlternatingSubarrays(self, nums: List[int]) -> int:\n # use mathematical formula subarrays = n * (n +1) // 2\n curr_alternating_length = 0\n res = 0\n\n def arithmetic_sum(x):\n return x*(x+1)//2\n\n for i, num in enumerate(nums):\n if i > 0 and num != nums[i-1]:\n curr_alternating_length += 1\n else:\n res += arithmetic_sum(curr_alternating_length)\n curr_alternating_length = 1\n\n return res + arithmetic_sum(curr_alternating_length)\n\n```
0
0
['Python3']
0
count-alternating-subarrays
Brute Completion Challenge #4 (no analysis)
brute-completion-challenge-4-no-analysis-meuq
Code\nruby []\n# @param {Integer[]} nums\n# @return {Integer}\ndef count_alternating_subarrays(nums)\n # every length 1 subarray is alternating:\n l = num
ifiht
NORMAL
2024-10-05T20:44:53.321025+00:00
2024-10-05T20:44:53.321063+00:00
0
false
# Code\n```ruby []\n# @param {Integer[]} nums\n# @return {Integer}\ndef count_alternating_subarrays(nums)\n # every length 1 subarray is alternating:\n l = nums.length\n # all length = 1 subarrays are valid\n altsubs = l\n # start with a length = 2 subarray\n ic = 1\n is = 0\n # there is no current longest valid subarray\n curr_longest_sub = []\n # iterate thru all possible LONGEST arrays, we can compute how many\n # subarrays each conatains with a simple equation\n while ic < l\n # since we jump bad subarrays, we only ever need to check\n # the last two values\n if nums[ic] != nums[ic - 1]\n curr_longest_sub = nums[is..ic]\n ic += 1\n #puts "replacing subarray #{subarr.inspect}"\n else\n # jump over the bad subarray\n is = ic\n ic += 1\n len = curr_longest_sub.length\n # the number of valid length == 2 subarrays in any array of length\n # >= 2 is given by the equation below:\n altsubs += (((len - 1) * len)/2)\n curr_longest_sub = []\n end\n end\n # check if there was still a valid sub when the\n # while loop reached the end\n if not curr_longest_sub.empty?\n len = curr_longest_sub.length\n remainder = (((len - 1) * len)/2)\n altsubs += remainder\n end\n return altsubs\nend\n```
0
0
['Ruby']
0
count-alternating-subarrays
Best Easy Soln
best-easy-soln-by-_rahul123-806c
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
_Rahul123
NORMAL
2024-09-19T05:33:23.231609+00:00
2024-09-19T05:33:23.231646+00:00
1
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)\n\n\n- Space complexity: O(1)\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long count = 0;\n\n int n = nums.size();\n\n for(int i =0; i < n; i++){\n int j =i;\n\n while(j+1 < n && nums[j] != nums[j+1]){ // Alternating\n j++;\n } \n\n int len = j - i + 1;\n\n count += (long long) len*(len+1)/2;\n\n i = j;\n\n }\n // T.C -> O(n)\n //S.C -> O(1)\n return count;\n }\n};\n```
0
0
['C++']
0
count-alternating-subarrays
C++ Solution || Easy to Understand
c-solution-easy-to-understand-by-pardhav-6gfg
Code\ncpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n if (nums.size() == 1) return 1;\n long lon
Pardhav_081911
NORMAL
2024-09-12T18:18:03.114615+00:00
2024-09-12T18:18:03.114636+00:00
1
false
# Code\n```cpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n if (nums.size() == 1) return 1;\n long long count = nums.size();\n long long len =0;\n for (long long i = 1; i < nums.size(); i++) {\n if (nums[i] != nums[i - 1]) {\n len++;;\n } else {\n count+= (len)*(len+1)/2;\n len=0;\n }if(i==nums.size()-1) count+=(len)*(len+1)/2;\n }\n return count;\n }\n};\n\n```
0
0
['C++']
0
count-alternating-subarrays
Easy C++ Solution
easy-c-solution-by-022_ankit-loku
```\nlong long countAlternatingSubarrays(vector& nums) {\n long long ans=0;\n int n=nums.size();\n int i=0,j=0;\n while(j0&&nums[j]!
022_ankit
NORMAL
2024-09-01T14:14:15.355172+00:00
2024-09-01T14:14:15.355209+00:00
0
false
```\nlong long countAlternatingSubarrays(vector<int>& nums) {\n long long ans=0;\n int n=nums.size();\n int i=0,j=0;\n while(j<n)\n {\n if(i==j||(j>0&&nums[j]!=nums[j-1]))\n {\n ans+=(j-i+1);\n j++;\n }\n else \n {\n i=j;\n }\n }\n return ans;\n }
0
0
[]
0
count-alternating-subarrays
[Accepted] Swift
accepted-swift-by-vasilisiniak-uodx
\nclass Solution {\n func countAlternatingSubarrays(_ nums: [Int]) -> Int {\n\n var dp = Array(repeating: 1, count: nums.count)\n\n for i in 1.
vasilisiniak
NORMAL
2024-08-31T21:27:13.130639+00:00
2024-08-31T21:27:13.130664+00:00
4
false
```\nclass Solution {\n func countAlternatingSubarrays(_ nums: [Int]) -> Int {\n\n var dp = Array(repeating: 1, count: nums.count)\n\n for i in 1..<nums.count\n where nums[i] != nums[i - 1] {\n dp[i] += dp[i - 1]\n }\n \n return dp.reduce(0, +)\n }\n}\n```
0
0
['Swift']
0
count-alternating-subarrays
O(N)
on-by-p_patel_12-pxwf
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
P_patel_12
NORMAL
2024-08-31T12:55:40.187789+00:00
2024-08-31T12:55:40.187873+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define ll long long\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) {\n long long int ans = 0;\n int n = nums.size();\n long long int cnt = 1;\n for (int i = 1; i < n; i++) {\n if (nums[i] != nums[i - 1]) {\n cnt++;\n } else {\n ans = ans + (cnt * (cnt + 1)) / 2;\n cnt = 1;\n }\n }\n ans = ans + (cnt * (cnt + 1)) / 2;\n return ans;\n }\n};\n```
0
0
['C++']
0
count-alternating-subarrays
Scala two pointer stuff with recursion
scala-two-pointer-stuff-with-recursion-b-kl8p
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
MaxPsm
NORMAL
2024-08-28T16:55:38.943665+00:00
2024-08-28T16:55:38.943702+00:00
0
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```scala []\nobject Solution {\n def countAlternatingSubarrays(nums: Array[Int]): Long = {\n def go(currentSubArrayLength: Int, prevElem: Int, x: Int, y: Int, nums: Array[Int], count: Long): Long = {\n if (y == nums.length - 1) {\n if (nums(y) != prevElem) count + calculateSubArrays(currentSubArrayLength + 1)\n else if (currentSubArrayLength > 1) count + calculateSubArrays(currentSubArrayLength)\n else count\n }\n else (prevElem, y) match {\n case (p, ind) if nums(ind) != p => go(currentSubArrayLength + 1, nums(ind), x, y + 1, nums, count)\n case (p, ind) if nums(ind) == p => go(1, nums(ind), y, y + 1, nums, count + calculateSubArrays(currentSubArrayLength))\n }\n }\n\n def calculateSubArrays(length: Int): Long = length.toLong * (length.toLong - 1) / 2\n\n if (nums.length == 1) 1L\n else go(1, nums(0), 0, 1, nums, nums.length)\n \n }\n}\n```
0
0
['Scala']
0
count-alternating-subarrays
Very Easy Java solution 🔥 Beats 97 % of Java Users .
very-easy-java-solution-beats-97-of-java-zsxh
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
zzzz9
NORMAL
2024-08-26T23:49:32.743235+00:00
2024-08-26T23:49:32.743254+00:00
3
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```java []\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long rs = 0 ; \n int n = nums.length ; \n long curr = 0 ; \n for(int i=0 ; i<n ; ++i ){\n curr++ ; \n while( i+1<n && (nums[i] ^ nums[i+1] ) == 1 ){\n curr++ ;\n i++ ;\n \n }\n rs += curr*(curr+1)/2 ;\n curr = 0 ;\n }\n return rs ;\n }\n}\n```
0
0
['Java']
0
count-alternating-subarrays
Recursion, without memoization Beats 6.15%
recursion-without-memoization-beats-615-d9j0i
Approach\nI started from Top down DP, but it tuns out solution without memoization accepted.\nwe\'re not actually counting subarrays, we can instead use the ar
remedydev
NORMAL
2024-08-22T08:13:38.946887+00:00
2024-08-22T08:13:38.946915+00:00
4
false
# Approach\nI started from Top down DP, but it tuns out solution without memoization accepted.\nwe\'re not actually counting subarrays, we can instead use the arithmetic progression formula 1+2+3+4+\u2026, which gives us the number of subarrays within the start and end indexes. Please refer to the comments in the code for more details.\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```javascript []\nvar countAlternatingSubarrays = function(nums) {\n \n const dfs=(start, i)=>{\n if(i===nums.length) return 0;\n\n let ans=0;\n if(i>0 && nums[i-1]!==nums[i]){\n // extending a widow\n // (i-start+1) - add all subarrays within a range, \n // e.g 1,0,1,0,1 = 1+2+3+4+5\n ans+=dfs(start,i+1)+(i-start+1);\n }else{\n // if we can not extend, start new window\n ans+=dfs(i,i+1)+1;\n }\n\n return ans;\n }\n\n return dfs(0,0);\n};\n```
0
0
['JavaScript']
0
count-alternating-subarrays
NNN solution with O(n)
nnn-solution-with-on-by-hokhacnhat-72ri
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
hokhacnhat
NORMAL
2024-08-21T12:55:17.494827+00:00
2024-08-21T12:55:17.494862+00:00
0
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```java []\nclass Solution {\n public long countAlternatingSubarrays(int[] nums) {\n long ans = 0;\n int j = 0;\n for(int i = 1 ;i < nums.length;i++){\n if(nums[i] != nums[i - 1])\n ans += i - j;\n else\n j = i;\n }\n return ans + nums.length;\n }\n}\n```
0
0
['Java']
0
count-alternating-subarrays
Easy CPP Solution
easy-cpp-solution-by-clary_shadowhunters-v81d
\n\n# Code\ncpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) \n {\n long long ans=1;\n long lo
Clary_ShadowHunters
NORMAL
2024-08-20T11:32:18.556150+00:00
2024-08-20T11:32:18.556180+00:00
0
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long countAlternatingSubarrays(vector<int>& nums) \n {\n long long ans=1;\n long long j=0;\n for (long long i=1;i<nums.size();i++)\n {\n if (nums[i]==nums[i-1]) j=i;\n ans+=(i-j+1);\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
distribute-candies
Python, Straightforward with Explanation
python-straightforward-with-explanation-0quw1
There are len(set(candies)) unique candies, and the sister picks only len(candies) / 2 of them, so she can't have more than this amount.\n\nFor example, if ther
awice
NORMAL
2017-05-07T03:08:19.236000+00:00
2018-10-22T14:57:33.713195+00:00
15,101
false
There are ```len(set(candies))``` unique candies, and the sister picks only ```len(candies) / 2``` of them, so she can't have more than this amount.\n\nFor example, if there are 5 unique candies, then if she is picking 4 candies, she will take 4 unique ones. If she is picking 7 candies, then she will only take 5 unique ones.\n\n```\ndef distributeCandies(self, candies):\n return min(len(candies) / 2, len(set(candies)))\n```
128
1
[]
24
distribute-candies
C++ 1-liner
c-1-liner-by-votrubac-hqgj
\nint distributeCandies(vector<int>& c) {\n return min(unordered_set<int>(begin(c), end(c)).size(), c.size() / 2);\n}\n
votrubac
NORMAL
2017-05-07T06:12:53.451000+00:00
2018-08-22T06:08:35.854166+00:00
5,869
false
```\nint distributeCandies(vector<int>& c) {\n return min(unordered_set<int>(begin(c), end(c)).size(), c.size() / 2);\n}\n```
77
6
[]
12
distribute-candies
Java Solution, 3 lines, HashSet
java-solution-3-lines-hashset-by-shawnga-uc0a
Thanks @wmcalyj , modified to use HashSet.\n\npublic class Solution {\n public int distributeCandies(int[] candies) {\n Set<Integer> kinds = new HashS
shawngao
NORMAL
2017-05-07T03:06:23.108000+00:00
2018-08-15T07:32:04.362135+00:00
19,955
false
Thanks @wmcalyj , modified to use HashSet.\n```\npublic class Solution {\n public int distributeCandies(int[] candies) {\n Set<Integer> kinds = new HashSet<>();\n for (int candy : candies) kinds.add(candy);\n return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size();\n }\n}\n```
65
2
[]
16
distribute-candies
C++, bitset, beats 99.60%
c-bitset-beats-9960-by-zestypanda-4az5
The idea is to use biset as hash table instead of unordered_set.\n\nint distributeCandies(vector<int>& candies) {\n bitset<200001> hash;\n int cou
zestypanda
NORMAL
2017-05-11T23:08:48.849000+00:00
2017-05-11T23:08:48.849000+00:00
6,863
false
The idea is to use biset as hash table instead of unordered_set.\n```\nint distributeCandies(vector<int>& candies) {\n bitset<200001> hash;\n int count = 0;\n for (int i : candies) {\n if (!hash.test(i+100000)) {\n count++;\n hash.set(i+100000);\n }\n }\n int n = candies.size();\n return min(count, n/2);\n }\n```
41
0
[]
8
distribute-candies
1-line JavaScript O(n) solution using Set
1-line-javascript-on-solution-using-set-i32gu
\nvar distributeCandies = function(candies) {\n return Math.min(new Set(candies).size, candies.length / 2);\n};\n
loctn
NORMAL
2017-05-07T03:41:50.429000+00:00
2017-05-07T03:41:50.429000+00:00
2,970
false
```\nvar distributeCandies = function(candies) {\n return Math.min(new Set(candies).size, candies.length / 2);\n};\n```
33
1
['JavaScript']
2
distribute-candies
[C++] Clean Code - 2 Solutions: Set and Sort
c-clean-code-2-solutions-set-and-sort-by-ko2c
Set - O(N) time, O(N) space\nWe can use a set to count all unique kinds of candies, but even all candies are unique, the sister cannot get more than half.\n(Eve
alexander
NORMAL
2017-05-07T03:04:45.684000+00:00
2018-10-02T04:06:17.748514+00:00
7,075
false
**Set - O(N) time, O(N) space**\nWe can use a set to count all unique kinds of candies, but even all candies are unique, the sister cannot get more than half.\n(Even though in reality my GF would always get more than half.)\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n unordered_set<int> kinds;\n for (int kind : candies) {\n kinds.insert(kind);\n }\n return min(kinds.size(), candies.size() / 2);\n }\n};\n```\nUsing range constructor as @i_square suggested:\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n return min(unordered_set<int>(candies.begin(), candies.end()).size(), candies.size() / 2);\n }\n};\n```\n**Sort - O(N logN) time, O(1) space**\nOr we can sort the candies by kinds, count kind if different than the prevous:\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n size_t kinds = 0;\n sort(candies.begin(), candies.end());\n for (int i = 0; i < candies.size(); i++) {\n kinds += i == 0 || candies[i] != candies[i - 1];\n }\n return min(kinds, candies.size() / 2);\n }\n};\n```\nThe counter can start from 1 since there is no test case for empty input:\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n size_t kinds = 1;\n sort(candies.begin(), candies.end());\n for (int i = 0; i < candies.size(); i++) {\n kinds += candies[i] != candies[i - 1];\n }\n return min(kinds, candies.size() / 2);\n }\n};\n```
29
1
[]
6
distribute-candies
[Java] 3 codes. Beats 100%
java-3-codes-beats-100-by-shk10-iuh5
Solution is to choose as many unique candy types as we can without exceeding the hard limit of n / 2 so the problem reduces to counting how many distinct candy
shk10
NORMAL
2021-03-01T09:08:39.606126+00:00
2021-03-01T09:08:39.606164+00:00
2,802
false
Solution is to choose as many unique candy types as we can without exceeding the hard limit of n / 2 so the problem reduces to counting how many distinct candy types are there.\n\n**Approach 1: HashSet**\nMost obvious and versatile choice for our use case is to use a HashSet.\n\n```\n// 33 ms. 62%\npublic int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet<>();\n for(int candy: candyType) {\n set.add(candy);\n }\n return Math.min(candyType.length / 2, set.size());\n}\n```\n\n**Approach 2: Boolean array**\nLeveraging on input limits, we can use a boolean array to achieve better runtime.\n\n```\n// 3 ms. 100%\npublic int distributeCandies(int[] candyType) {\n boolean[] type = new boolean[200001];\n int count = 0, max = candyType.length / 2;\n for(int candy: candyType) {\n int t = candy + 100000;\n if(!type[t]) {\n if(++count == max) return max;\n type[t] = true;\n }\n }\n return count;\n}\n```\n\n**Approach 3: BitSet**\nWe can alternatively use a bitset if we\'d like to optimize space.\n\n```\n// 6 ms. 98.66%\npublic int distributeCandies(int[] candyType) {\n BitSet bits = new BitSet(200001);\n int count = 0, max = candyType.length / 2;\n for(int candy: candyType) {\n int t = candy + 100000;\n if(!bits.get(t)) {\n if(++count == max) return max;\n bits.set(t);\n }\n }\n return count;\n}\n```
26
1
['Java']
3
distribute-candies
[Python] Oneliner, explained
python-oneliner-explained-by-dbabichev-4dny
Alice needs to eat exactly n//2 candies and the question is how many types she can eat. There are two restrictions we have here:\n\n1. len(Counter(candies)) is
dbabichev
NORMAL
2021-03-01T08:31:27.925328+00:00
2021-03-01T08:31:27.925369+00:00
1,242
false
Alice needs to eat exactly `n//2` candies and the question is how many types she can eat. There are two restrictions we have here:\n\n1. `len(Counter(candies))` is how many candies type we have at all, and we can not eat more than this number types of candies.\n2. `len(candies)//2` is exaclty how many candies Alice must eat, so we can not eat more than this number (she can eat less and then eat any other candies to have exactly the half).\n\nNotice also, that these two conditions are **sufficient and enough**: strategy is the following: first eat one candy of each type until it is possible and then if we have eaten less than half, eat any candies to make it half.\n\n**Complexity**: time complexity is `O(n)`, where `n` is total number of candies, space complexity is also `O(n)`.\n\n```\nclass Solution:\n def distributeCandies(self, candies):\n return min(len(candies)//2, len(Counter(candies)))\n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**
18
5
[]
3
distribute-candies
C++ TWO-LINES-ONLY! SUPER Simple Solution
c-two-lines-only-super-simple-solution-b-jl8p
\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n
yehudisk
NORMAL
2021-03-01T08:22:09.166821+00:00
2021-03-01T08:22:09.168044+00:00
1,430
false
```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n return types_num > candies.size()/2 ? candies.size()/2 : types_num;\n }\n};\n```\n**LIKE IT? PLEASE UPVOTE...**
15
7
['C']
1
distribute-candies
Python | Easy Solution✅
python-easy-solution-by-gmanayath-b7x3
\ndef distributeCandies(self, candyType: List[int]) -> int:\n # half length of candyType list\n candy_len = int(len(candyType)/2)\n # no of
gmanayath
NORMAL
2022-08-09T14:36:20.943802+00:00
2022-12-22T16:51:14.269675+00:00
1,458
false
```\ndef distributeCandies(self, candyType: List[int]) -> int:\n # half length of candyType list\n candy_len = int(len(candyType)/2)\n # no of of unique candies \n unique_candy_len = len(set(candyType))\n return min(candy_len,unique_candy_len)\n```
10
0
['Python', 'Python3']
1
distribute-candies
[Java] 1-Liner using HashSet
java-1-liner-using-hashset-by-i18n-vu1d
\nclass Solution {\n public int distributeCandies(int[] candyType) {\n return Math.min(candyType.length / 2, Arrays.stream(candyType).boxed().collect(
i18n
NORMAL
2021-03-01T12:55:09.205962+00:00
2021-03-01T12:55:09.206006+00:00
203
false
```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n return Math.min(candyType.length / 2, Arrays.stream(candyType).boxed().collect(Collectors.toSet()).size());\n }\n}\n```\n\n`TC - O(n)`\n
8
5
[]
0
distribute-candies
[C++/Java/Python] 1 Liner
cjavapython-1-liner-by-dnuang-4zdf
She cannot get more than half even if the all the candies are different.\n\nC++\n\nint distributeCandies(vector<int>& candies) {\n return min(candies.size()
dnuang
NORMAL
2018-03-16T05:04:33.179007+00:00
2018-03-16T05:04:33.179007+00:00
722
false
She **cannot get more than half** even if the all the candies are different.\n\nC++\n```\nint distributeCandies(vector<int>& candies) {\n return min(candies.size() / 2, unordered_set<int>(candies.begin(), candies.end()).size()); \n}\n```\n\nJava\n```\npublic int distributeCandies(int[] candies) {\n return Math.min(candies.length / 2, IntStream.of(candies).boxed().collect(Collectors.toSet()).size());\n}\n```\n\n\nPython\n```\ndef distributeCandies(self, candies):\n return min(len(candies) / 2, len(set(candies)))\n```
8
0
[]
2
distribute-candies
575: Time 92.8%, Solution with step by step explanation
575-time-928-solution-with-step-by-step-otamc
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Initialize a set to store unique candy types.\n2. Traverse through the
Marlen09
NORMAL
2023-03-15T05:34:11.523074+00:00
2023-03-15T05:34:11.523113+00:00
1,409
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a set to store unique candy types.\n2. Traverse through the input array and add each candy type to the set.\n3. Find the length of the input array and divide it by 2 to get the maximum number of candies Alice can eat.\n4. Find the length of the set of unique candy types.\n5. Return the minimum between the length of the set of unique candy types and the maximum number of candies Alice can eat.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n # Use set to count the number of unique candies\n unique_candies = set(candyType)\n \n # Return the minimum between the number of unique candies and half the length of the input array\n return min(len(unique_candies), len(candyType)//2)\n\n```
7
0
['Array', 'Hash Table', 'Python', 'Python3']
0
distribute-candies
✅ Easiest || 💯 Beats || ⭐ Java || ✨ Sweet Strategy
easiest-beats-java-sweet-strategy-by-muk-3m31
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is asking to maximize the number of different candy types Alice can e
mukund_rakholiya
NORMAL
2024-09-20T14:31:53.572594+00:00
2024-09-20T14:31:53.572632+00:00
1,434
false
```\n```\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**The problem is asking to maximize the number of different candy types Alice can eat, while still following the doctor\'s rule of only eating half of the candies. This suggests that we need to track the number of unique candy types and compare it to the maximum number of candies Alice is allowed to eat.**\n\n```\n```\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Use a set to store the unique candy types.**\n2. **Calculate the maximum number of candies Alice can eat: `n / 2`, where `n` is the length of the `candyType` array.**\n3. **If the number of unique candy types is greater than or equal to `n / 2`, return `n / 2`, since Alice can\'t eat more than that many candies.**\n4. **Otherwise, return the number of unique candy types, as Alice can eat all of them.**\n\n```\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**`O(n)` where `n` is the number of candies. We iterate through the array once to add candy types to the set.**\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**`O(n)` in the worst case, when all candy types are unique, the set will store all `n` elements.**\n\n```\n```\n\n# Code\n```java []\nclass Solution {\n public int distributeCandies(int[] candyType) {\n Set<Integer> set = new HashSet<>();\n\n for (var i : candyType) \n set.add(i);\n \n var n = candyType.length / 2;\n\n if (set.size() >= n) \n return n;\n else \n return set.size();\n }\n}\n```\n\n```\n```\n\n![upvote.png](https://assets.leetcode.com/users/images/6e3afe3f-353d-42ac-99d5-7287bd257839_1726842619.6860626.png)\n
6
0
['Array', 'Hash Table', 'Java']
3
distribute-candies
Easy to solve without set & beginner friendly.
easy-to-solve-without-set-beginner-frien-fgxe
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is about distributing candies to ensure the maximum number of unique candy
ShivaanjayNarula
NORMAL
2024-06-30T00:35:02.898471+00:00
2024-06-30T00:35:02.898494+00:00
598
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about distributing candies to ensure the maximum number of unique candy types one person can receive, given that there are n candies and the maximum each person can get is n/2 candies.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Sorting:**\n\nThe code begins by sorting the candyType vector. Sorting helps in grouping the same types of candies together, making it easier to count the unique types.\n\n**2. Counting Unique Candy Types:**\n\nInitialize a variable ans to 1, which will store the count of unique candy types.\n\nIterate through the sorted candyType array.\n\nFor each candy type, check if it is different from the next one. If it is, increment the count of unique candy types (ans).\n\n**3. Determining Maximum Unique Types:**\n\nCalculate check as n / 2 because one person can only get up to n / 2 candies.\n\nCompare ans (the number of unique types) with check. The result should be the minimum of these two values because:\n\n- If there are more unique types than n / 2, the person can only get n/2 unique types.\n\n- If there are fewer or equal unique types than n / 2, the person can get all unique types.\n\n# Complexity\n- Time complexity: O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int n = candyType.size();\n sort(candyType.begin(), candyType.end());\n int ans = 1; \n for(int i = 0; i < n-1; i++)\n {\n if(candyType[i] != candyType[i+1])\n {\n ans++;\n }\n }\n int check = n/2;\n if(ans > check)\n {\n ans = check;\n }\n return ans;\n }\n};\n```\n\n# Please upvote my solution, if found useful.
6
0
['Array', 'Hash Table', 'C++']
1
distribute-candies
🔥🔥🔥🔥🔥 Beat 99% 🔥🔥🔥🔥🔥 EASY 🔥🔥🔥🔥🔥🔥
beat-99-easy-by-abdallaellaithy-vk28
\n\n\n# Code\n\nclass Solution(object):\n def distributeCandies(self, candyType):\n """\n :type candyType: List[int]\n :rtype: int\n
abdallaellaithy
NORMAL
2024-02-29T10:47:27.295081+00:00
2024-03-16T15:09:27.522728+00:00
907
false
![Screenshot 2024-03-16 170233.png](https://assets.leetcode.com/users/images/819277ee-b498-49af-8073-4ca86a7cbbb3_1710601760.5862021.png)\n\n\n# Code\n```\nclass Solution(object):\n def distributeCandies(self, candyType):\n """\n :type candyType: List[int]\n :rtype: int\n """\n return min(len(candyType)/2, len(set(candyType)))\n```
6
0
['Python', 'Python3']
1
distribute-candies
Easy unordered_set solution | | O(n) time complexity
easy-unordered_set-solution-on-time-comp-qw17
\n# Approach\n Describe your approach to solving the problem. \nStore elements of given vector in an unordered_set. Since the unordered_set stores only unique e
suhani_29
NORMAL
2023-04-27T07:24:53.766708+00:00
2023-05-09T13:09:30.515841+00:00
911
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStore elements of given vector in an unordered_set. Since the unordered_set stores only unique elements the occurence of each element will be 1 only.\nNow we know she can eat only n/2 candies of different types so if the number of distinct elements is greater or equal to n/2 then she can have only n/2 candies irrespectiv of the distinct elements.\nBut if the number is less than n/2 then the option is the number of distinct cnadies only.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n int n = candyType.size();\n unordered_set<int> s(candyType.begin(), candyType.end());\n if(s.size() >= n/2){\n return n/2;\n }\n return s.size();\n }\n};\n```
6
0
['C++']
1
distribute-candies
HashSet easy solution
hashset-easy-solution-by-priyankan_23-1vkf
\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> set=new HashSet<>();\n for(int num : candyType )set.add
priyankan_23
NORMAL
2022-09-13T18:30:41.045978+00:00
2022-09-13T18:30:41.046023+00:00
794
false
```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> set=new HashSet<>();\n for(int num : candyType )set.add(num);\n return set.size()>=(candyType.length/2)?candyType.length/2:set.size();\n }\n}\n```
6
0
['Java']
0
distribute-candies
JS, Python, Java, C++ | Set Solution w/ Explanation
js-python-java-c-set-solution-w-explanat-xmpl
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n
sgallivan
NORMAL
2021-03-01T09:01:24.202814+00:00
2021-03-01T09:01:24.202856+00:00
529
false
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nIn order to solve this problem, we need to identify how many unique types of candy there are. The easiest method to find unique values is with a **set**. If we convert our input array of candy types (**C**) to a set, then it will only contain unique values, and thus the size of the set will represent the number of different candy types.\n\nThe only other thing to remember is that we\'re constrained to at most **C.length / 2** pieces, per the instructions, so we need to use a **min()** boundary before we **return** our answer.\n\n---\n\n#### ***Implementation:***\n\nJava alone does not have an easy **set** constructor from an **int array**. Any such solution would have to invole boxing the primitive **int**s into **Integer**s before converting to a **HashSet**, so it\'s easier just to build the **HashSet** iteratively via a **for loop**.\n\n---\n\n#### ***Javascript Code:***\n\n```javascript\nconst distributeCandies = C => Math.min((new Set(C)).size, C.length / 2)\n```\n\n---\n\n#### ***Python Code:***\n\n```python\nclass Solution:\n def distributeCandies(self, C: List[int]) -> int:\n return min(len(set(C)), len(C) // 2)\n```\n\n---\n\n#### ***Java Code:***\n\n```java\nclass Solution {\n public int distributeCandies(int[] C) {\n Set<Integer> cset = new HashSet<>();\n for (int c : C) cset.add(c)\n return Math.min(cset.size(), C.length / 2);\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\n```c++\nclass Solution {\npublic:\n int distributeCandies(vector<int>& C) {\n unordered_set<int> cset(begin(C), end(C));\n return min(cset.size(), C.size() / 2);\n }\n};\n```
6
3
['C', 'Python', 'Java', 'JavaScript']
0
distribute-candies
Python One-Liner Simple Solution
python-one-liner-simple-solution-by-yehu-vov2
\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return min(len(candyType)//2, len(set(candyType)))\n\nLike it? please up
yehudisk
NORMAL
2021-03-01T08:23:34.581722+00:00
2021-03-01T12:07:25.704766+00:00
475
false
```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return min(len(candyType)//2, len(set(candyType)))\n```\n**Like it? please upvote...**
6
0
['Python']
0
distribute-candies
C++ solution 98% faster time and 96% lesser space Distribute Candies
c-solution-98-faster-time-and-96-lesser-8yxbo
```\nint distributeCandies(vector& candyType) {\n bitset<200001> bit(0);//200001 covers the range (10^-5 , 10^5)\n int n = candyType.size();\n
grey__c__
NORMAL
2021-01-31T18:06:52.275286+00:00
2021-01-31T18:06:52.275311+00:00
522
false
```\nint distributeCandies(vector<int>& candyType) {\n bitset<200001> bit(0);//200001 covers the range (10^-5 , 10^5)\n int n = candyType.size();\n for(int i=0;i<n;++i)bit.set(candyType[i]+100000);\n n/=2;\n int count = bit.count();\n return min(n,count);\n }
6
0
[]
3
distribute-candies
C++ 2-line super-simple solution
c-2-line-super-simple-solution-by-yehudi-w5u9
\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n
yehudisk
NORMAL
2020-08-18T22:13:16.646686+00:00
2020-08-18T22:13:16.646721+00:00
743
false
```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n int types_num = set<int>(candies.begin(), candies.end()).size();\n return types_num > candies.size()/2 ? candies.size()/2 : types_num;\n }\n};\n```
6
0
['C', 'C++']
0
distribute-candies
JAVA Easy 2 Solutions 🔥100% Faster Code 🔥Beginner Friendly🔥
java-easy-2-solutions-100-faster-code-be-axng
Please UPVOTE if helps!\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space comple
diyordev
NORMAL
2023-12-06T10:22:55.534373+00:00
2023-12-06T10:22:55.534409+00:00
702
false
# Please UPVOTE if helps!\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# First Solution\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n boolean[] types = new boolean[200001];\n int count = 0;\n for(int i : candyType){\n int temp = i + 100000;\n if (!types[temp]){\n if (++count == candyType.length / 2) return count;\n types[temp] = true;\n }\n }\n return count;\n }\n}\n```\n\n# Second Solution\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> types = new HashSet<>();\n int canEat = candyType.length / 2;\n for (int i : candyType){\n if (types.size() >= canEat)\n return canEat;\n types.add(i);\n }\n return Math.min(canEat, types.size());\n }\n}\n```
5
0
['Java']
1
distribute-candies
3 Line Java Solution
3-line-java-solution-by-im_bug-jaiy
\n public int distributeCandies(int[] candyType) {\n int n = candyType.length;\n Set set = new HashSet();\n for(int candy : candyType)\n
im_BUG
NORMAL
2022-10-10T05:02:41.751310+00:00
2022-10-10T05:02:41.751343+00:00
817
false
\n public int distributeCandies(int[] candyType) {\n int n = candyType.length;\n Set<Integer> set = new HashSet();\n for(int candy : candyType)\n set.add(candy);\n return Math.min(set.size(), n/2);\n }\n\t\t //plz !!! upvote
5
0
['Ordered Set', 'Java']
1
distribute-candies
C++ Easy Solution
c-easy-solution-by-naman_151-9bbo
Hope this helps : )\n\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n sort(candyType.begin(),candyType.end());\n
Naman_151
NORMAL
2022-06-30T18:30:24.858225+00:00
2022-06-30T18:30:24.858272+00:00
366
false
Hope this helps : )\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n sort(candyType.begin(),candyType.end());\n int count = 1;\n for(int i = 0;i<candyType.size();i++){\n for(int j = i+1;j<candyType.size();j++){\n if(candyType[i]==candyType[j]){\n continue;\n }\n else if(candyType[i]!=candyType[j]){\n i=j;\n i--;\n count++;\n break;\n }\n }\n }\n int n = candyType.size()/2;\n if(count == n){\n return n;\n }\n else{\n return min(count,n);\n }\n }\n};\n```\nMake sure to upvote.
5
0
['C']
0
distribute-candies
Python 1-line
python-1-line-by-emoson-hcz8
class Solution(object):\n\n def distributeCandies(self, candies):\n \treturn min(len(candies) / 2,len(set(candies)))
emoson
NORMAL
2017-05-07T03:25:18.977000+00:00
2017-05-07T03:25:18.977000+00:00
1,392
false
class Solution(object):\n\n def distributeCandies(self, candies):\n \treturn min(len(candies) / 2,len(set(candies)))
5
0
[]
0
distribute-candies
Java solution beats 99.07%
java-solution-beats-9907-by-vegito2002-0fiw
Based on Bucket Sort:\n\n public int distributeCandies(int[] candies) {\n int[] b = new int[200001];\n int nonEmptyBucketNo = 0;\n for (
vegito2002
NORMAL
2017-06-16T03:11:59.566000+00:00
2017-06-16T03:11:59.566000+00:00
1,340
false
Based on Bucket Sort:\n<pre><code>\n public int distributeCandies(int[] candies) {\n int[] b = new int[200001];\n int nonEmptyBucketNo = 0;\n for (int i : candies) if (b[i + 100000]++ == 0) nonEmptyBucketNo++;\n return nonEmptyBucketNo <= candies.length / 2 ? nonEmptyBucketNo : candies.length / 2;\n }\n</code></pre>
5
2
[]
1
distribute-candies
simple cpp solution
simple-cpp-solution-by-prithviraj26-9vdi
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
prithviraj26
NORMAL
2023-02-21T16:43:38.126969+00:00
2023-02-21T16:43:38.127011+00:00
556
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 distributeCandies(vector<int>& candyType) {\n unordered_set<int>s;\n \n int n=candyType.size();\n for(int i=0;i<n;i++)\n {\n s.insert(candyType[i]);\n }\n n/=2;\n if(s.size()<n)\n {\n return s.size();\n }\n return n;\n }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/2410b22b-c672-4e1a-afc3-35e120195b30_1676997814.3927085.jpeg)\n
4
0
['C++']
0
distribute-candies
Java One Liner Solution
java-one-liner-solution-by-janhvi__28-12g5
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
Janhvi__28
NORMAL
2022-12-08T19:02:41.647176+00:00
2022-12-08T19:02:41.647216+00:00
1,160
false
# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n Set<Integer> s = new HashSet<>();\n for (int x : candyType) {\n s.add(x);\n }\n return Math.min(candyType.length >> 1, s.size());\n }\n}\n```
4
0
['Java']
0
distribute-candies
Rust solution
rust-solution-by-wddwycc-we40
rust\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn distribute_candies(candy_type: Vec<i32>) -> i32 {\n let len = candy_type.len();\n
wddwycc
NORMAL
2021-03-01T12:43:06.240652+00:00
2021-03-01T12:43:06.240691+00:00
89
false
```rust\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn distribute_candies(candy_type: Vec<i32>) -> i32 {\n let len = candy_type.len();\n let hashset: HashSet<i32> = candy_type.into_iter().collect();\n std::cmp::min(len / 2, hashset.len()) as i32\n }\n}\n```
4
1
['Rust']
1
distribute-candies
Python. One-liner Easy-understanding solution.
python-one-liner-easy-understanding-solu-i5bs
```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(candyType) //2, len(set(candyType)))
m-d-f
NORMAL
2021-03-01T11:40:50.277928+00:00
2021-03-01T11:40:50.277981+00:00
308
false
```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(candyType) //2, len(set(candyType)))
4
2
['Python', 'Python3']
0
distribute-candies
Distribute Candies | JS, Python, Java, C++ | Set Solution w/ Explanation
distribute-candies-js-python-java-c-set-1zy5e
(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\n\n---\n\n#### Idea:\n
sgallivan
NORMAL
2021-03-01T09:02:18.097443+00:00
2021-03-01T09:02:18.097477+00:00
189
false
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nIn order to solve this problem, we need to identify how many unique types of candy there are. The easiest method to find unique values is with a **set**. If we convert our input array of candy types (**C**) to a set, then it will only contain unique values, and thus the size of the set will represent the number of different candy types.\n\nThe only other thing to remember is that we\'re constrained to at most **C.length / 2** pieces, per the instructions, so we need to use a **min()** boundary before we **return** our answer.\n\n---\n\n#### ***Implementation:***\n\nJava alone does not have an easy **set** constructor from an **int array**. Any such solution would have to invole boxing the primitive **int**s into **Integer**s before converting to a **HashSet**, so it\'s easier just to build the **HashSet** iteratively via a **for loop**.\n\n---\n\n#### ***Javascript Code:***\n\n```javascript\nconst distributeCandies = C => Math.min((new Set(C)).size, C.length / 2)\n```\n\n---\n\n#### ***Python Code:***\n\n```python\nclass Solution:\n def distributeCandies(self, C: List[int]) -> int:\n return min(len(set(C)), len(C) // 2)\n```\n\n---\n\n#### ***Java Code:***\n\n```java\nclass Solution {\n public int distributeCandies(int[] C) {\n Set<Integer> cset = new HashSet<>();\n for (int c : C) cset.add(c)\n return Math.min(cset.size(), C.length / 2);\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\n```c++\nclass Solution {\npublic:\n int distributeCandies(vector<int>& C) {\n unordered_set<int> cset(begin(C), end(C));\n return min(cset.size(), C.size() / 2);\n }\n};\n```
4
1
[]
1
distribute-candies
Python one-liner simplest solution
python-one-liner-simplest-solution-by-ye-eu6z
\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return len(candies)//2 if len(set(candies)) > len(candies)//2 else len(s
yehudisk
NORMAL
2020-08-19T12:46:03.771504+00:00
2020-08-19T12:46:03.771532+00:00
265
false
```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return len(candies)//2 if len(set(candies)) > len(candies)//2 else len(set(candies))\n```
4
0
['Python3']
0
distribute-candies
100% | 100% | Java | 4 Solution | Optimisations
100-100-java-4-solution-optimisations-by-wx1c
Using Hash technique\n37 ms, faster than 83.75%\n\n\n\n/**\n * Important observation is that, if there are n types of candies then sister is more likely to have
nits2010
NORMAL
2019-08-24T14:12:31.132306+00:00
2019-08-24T14:12:31.132341+00:00
300
false
Using Hash technique\n37 ms, faster than 83.75%\n\n```\n\n/**\n * Important observation is that, if there are n types of candies then sister is more likely to have n types of candies\n * 1. if; distribution of candies > types of candies -> sister will have all kind of candies for sure\n * 2. else distribution of candies < types of candies -> sister will can not have all types of candies as her share is smaller then types\n * <p>\n * O(n) / O (n)\n */\nclass DistributeCandiesUsingHash {\n public int distributeCandies(int[] candies) {\n\n if (candies == null || candies.length == 0)\n return 0;\n\n Map<Integer, Integer> map = new HashMap<>();\n\n for (int i = 0; i < candies.length; i++) {\n int c = candies[i];\n map.put(c, map.getOrDefault(c, 0) + 1);\n }\n\n int types = map.size();\n int total = candies.length;\n\n int equal = total / 2;\n\n if (equal < types)\n return equal;\n else\n return types;\n\n\n }\n\n\n /**\n * You don\'t need to count till end of array. Since if \'distribution of candies > types of candies\' then for sure she\'ll get all\n * kind of candies; Since distribution of candies = length / 2\n * <p>\n * <p>\n * Runtime: 37 ms, faster than 83.75% of Java online submissions for Distribute Candies.\n * Memory Usage: 40.4 MB, less than 100.00% of Java online submissions for Distribute Candies.\n *\n * @param candies\n * @return\n */\n public int distributeCandiesFaster(int[] candies) {\n\n if (candies == null || candies.length == 0)\n return 0;\n\n Set<Integer> set = new HashSet<>();\n int types = 0;\n\n for (int i = 0; i < candies.length && types < candies.length / 2; i++) {\n int c = candies[i];\n if (!set.contains(c))\n types++;\n set.add(c);\n }\n\n return types;\n\n\n }\n}\n\n```\n\nUsing Bit set:\n11 ms, faster than 96.95%\n\n```\n\n/**\n * Important observation is that, if there are n types of candies then sister is more likely to have n types of candies\n * 1. if; distribution of candies > types of candies -> sister will have all kind of candies for sure\n * 2. else distribution of candies < types of candies -> sister will can not have all types of candies as her share is smaller then types\n * <p>\n * Since types of candies are fixed range [-100,000, 100,000].\n * Then we can use bitSet to count the types\n * <p>\n * Runtime: 11 ms, faster than 96.95% of Java online submissions for Distribute Candies.\n * Memory Usage: 45.1 MB, less than 47.37% of Java online submissions for Distribute Candies.\n */\n\nclass DistributeCandiesUsingBit {\n\n\n public int distributeCandies(int[] candies) {\n if (candies == null || candies.length == 0)\n return 0;\n\n int types = 0;\n final int offset = 100000;\n BitSet bitSet = new BitSet(100000 * 2 + 1);\n\n for (int i = 0; i < candies.length && types < candies.length >> 1; i++) {\n\n int c = candies[i] + offset;\n\n if (!bitSet.get(c))\n types++;\n bitSet.set(c);\n\n\n }\n\n return types;\n\n\n }\n}\n\n```\n\nUsing boolean array: This will reduce the overall task to manage a bit\n6 ms, faster than 100% \n```\nclass DistributeCandiesUsingBoolean {\n\n\n public int distributeCandies(int[] candies) {\n if (candies == null || candies.length == 0)\n return 0;\n\n final int offset = 100000;\n boolean[] set = new boolean[2 * offset + 1];\n int types = 0;\n for (int i = 0; i < candies.length && types < candies.length >> 1; i++) {\n\n if (!set[candies[i] + offset]) {\n types++;\n set[candies[i] + offset] = true;\n }\n }\n return types;\n\n\n }\n\n\n}\n```
4
0
[]
0
distribute-candies
One line Python
one-line-python-by-yindaiying-8462
\nclass Solution(object):\n def distributeCandies(self, candies):\n return min(len(candies)//2, len(set(candies)))\n
yindaiying
NORMAL
2019-07-16T08:36:31.737930+00:00
2019-07-16T08:36:31.737962+00:00
380
false
```\nclass Solution(object):\n def distributeCandies(self, candies):\n return min(len(candies)//2, len(set(candies)))\n```
4
1
[]
0
distribute-candies
Java hashset solution
java-hashset-solution-by-earlme-r7ea
public int distributeCandies(int[] candies) {\n Set<Integer> set = new HashSet<>();\n for(Integer candie : candies) {\n set.add(candie)
earlme
NORMAL
2017-05-07T03:03:17.812000+00:00
2017-05-07T03:03:17.812000+00:00
1,678
false
public int distributeCandies(int[] candies) {\n Set<Integer> set = new HashSet<>();\n for(Integer candie : candies) {\n set.add(candie);\n if(set.size() == candies.length/2) return set.size();\n }\n return Math.min(set.size(), candies.length/2);\n }
4
2
[]
2
distribute-candies
Java 8 one line solution O(n)
java-8-one-line-solution-on-by-lxyjscz-09h6
```\npublic class Solution {\n public int distributeCandies(int[] candies) {\n return Math.min(candies.length / 2, IntStream.of(candies).boxed().colle
lxyjscz
NORMAL
2017-05-07T19:14:54.373000+00:00
2017-05-07T19:14:54.373000+00:00
2,743
false
```\npublic class Solution {\n public int distributeCandies(int[] candies) {\n return Math.min(candies.length / 2, IntStream.of(candies).boxed().collect(Collectors.toSet()).size());\n }\n}\n````
4
1
[]
1
distribute-candies
1-liner Java and Python
1-liner-java-and-python-by-jianchao-li-sttl
Given n (even) candies, the sister can at most get n / 2 of them (distributed evenly). And if there are k kinds, k is also the upper bound of the number of kind
jianchao-li
NORMAL
2017-11-22T14:07:04.698000+00:00
2017-11-22T14:07:04.698000+00:00
577
false
Given `n` (even) candies, the sister can at most get `n / 2` of them (distributed evenly). And if there are `k` kinds, `k` is also the upper bound of the number of kinds the sister can get.\n\n`n / 2` is simply `candies.length / 2`. To compute `k`, a traditional way is to use a hash map to count occurrences. And a shorter way is to use Java 8 streams.\n\n**1-liner Java 8 stream**\n```\nclass Solution {\n public int distributeCandies(int[] candies) {\n return Integer.min((int) Stream.of(candies).distinct().count(), candies.length / 2);\n }\n}\n```\n\n**Traditional HashMap**\n```\nclass Solution {\n public int distributeCandies(int[] candies) {\n final Map<Integer, Integer> kinds = new HashMap<>();\n for (final int candy : candies) {\n if (kinds.containsKey(candy)) {\n kinds.put(candy, kinds.get(candy) + 1);\n } else {\n kinds.put(candy, 1);\n }\n }\n return Integer.min(kinds.size(), candies.length / 2);\n }\n}\n```\n\n**Python 1-liner**\nComputing `k` is just the use case of `Counter`.\n```\nfrom collections import Counter\n\nclass Solution(object):\n def distributeCandies(self, candies):\n """\n :type candies: List[int]\n :rtype: int\n """\n return min(len(Counter(candies)), len(candies) / 2) \n```\nWith Java 8 streams, 1-liner becomes more likely for Java :-)
4
0
[]
2
distribute-candies
C++✅ || Beats 65%💯|| 6 Lines Code💀💯|| EasyPizyy🔥💯
c-beats-65-6-lines-code-easypizyy-by-yas-64mj
🍬 IntuitionThe goal is to maximize the number of unique candy types the sister can eat while ensuring she only eats half of the total candies. 🎯🛠️ Approach 🏷️ U
yashm01
NORMAL
2025-02-15T14:43:15.078082+00:00
2025-02-15T14:43:15.078082+00:00
197
false
![Screenshot 2025-02-15 201017.png](https://assets.leetcode.com/users/images/37af4f7c-6768-4532-90ad-251bf63922fb_1739630524.8006313.png) # 🍬 Intuition The goal is to **maximize the number of unique candy types** the sister can eat while ensuring she only eats **half** of the total candies. 🎯 # 🛠️ Approach 1. 🏷️ **Use a HashMap (`unordered_map`)** to track unique candy types. 2. 🍪 Count how many unique candy types exist. 3. ⚖️ The maximum candies she can eat is **half of the total candies** (`n/2`). 4. ✅ Return the **minimum** of (unique candy types, `n/2`) since she can't exceed her limit. # ⏳ Complexity - **Time Complexity:** ⏱️ $$O(n)$$ (Loop through candies once). - **Space Complexity:** 📦 $$O(n)$$ (For storing unique candy types). # 💻 Code ```cpp class Solution { public: int distributeCandies(vector<int>& candyType) { unordered_map<int,bool> candyExist; int candy = candyType.size() / 2; int cnt = 0; for (int i : candyType) { if (!candyExist[i]) { // 🍬 Found a new type of candy cnt++; candyExist[i] = true; } } return min(cnt, candy); // ✅ Choose the max unique candies possible } }; ``` ![upvote.jpeg](https://assets.leetcode.com/users/images/b172ae49-b682-4b8d-b91b-76dc6fb053a3_1739630511.5648668.jpeg)
3
0
['Array', 'Hash Table', 'C++']
0
distribute-candies
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-kbqg
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n int distributeCandies(vector<int>& nums) \n {\n set<i
shishirRsiam
NORMAL
2024-05-20T18:27:18.892979+00:00
2024-05-20T18:27:18.893007+00:00
499
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& nums) \n {\n set<int>st;\n for(int val:nums) st.insert(val);\n return min(nums.size()/2, st.size());\n }\n};\n```
3
0
['Array', 'Math', 'C++']
3
distribute-candies
Simple O(n) solution
simple-on-solution-by-sharmanishchay-iouq
Intuition\n Describe your first thoughts on how to solve this problem. \n- HashSet Usage: By utilizing a HashSet, the code efficiently keeps track of the unique
sharmanishchay
NORMAL
2024-02-14T13:05:20.970146+00:00
2024-02-14T13:05:20.970174+00:00
57
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- HashSet Usage: By utilizing a HashSet, the code efficiently keeps track of the unique types of candies. A HashSet ensures that only unique elements are stored, which is perfect for this scenario as we are interested in counting the different types of candies available.\n- Counting Unique Types: As the code iterates through the candyType array, it adds each type of candy to the HashSet. Since a HashSet does not allow duplicates, it automatically filters out repeated types of candies, ensuring that each type is counted only once.\n- Calculating Maximum Types: After collecting all unique types of candies, the code calculates the maximum number of different types of candies the sister can have. This is determined by taking the minimum of two values:\n- The number of unique types of candies stored in the HashSet.\nHalf of the total number of candies available (candyType.length / 2). This represents the maximum number of candies the sister can have if she takes half of all available candies.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Using HashSet for Unique Types: The method begins by initializing a HashSet named set. This data structure is chosen because it automatically maintains uniqueness of elements. Each element added to the HashSet is unique, meaning duplicates are automatically removed.\n- Iterating Through Candy Types: The method iterates through the candyType array using a for loop. During each iteration, it adds the current candy type to the HashSet using the add() method. This effectively filters out duplicate candy types, ensuring that each unique type is counted only once.\n- Calculating Maximum Number of Types: After iterating through all candy types, the method calculates the maximum number of different types of candies the sister can have. This is done by taking the minimum of two values:\n- The size of the HashSet (set.size()), which represents the number of unique candy types collected.\nHalf of the total number of candies available, calculated as candyType.length / 2. This is because the sister can only have at most half of the total candies available.\n- Returning the Result: Finally, the method returns the calculated maximum number of different types of candies the sister can have. This ensures that the sister gets as many different types as possible while still adhering to the constraint of taking only half of the total candies.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n HashSet<Integer> set = new HashSet<>();\n for(int i = 0;i < candyType.length;i++){\n set.add(candyType[i]);\n } \n return Math.min(set.size(), candyType.length / 2);\n }\n}\n```
3
0
['Hash Table', 'Java']
0
distribute-candies
Easy Solution in C++, Time complexity: O(N)
easy-solution-in-c-time-complexity-on-by-mkxx
Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) \n
ashiquranik
NORMAL
2023-08-27T10:20:14.440556+00:00
2023-08-27T10:54:20.770902+00:00
280
false
# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) \n {\n map<int,int>m;\n for(int i=0;i<candyType.size();i++)\n {\n m[candyType[i]]++;\n }\n int eat = candyType.size()/2;\n //return eat;\n int type = m.size();\n cout<<type<<endl;\n if(eat>=type)\n {\n return type;\n }\n else\n {\n return eat;\n }\n }\n};\n```
3
0
['C++']
0
distribute-candies
C# one line
c-one-line-by-maxim_kurbanov-simb
Code\n\npublic class Solution \n{\n public int DistributeCandies(int[] candyType) \n {\n return Math.Min(candyType.ToHashSet().Count, candyType.Len
Maxim_Kurbanov
NORMAL
2023-05-17T18:50:52.529609+00:00
2023-05-17T18:50:52.529644+00:00
72
false
# Code\n```\npublic class Solution \n{\n public int DistributeCandies(int[] candyType) \n {\n return Math.Min(candyType.ToHashSet().Count, candyType.Length / 2);\n }\n}\n```
3
0
['C#']
0
distribute-candies
✔Beats 100% TC || Simple if else || Easily Understandable Python Solution
beats-100-tc-simple-if-else-easily-under-12zc
Approach\n - Converts the array candyType to a set which gonna contain only discrete values\n - if eat <= len(dis_candyType) it means there are enough options a
Gourav_Sinha
NORMAL
2023-04-28T15:02:56.605288+00:00
2023-04-28T15:14:19.800946+00:00
832
false
# Approach\n - Converts the array ```candyType``` to a set which gonna contain only discrete values\n - if ```eat <= len(dis_candyType)``` it means there are enough options available (i.e. Here every candy Alice eats is of different type)\n - elif ```eat > len(dis_candyType)``` not enough options available \n (i.e. Here Alice will have ```len(dis_candyType)``` different types of candies)\n# Complexity\n- Time complexity:\nBeats 100%\n\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n l = len(candyType)\n eat = l//2\n dis_candyType = set(candyType)\n\n if eat <= len(dis_candyType):\n return eat\n\n elif eat > len(dis_candyType):\n return len(dis_candyType) \n\n# Please Upvote if you like it :)\n```
3
0
['Python', 'Python3']
0
distribute-candies
Python 3-lines ✅✅✅ || Faster than 98.93% || Simple + Explained
python-3-lines-faster-than-9893-simple-e-1wzp
Note: In the tags, I put Ordered Set there but the set doesn\'t actually have any order.\n## Please \uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D
a-fr0stbite
NORMAL
2022-12-25T00:57:46.175171+00:00
2022-12-25T01:04:57.568674+00:00
890
false
**Note:** In the tags, I put Ordered Set there but the set doesn\'t actually have any order.\n## Please \uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB if u like!!\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType):\n n = len(candyType) // 2 # just get the number of candies you can eat\n LEN = len(set(candyType)) # types of different candies\n return min(n, LEN) # use min() to get the max types we can get\n```\n![image.png](https://assets.leetcode.com/users/images/2214ba90-c367-4ae0-b62a-c44c309bd34e_1671929564.8890448.png)
3
0
['Array', 'Ordered Set', 'Python', 'Python3']
0
distribute-candies
Java Solution using HashMap
java-solution-using-hashmap-by-akash_200-4stk
If the solution is helpful please upvote this.\n\n\nclass Solution {\n public int distributeCandies(int[] candyType) {\n \n HashMap<Integer, In
Akash_2000
NORMAL
2022-10-17T16:53:45.295280+00:00
2022-10-17T16:53:45.295323+00:00
692
false
If the solution is helpful please upvote this.\n\n```\nclass Solution {\n public int distributeCandies(int[] candyType) {\n \n HashMap<Integer, Integer> map = new HashMap<>();\n \n for(int i = 0; i<candyType.length; i++)\n {\n map.put(candyType[i], map.getOrDefault(candyType[i], 0)+1);\n }\n \n int permit = candyType.length / 2;\n \n if(map.size() < permit)\n {\n return map.size();\n }\n \n return permit;\n }\n}\n```
3
0
['Java']
0
distribute-candies
Java easy solution
java-easy-solution-by-anchaljain_04-rflg
\tclass Solution {\n\t\tpublic int distributeCandies(int[] candyType) {\n\t\t\tHashSeths=new HashSet<>();\n\t\t\tfor(int i:candyType)\n\t\t\t\ths.add(i);\n\t\t\
anchaljain_04
NORMAL
2022-10-06T12:48:22.938671+00:00
2022-10-06T12:48:22.938740+00:00
343
false
\tclass Solution {\n\t\tpublic int distributeCandies(int[] candyType) {\n\t\t\tHashSet<Integer>hs=new HashSet<>();\n\t\t\tfor(int i:candyType)\n\t\t\t\ths.add(i);\n\t\t\tint r=candyType.length/2;\n\t\t\tif(hs.size()<r)\n\t\t\t return hs.size();\n\t\t\telse\n\t\t\t\treturn r;\n\t\t}\n\t}
3
0
[]
0
distribute-candies
C++ BEGINNERS FRNDLY SOLn
c-beginners-frndly-soln-by-geek_monk-d90a
\nclass Solution {\npublic:\n int distributeCandies(vector<int>& a) {\n unordered_set<int> s; // declaration of set\n for(int i=0;i<a.si
geek_monk
NORMAL
2022-04-14T07:24:09.801672+00:00
2022-04-14T07:24:09.801703+00:00
146
false
```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& a) {\n unordered_set<int> s; // declaration of set\n for(int i=0;i<a.size();i++)\n s.insert(a[i]); // insertion in set\n \n int x=min(s.size(),a.size()/2); // finding minimum of half of total and different kinds of candies\n return x; // returning the answer\n \n \n }\n};\n```\nKINDLY UPVOTE <3 !!
3
0
['Ordered Set']
0
distribute-candies
Simple C++ Solution || Runtime faster than 79.79% || Memory Usage less than 62.37%
simple-c-solution-runtime-faster-than-79-zjmw
\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n unordered_set<int> s;\n int n = candyType.size();\n for(
Arbind007
NORMAL
2021-11-27T11:43:50.509270+00:00
2021-11-27T11:43:57.105205+00:00
677
false
```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candyType) {\n unordered_set<int> s;\n int n = candyType.size();\n for(int i=0;i<n;i++){\n s.insert(candyType[i]);\n }\n if(n/2 < s.size()){\n return n/2;\n }\n return s.size();\n }\n};\n```
3
0
['C', 'Ordered Set', 'C++']
0
distribute-candies
JavaScript One-Liner
javascript-one-liner-by-control_the_narr-5ka2
javascript\nvar distributeCandies = function(candyType) {\n return Math.min(candyType.length/2, new Set(candyType).size)\n};\n
control_the_narrative
NORMAL
2021-03-01T13:36:36.686247+00:00
2021-03-01T13:36:36.686285+00:00
294
false
```javascript\nvar distributeCandies = function(candyType) {\n return Math.min(candyType.length/2, new Set(candyType).size)\n};\n```
3
0
['JavaScript']
1
distribute-candies
JS One-liner Easy-understanding solution
js-one-liner-easy-understanding-solution-17e3
```\nvar distributeCandies = function(candyType) {\n return Math.min(candyType.length / 2, new Set(candyType).size);\n};
m-d-f
NORMAL
2021-03-01T11:59:06.268569+00:00
2021-03-01T11:59:06.268611+00:00
150
false
```\nvar distributeCandies = function(candyType) {\n return Math.min(candyType.length / 2, new Set(candyType).size);\n};
3
1
['JavaScript']
0
distribute-candies
[Python 3] Easy, fast, no Set(), O(n)
python-3-easy-fast-no-set-on-by-dpustova-20ki
To eat the maximum number of different types, Alice needs to eat the minimum number of every type. In other words she eats all types (by one candy) or a half of
dpustovarov
NORMAL
2021-03-01T10:15:11.223687+00:00
2021-03-01T10:22:35.152334+00:00
172
false
- To eat the maximum number of different types, Alice needs to eat the minimum number of every type. In other words she eats all types (by one candy) or a half of total number of candies. \n- Use set to control uniqueness. Set syntax `{*...}` is faster than set function `set(...)`.\n- Time complexity is `O(n)`. Space complexity is `O(n)`.\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(candyType) >> 1, len({*candyType}))\n```
3
1
['Ordered Set', 'Python']
0
distribute-candies
Distribute Candies | C++ using set
distribute-candies-c-using-set-by-sekhar-l4pe
Find unique candies by using a set\n2. Return min of (unique candies(size of set) and half the no of candies)\n\nclass Solution {\npublic:\n int distributeCa
sekhar179
NORMAL
2021-03-01T09:17:44.468738+00:00
2021-03-01T09:17:44.468801+00:00
178
false
1. Find unique candies by using a set\n2. Return min of (unique candies(size of set) and half the no of candies)\n```\nclass Solution {\npublic:\n int distributeCandies(vector<int>& candies) {\n set<int> st;\n for (auto candie: candies)\n st.insert(candie);\n return min(st.size(), candies.size()/2);\n }\n};\n```
3
1
['C']
0
distribute-candies
python 3 || one liner
python-3-one-liner-by-adarshbiradar-95e7
```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return min(len(set(candies)),len(candies)//2)
adarshbiradar
NORMAL
2020-07-20T09:23:02.604654+00:00
2020-07-20T09:24:19.127524+00:00
205
false
```\nclass Solution:\n def distributeCandies(self, candies: List[int]) -> int:\n return min(len(set(candies)),len(candies)//2)
3
1
['Ordered Set', 'Python3']
0
distribute-candies
⭐️ [ Javascript / Python3 / C++ ] 🎯 1-Liners
javascript-python3-c-1-liners-by-clayton-9u9g
Synopsis:\n\nSimply return the minimum of unique candies and half the length of A. This conclusion was derived from the following 2 use cases:\n\n Case 1: if l
claytonjwong
NORMAL
2020-06-03T23:46:32.321703+00:00
2020-10-05T14:17:11.933160+00:00
110
false
**Synopsis:**\n\nSimply return the minimum of unique candies and half the length of `A`. This conclusion was derived from the following 2 use cases:\n\n* **Case 1:** if less than half of the candies are unique, then give all those unique candies to the sister\n* **Case 2:** if more than half of the candies are unique, then we can give at most half to the sister\n\n*Javascript*\n```\nlet distributeCandies = A => Math.min(new Set(A).size, A.length / 2);\n```\n\n*Python3*\n```\nclass Solution:\n def distributeCandies(self, A: List[int]) -> int:\n return min(len(set(A)), len(A) // 2)\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n using Set = unordered_set<int>;\n int distributeCandies(VI& A) {\n return min(Set{ A.begin(), A.end() }.size(), A.size() / 2);\n }\n};\n```
3
0
[]
0