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
find-x-sum-of-all-k-long-subarrays-i
Easy To Understand Approach || Beats 100% βœ…βœ…β˜‘οΈβ˜‘οΈ
easy-to-understand-approach-beats-100-by-ijgm
\n# Steps to Solve the Problem\n1. Frequency Map:\n- Use an unordered map to count the frequency of elements in the current subarray of length k.\n2. Initial Wi
swapneel_singh
NORMAL
2024-10-13T05:09:17.229379+00:00
2024-10-13T17:25:14.437182+00:00
4,141
false
\n# Steps to Solve the Problem\n1. Frequency Map:\n- Use an unordered map to count the frequency of elements in the current subarray of length k.\n2. Initial Window:\n- Populate the frequency map for the first subarray (nums[0..k-1]).\n3. Calculate x-sum:\n\n- For the first window, determine the x-sum using the most frequent elements. If frequencies are tied, choose the larger value. Use a max heap for efficient retrieval of the top x elements.\n3. Sliding Window:\n\n- Slide the window across the array:\nRemove the outgoing element from the frequency map.\nAdd the new incoming element.\nCalculate the x-sum for the updated window.\n4. Return Results:\n\n- Store the x-sums in a result vector and return it.\n\n# Complexity\n- Time complexity: O(n\u22C5klogk)\n- Space complexity: O(n+k)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) \n {\n int n = nums.size();\n vector<int> answer;\n unordered_map<int, int> freq;\n\n // Initialize frequency map for the first window\n for (int j = 0; j < k; j++) {\n freq[nums[j]]++;\n }\n\n // Calculate x-sum for the first window\n answer.push_back(calculateXSum(freq, x));\n\n // Slide the window\n for (int i = 1; i <= n - k; i++) {\n // Remove the element going out of the window\n freq[nums[i - 1]]--;\n if (freq[nums[i - 1]] == 0) {\n freq.erase(nums[i - 1]);\n }\n\n // Add the new element coming into the window\n freq[nums[i + k - 1]]++;\n\n // Calculate x-sum for the current window\n answer.push_back(calculateXSum(freq, x));\n }\n \n return answer;\n }\n\nprivate:\n int calculateXSum(const unordered_map<int, int>& freq, int x) {\n // Use a priority queue (max heap) to get the top x elements\n priority_queue<pair<int, int>> pq; // (frequency, value)\n\n for (const auto& entry : freq) {\n pq.push({entry.second, entry.first});\n }\n\n int sum = 0;\n for (int i = 0; i < x && !pq.empty(); i++) {\n auto top = pq.top();\n pq.pop();\n sum += top.second * top.first; // sum = value * frequency\n }\n\n return sum;\n }\n};\n\n```
20
0
['Hash Table', 'Heap (Priority Queue)', 'C++']
6
find-x-sum-of-all-k-long-subarrays-i
Python3 || 5 lines, nlargest, mapping || T/S: 81% / 58%
python3-5-lines-nlargest-mapping-ts-81-5-nztz
Here\'s the intuition:\n- This problem is really a series of problems, each on a k-length subarray of nums. \n- Thus, we can determine a function to find the su
Spaulding_
NORMAL
2024-10-13T17:00:42.281663+00:00
2024-10-16T21:35:43.658712+00:00
1,657
false
Here\'s the intuition:\n- This problem is really a series of problems, each on a *k*-length subarray of `nums`. \n- Thus, we can determine a function to find the sum for each such a subarray and then map it to each subarray to determine the answer.\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n\n def do_sum (idx: int)-> int:\n\n ctr = Counter(nums[idx:idx + k])\n most_freq = nlargest(x, ctr, key = lambda y: (ctr[y], y))\n\n return sum(map(lambda y: y * ctr[y], most_freq))\n\n\n return map(do_sum,range(len(nums)+1 - k))\n```\n```cpp []\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int> result;\n\n auto do_sum = [&](int idx) -> int {\n unordered_map<int, int> ctr;\n\n for (int i = idx; i < idx + k; ++i) {\n ctr[nums[i]]++;}\n\n priority_queue<pair<int, int>> pq;\n\n for (auto& p : ctr) {\n pq.push({p.second, p.first}); }\n\n int sum = 0;\n for (int i = 0; i < x && !pq.empty(); ++i) {\n sum += pq.top().second * pq.top().first;\n pq.pop();}\n\n return sum;};\n\n for (int i = 0; i <= nums.size() - k; ++i) {\n result.push_back(do_sum(i));}\n\n return result;}\n};\n```\n[https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i/submissions/1421175528/](https://leetcode.com/problems/find-x-sum-of-all-k-long-subarrays-i/submissions/1421175528/)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*NKX*) and space complexity is *O*(*K*), in which *N* ~ `len(nums)`, *K* ~ `k`, and *X* ~ `x`.\n
13
1
['C++', 'Python3']
1
find-x-sum-of-all-k-long-subarrays-i
βœ… Simple Java Solution
simple-java-solution-by-harsh__005-0eni
CODE\nJava []\npublic int[] findXSum(int[] nums, int k, int x) {\n\tint n = nums.length;\n\tint res[] = new int[n-k+1];\n\tfor(int i=0; i<res.length; i++) {\n\t
Harsh__005
NORMAL
2024-10-13T04:15:51.084566+00:00
2024-10-13T04:15:51.084596+00:00
2,247
false
## **CODE**\n```Java []\npublic int[] findXSum(int[] nums, int k, int x) {\n\tint n = nums.length;\n\tint res[] = new int[n-k+1];\n\tfor(int i=0; i<res.length; i++) {\n\t\tint sum = 0;\n\t\tSet<Integer> set = new HashSet<>();\n\t\tHashMap<Integer, Integer> map = new HashMap<>();\n\t\tfor(int j=i; j < i+k; j++) {\n\t\t\tsum += nums[j];\n\t\t\tset.add(nums[j]);\n\t\t\tmap.put(nums[j], map.getOrDefault(nums[j], 0) + 1);\n\t\t}\n\n\t\tif(set.size() < x) res[i] = sum;\n\t\telse {\n\t\t\tPriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> {\n\t\t\t\tif(map.get(a) == map.get(b)) return b-a;\n\t\t\t\treturn map.get(b)-map.get(a);\n\t\t\t});\n\t\t\tfor(int ele : set) pq.add(ele);\n\t\t\tint ct = x;\n\t\t\twhile(ct-- > 0) {\n\t\t\t\tint top = pq.remove();\n\t\t\t\tres[i] += (top*map.get(top));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n```
12
0
['Java']
2
find-x-sum-of-all-k-long-subarrays-i
Freq count + 2 pointer sliding window||15 ms Beats 94.74%
freq-count-2-pointer-sliding-window15-ms-du3r
Intuition\n Describe your first thoughts on how to solve this problem. \nUse 2 pointers/sliding window to solve.\n\nOnly the testcases are small, it\'s not easy
anwendeng
NORMAL
2024-10-13T05:40:24.077847+00:00
2024-10-13T05:45:56.112566+00:00
2,080
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse 2 pointers/sliding window to solve.\n\nOnly the testcases are small, it\'s not easy.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. define a function `int x_sum( const auto& freq, int k, int x)` to compute the x-sum; the most time consuming part is the copying freq & sort.\n2. Compute ans[0], i.e x_sum for the 0th window\n3. Sliding window with moving l, r to compute x_sum for other windows\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n \\times 51 \\log 51)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(51)$\n# Code||C++ 15 ms Beats 94.74%\n```cpp []\nclass Solution {\npublic:\n using int2=pair<int, int>;\n int x_sum( const auto& freq, int k, int x){\n auto freq2=freq;// copy\n sort(freq2.begin(), freq2.end(), greater<int2>());\n int sum=0;\n for (int i=0; i<x; i++){\n auto [f, num]=freq2[i];\n if (f==0) break;\n sum+=num*f;\n }\n return sum;\n }\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n const int n=nums.size(), sz=n-k+1;\n vector<int> ans(sz);\n array<int2, 51> freq;\n freq.fill({0, 0});\n for(int r=0; r<k; r++){\n int z=nums[r];\n freq[z].second=z;\n freq[z].first++;\n }\n ans[0]=x_sum(freq, k, x);\n for(int l=1, r=k; l<sz; l++, r++){\n int L=nums[l-1], R=nums[r];\n freq[L].first--;\n freq[R].first++;\n freq[R].second = R;\n ans[l]=x_sum(freq, k, x);\n }\n return ans;\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```
8
0
['Two Pointers', 'Sliding Window', 'C++']
1
find-x-sum-of-all-k-long-subarrays-i
πŸ”₯πŸ”₯πŸ”₯ Python Simple Solution πŸ”₯πŸ”₯πŸ”₯ | sliding window + sorted list | O(n log k) Time, O(k) Space
python-simple-solution-sliding-window-so-dn2v
Intuition\ncount numbers in subarray and sort them by count and value.\nThen calculate the sum.\n\n# Solution 1 - brute force\nTime complexity: O(n k log k)\nSp
hululu0405
NORMAL
2024-10-13T04:00:36.057096+00:00
2024-10-13T04:26:52.484137+00:00
1,186
false
# Intuition\ncount numbers in subarray and sort them by count and value.\nThen calculate the sum.\n\n# Solution 1 - brute force\nTime complexity: $$O(n k log k)$$\nSpace complexity: $$O(k)$$ (not consider the answer space $$O(n$$))\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n res = []\n for i in range(len(nums) - k + 1):\n c = [[count, val] for val, count in Counter(nums[i:i + k]).items()]\n c = heapq.nlargest(x, c)\n res.append(sum(val * count for count, val in c))\n return res\n```\n\n# Intuition\nUse sliding window.\nMaintain a number `total` and a set `in_top_x`.\ncheck if the number added in sliding window will be added in our top x.\nAlso need to check if the number removed or be squeezed out of top x.\n\n# Solution 2 - sliding window + sorted list\nTime complexity: $$O(n \\log k)$$\nSpace complexity: $$O(k)$$ (not consider the answer space $$O(n$$))\n```python3 []\nfrom sortedcontainers import SortedList\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n res = []\n counter = Counter(nums[:k - 1])\n sl = SortedList(counter.keys(), key=lambda a: (-counter[a], -a))\n total = 0\n in_top_x = set()\n for i in range(min(x, len(sl))):\n total += sl[i] * counter[sl[i]]\n in_top_x.add(sl[i])\n\n for i in range(k - 1, len(nums)):\n if nums[i] in sl:\n sl.remove(nums[i])\n counter[nums[i]] += 1\n sl.add(nums[i])\n j = sl.bisect_left(nums[i])\n if j < x:\n if nums[i] in in_top_x:\n total += nums[i]\n else:\n total += nums[i] * counter[nums[i]]\n in_top_x.add(nums[i])\n if len(sl) > x and sl[x] in in_top_x:\n total -= sl[x] * counter[sl[x]]\n in_top_x.remove(sl[x])\n\n res.append(total)\n\n sl.remove(nums[i - k + 1])\n counter[nums[i - k + 1]] -= 1\n sl.add(nums[i - k + 1])\n j = sl.bisect_left(nums[i - k + 1])\n if nums[i - k + 1] in in_top_x:\n if j >= x:\n total -= nums[i - k + 1] * (counter[nums[i - k + 1]] + 1)\n in_top_x.remove(nums[i - k + 1])\n else:\n total -= nums[i - k + 1]\n if len(sl) >= x and sl[x - 1] not in in_top_x:\n total += sl[x - 1] * counter[sl[x - 1]]\n in_top_x.add(sl[x - 1])\n return res\n```
5
0
['Python3']
1
find-x-sum-of-all-k-long-subarrays-i
πŸš€ Brutal Brute Force || Java || O(n) || Sliding Window || No built-ins! ||Easy πŸŽ‰
brutal-brute-force-java-on-sliding-windo-vnin
Intuition\uD83E\uDDE0\nThe problem involves calculating the x-sum of all k-long subarrays of the input array. The x-sum considers the most frequent elements in
dheaneshwar
NORMAL
2024-10-13T04:19:29.859767+00:00
2024-10-15T14:54:17.327468+00:00
749
false
# Intuition\uD83E\uDDE0\nThe problem involves calculating the x-sum of all k-long subarrays of the input array. The x-sum considers the most frequent elements in a subarray, allowing us to track the top x most frequent elements and their counts efficiently using a **sliding window technique**.\n\n---\n\n\n# Approach\uD83D\uDEE0\uFE0F\n**Step-by-Step Breakdown \uD83D\uDD0D:**\n\n**Sliding Window Technique \uD83D\uDD04:**\nMaintain a window of size k over the array and slide it one element at a time.\nUse an array freq to count the occurrences of each number in the current window, where freq[i] represents the count of the number i.\nInitial Setup \uD83C\uDFC1:\nStart with a window containing the first k elements and populate the freq array with their counts.\nCalculate the x-sum for this initial window using a helper function find.\n\n**Window Sliding \uD83D\uDD00:**\nSlide the window to the right, updating the freq array by adding the new rightmost element and removing the leftmost element as the window shifts.\nRecompute the x-sum for each new window and store the result.\n\n**Helper Function `find` \uD83C\uDFAF Explanation:**\n\n- *Deep Copy Creation \uD83D\uDCDD:*\n - A copy of the original frequency array `f` is created to preserve the original counts for the subsequent sliding windows.\n - Two arrays are used: `freq` to store the frequencies and `nums` to store the corresponding values (from 1 to 50). This setup maintains the **mapping between numbers and their frequencies**.\n\n- *Sorting (**Insertion Sort**) \uD83D\uDCCA:*\n - The goal is to sort the `freq` array in descending order while keeping the corresponding numbers in the `nums` array synchronized.\n - This is achieved using an insertion sort:\n - For each element in the `freq` array, compare it with previous elements and shift higher frequency values to the right until the correct position for the current frequency (`key`) is found.\n - Simultaneously, the `nums` array is updated to maintain the `freq:value` pair order.\n\n- *Handling Ties Between Frequencies \u2696\uFE0F:*\n - If two elements have the same frequency, the sorting algorithm correctly places the higher-valued element first. This happens because the `nums` array is initially filled in ascending order (1 to 50), ensuring that when frequencies are equal, the value being considered in the insertion sort will always be larger than the previous one.\n - Thus, the algorithm naturally satisfies the condition where higher values are treated as more frequent when there is a tie in frequency.\n\n- *Calculating the X-Sum \uD83E\uDDEE:*\n - After sorting, the first `x` elements in the `nums` array correspond to the numbers with the highest frequencies.\n - For each of these top `x` numbers, their frequency is multiplied by the value itself, and the result is added to the sum.\n\n---\n\n\n# Complexity\uD83D\uDCCA\n- **Time complexity:**\n**Sliding Window Initialization:** Filling the frequency array for the first window takes O(k).\n**Sliding Window Update:** For each of the n - k remaining windows, updating the frequency array takes O(1).\n**Sorting in find Function:** Sorting the frequency array has a time complexity of O(51 log 51), which is effectively O(1) due to the fixed size of 51.\nAlthough each subarray\'s processing seems like O(k), the fixed frequency array length (51) allows sorting and finding the top x elements in constant time, making the overall complexity O(n).\n\n**Final Time Complexity: O(n)**\n- **Space complexity:**\n**Frequency Array:** Uses O(51) space, which is effectively O(1).\n**Result Array:** Uses O(n - k + 1) space.\n\n**Final Space Complexity: O(n)**\n\n---\n\n\n# Code (with detailed comments)\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int[] ans=new int[nums.length-k+1];\n \n int left=0;\n int right=k-1;\n int[] freq= new int[51]; //for storing the count\n for(int i=left;i<=right;i++)freq[nums[i]]++; //counted\n ans[0]=find(freq,x); //firstSubArray\'sAnswer\n \n int ind=1; //ans array pointer\n while(right<nums.length){\n right++; //next one in the array\n if(right==nums.length)break; //if reached out break\n freq[nums[right]]++; //count the incoming number\n freq[nums[left]]--; //decrement left most number\'s count\n left++; //update left\n \n ans[ind++]=find(freq,x); //find the top x for this freq\n }\n return(ans);\n }\n private int find(int[] f, int x){\n //create a deep copy of f as f needs to be preserved for next subarrays\n int[] freq= new int[51]; \n for(int i=0;i<51;i++) freq[i]=f[i]; //done\n int[] nums=new int[51];\n for(int i=0;i<51;i++)nums[i]=i; //we need a freq:value pointer, hence this array\n\n //perform any sort (used insertion below) on freq to be descending\n //while modifying freq modify corresponding num as well in the nums array\n //so the freq:value pair order is preserved\n for(int i=1;i<51;i++){\n int key=freq[i];\n int numKey=nums[i];\n int j=i-1;\n while(j>=0 && freq[j]<=key){\n freq[j+1]=freq[j];\n nums[j+1]=nums[j];\n j--;\n }\n freq[j+1]=key;\n nums[j+1]=numKey;\n }\n //in the end we get the descending order of the freq\n //along with which number\'s freq each is\n int sum=0;\n for(int i=0;i<x;i++){ //simply calculate the sum of numbers upto x elements\n sum+=(nums[i]*freq[i]); //each i in nums have repeated freq[i] times, so add that\n }\n return(sum);\n }\n}\n```\n\n---\n\n![itachi_sad_upvote.jpg](https://assets.leetcode.com/users/images/72f7adcd-adc3-4058-9f69-fe9df736734e_1728792835.1081.jpeg)\n
4
0
['Sliding Window', 'Sorting', 'Java']
1
find-x-sum-of-all-k-long-subarrays-i
Find X-Sum of All K-Long Subarrays I ->easy
find-x-sum-of-all-k-long-subarrays-i-eas-9fwj
Intuition\n Describe your first thoughts on how to solve this problem. \nwe have to store fre. of ele and have to do some operation as per fre and ele value\n\n
izer
NORMAL
2024-10-13T10:32:27.496281+00:00
2024-10-13T10:32:27.496317+00:00
318
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have to store fre. of ele and have to do some operation as per fre and ele value\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n.map to store ele. and fre.\n.use min heap to store fre. and ele as pair\n.if top ele. fre. is same as coming ele fre then compare ele. and put larger value ele in heap\n.simple one multiply fre. with ele. and push in vector.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2 + NlogX + X)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N + X + K)\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int>ans;\n int n=nums.size();\n for(int i=0;i<n-k+1;i++){\n map<int,int>mp;//ele. and fre.\n for(int j=i;j<=i+k-1;j++){\n mp[nums[j]]++;\n }\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;//min heap storing pair of fre and ele\n for(auto ele:mp){\n if((!pq.empty() and pq.size()>=k) and pq.top().first==ele.second){// if top ele. fre. is same as coming ele fre then compare ele. and put larger value ele in heap\n if(pq.top().second<ele.first){\n pq.pop();\n // pq.push({ele.second,ele.first});\n }\n }\n pq.push({ele.second,ele.first});\n if(pq.size()>x) pq.pop();\n\n }\n\n int sum=0;\n while(!pq.empty()){//simple one multiply fre. with ele. and push in vector.\n sum+=(pq.top().first*pq.top().second);\n pq.pop();\n }\n \n ans.push_back(sum);\n }\n return ans; \n }\n};\n```
3
0
['C++']
1
find-x-sum-of-all-k-long-subarrays-i
Basic solution for beginners!!
basic-solution-for-beginners-by-errorner-al36
Intuition\nBreak Down the Problem into Subarrays \uD83D\uDD04:\n\nWe slide through the array nums using a window of size k. This allows us to look at all possib
GeekDork
NORMAL
2024-10-13T08:49:31.334552+00:00
2024-10-13T08:49:31.334600+00:00
138
false
# Intuition\nBreak Down the Problem into Subarrays \uD83D\uDD04:\n\nWe slide through the array nums using a window of size k. This allows us to look at all possible contiguous subarrays of length k.\nFor each of these subarrays, we need to determine the most frequent elements and sum up the top x of them.\nTrack Frequency of Elements in Each Subarray \uD83D\uDCCA:\n\nFor each subarray, we keep track of how often each number appears using a HashMap.\nThis helps us know the frequency of each element quickly.\nUse a Priority Queue (Max-Heap) for the Most Frequent Elements \uD83C\uDF1F:\n\nOnce we have the frequency of each element in the current subarray, we want to find the top x most frequent ones.\nWe use a max-priority queue (PriorityQueue) to efficiently sort and extract these elements based on:\nFrequency: Elements with higher frequency come first.\nValue: If two elements have the same frequency, the larger value is prioritized.\nCompute the Weighted Sum of the Top x Elements \u2795:\n\nWe extract the top x elements from the priority queue, multiply each by its frequency (to consider all its occurrences), and sum them up.\nThis sum represents the desired value for the current subarray.\nStore and Return the Results \uD83D\uDCDD:\n\nWe store the computed sum for each subarray in the result array res, and once all subarrays are processed, we return the array.\n\n# Approach\nEfficient Frequency Counting: Using a HashMap ensures that we quickly get the frequency of each element in the subarray.\nPriority Queue Optimization: By using a max-heap, we efficiently get the top x elements without needing to fully sort all entries, making the solution faster.\nSliding Window: The approach of iterating through each possible subarray ensures that we explore all parts of the array, giving a complete and accurate result.\n\n# Complexity\nTime Complexity: O(n * (k + x log k))\nExplanation: For each of the n - k + 1 subarrays, we perform operations that take O(k + x log k) time.\n\nSpace Complexity: O(n + k)\nExplanation: We store the result in an array of size O(n) and use auxiliary data structures (HashMap and PriorityQueue) that take up O(k) space per iteration.\n\n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n int[] res = new int[n-k+1];\n for(int i=0;i<=n-k;i++){\n HashMap<Integer,Integer> map = new HashMap<>();\n\n for(int j=i;j<i+k;j++){\n map.put(nums[j] , map.getOrDefault(nums[j],0)+1);\n }\n\n PriorityQueue<Map.Entry<Integer,Integer>> pq = new PriorityQueue<>((a,b)->{\n if(a.getValue() != b.getValue()){\n return b.getValue() - a.getValue();\n }\n return b.getKey() - a.getKey();\n });\n\n pq.addAll(map.entrySet());\n \n\n int sum = 0;\n for(int j=0;j<x && !pq.isEmpty();j++){\n Map.Entry<Integer,Integer> e = pq.poll();\n sum += e.getKey()*e.getValue();\n }\n res[i] = sum;\n }\n return res;\n }\n}\n```
3
0
['Hash Table', 'Heap (Priority Queue)']
0
find-x-sum-of-all-k-long-subarrays-i
βœ… One Line Solution
one-line-solution-by-mikposp-7mbr
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\nTime complexity: O(n^2). Space complexity: O(n).
MikPosp
NORMAL
2024-10-21T22:09:42.295235+00:00
2024-10-22T07:57:46.819969+00:00
508
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```python3\nclass Solution:\n def findXSum(self, a: List[int], k: int, x: int) -> List[int]:\n return [sum(map(prod,nlargest(x,Counter(a[i:i+k]).items(),lambda q:q[::-1]))) for i in range(len(a)-k+1)]\n```
2
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Python', 'Python3']
2
find-x-sum-of-all-k-long-subarrays-i
It is NOT an easy problem to solve. Using Sliding window, Priority queue
it-is-not-an-easy-problem-to-solve-using-m5eu
Code\njavascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findXSum = function (nums, k, x
bossnu1204
NORMAL
2024-10-14T07:57:12.245146+00:00
2024-10-14T07:57:12.245169+00:00
240
false
# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findXSum = function (nums, k, x) {\n // Initialize values\n // Answer, array is sliding window,\n // memo is where the frequency of occurrence of numbers is stored\n // compare is a function that compares the frequency of\n // occurrence of numbers in the sliding window. If the frequency\n // is the same, it will compare which number is larger.\n let answer = new Array(nums.length - k + 1).fill(0)\n let array\n let memo = {}\n let compare = ((a, b) => {\n if (memo[a] != memo[b]) {\n return memo[b] - memo[a]\n }\n return b - a\n })\n\n\n // Fill each element into the answer array\n for (let i = 0; i < answer.length; i++) {\n\n // [START] sliding window\n if (i == 0) {\n array = nums.slice(0, k)\n for (let ar of array) {\n memo[ar] = (memo[ar] || 0) + 1\n }\n } else {\n let elDel = array.shift()\n let elInsert = nums[i + k - 1]\n array.push(elInsert)\n memo[elDel] -= 1\n memo[elInsert] = (memo[elInsert] || 0) + 1\n }\n // [END] sliding window\n\n // use PriorityQueue to sort\n let priority = new PriorityQueue({ compare })\n for (let key in memo) {\n priority.enqueue(key)\n }\n\n // Use PriorityQueue to get the most frequent numbers from\n // largest to smallest for calculation\n let ans = 0\n for (let j = 0; j < x; j++) {\n let el = priority.dequeue()\n if (el) {\n ans += memo[el] * el\n }\n }\n answer[i] = ans\n }\n return answer\n};\n```
2
0
['JavaScript']
2
find-x-sum-of-all-k-long-subarrays-i
Day 329 Problem 2 Solved
day-329-problem-2-solved-by-lakshya311-10cx
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# Code\npython3 []\nc
lakshya311
NORMAL
2024-10-13T10:31:18.918081+00:00
2024-10-13T10:31:18.918109+00:00
344
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# Code\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n res = []\n for i in range(len(nums) - k + 1):\n c = [[count, val] for val, count in Counter(nums[i : i + k]).items()]\n c = heapq.nlargest(x, c)\n res.append(sum(val * count for count, val in c))\n return res\n\n```
2
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Priority queue with compared second element ..
priority-queue-with-compared-second-elem-gd6a
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
CodeRizzler99
NORMAL
2024-10-13T10:26:22.657330+00:00
2024-10-13T10:26:22.657360+00:00
208
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 []\nstruct Compare {\n bool operator()(pair<int, int>& a, pair<int, int>& b) {\n if (a.second == b.second) {\n return a.first < b.first;\n }\n return a.second < b.second;\n }\n};\nclass Solution {\npublic:\n\n\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n \n int n = nums.size();\n vector<int> answer(n - k + 1);\n unordered_map<int, int> freqMap;\n\n for (int i = 0; i < k; ++i) {\n freqMap[nums[i]]++;\n }\n\n auto computeXSum = [&](unordered_map<int, int>& freqMap) -> int {\n priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;\n\n for (auto& entry : freqMap) {\n pq.push(entry);\n }\n\n int sum = 0;\n int count = 0;\n\n while (!pq.empty() && count < x) {\n auto [val, freq] = pq.top();\n pq.pop();\n sum += val * freq;\n count++;\n }\n\n return sum;\n };\n\n answer[0] = computeXSum(freqMap);\n\n for (int i = 1; i <= n - k; ++i) {\n int leftElem = nums[i - 1];\n freqMap[leftElem]--;\n if (freqMap[leftElem] == 0) {\n freqMap.erase(leftElem);\n }\n\n int newElem = nums[i + k - 1];\n freqMap[newElem]++;\n\n answer[i] = computeXSum(freqMap);\n }\n\n return answer;\n }\n};\n```
2
0
['Hash Table', 'Heap (Priority Queue)', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
Brute force using Priority Queue and HashMap
brute-force-using-priority-queue-and-has-o17n
Intuition\n\n# Approach\nfor every subarray define your hashmap and priority queue.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n
kanishka1
NORMAL
2024-10-13T04:37:04.450687+00:00
2024-10-13T04:37:04.450718+00:00
214
false
# Intuition\n\n# Approach\nfor every subarray define your hashmap and priority queue.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n= nums.length;\n int[] ans = new int[n - k + 1];\n for (int i = 0; i < n - k + 1; i++) {\n ans[i] = getSum(nums, i, i + k - 1, x);\n }\n return ans;\n }\n public int getSum(int[] nums, int start, int end, int x) {\n HashMap<Integer, Integer> hm = new HashMap<>();\n for (int i = start; i <= end; i++) {\n hm.put(nums[i], hm.getOrDefault(nums[i], 0) + 1);\n }\n PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(\n (a, b) -> (b.getValue() == a.getValue())?b.getKey()-a.getKey() :b.getValue() - a.getValue());\n for (Map.Entry<Integer, Integer> entry : hm.entrySet()) {\n pq.add(entry);\n }\n int sum = 0;\n while (x-- > 0 && !pq.isEmpty()) {\n Map.Entry<Integer, Integer> e = pq.poll();\n sum += e.getKey() * e.getValue();\n }\n return sum;\n }\n}\n```
2
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
JAVA | Sliding Window | Sort 2D array
java-sliding-window-sort-2d-array-by-cg1-ekbe
Intuition\nThe data range is [1, 50], we can use a 2D array to store the number and its frequency.\n\nWhen calculate the sum, sort the 2D array on frequency. Re
cg1319
NORMAL
2024-10-13T04:17:56.188361+00:00
2024-10-13T04:27:21.158849+00:00
538
false
# Intuition\nThe data range is [1, 50], we can use a 2D array to store the number and its frequency.\n\nWhen calculate the sum, sort the 2D array on frequency. Remember to sort again by number for the following processing.\n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n int[] res = new int[n - k + 1];\n int[][] freq = new int[51][2];\n // store the number in 2D array\n for (int i = 0; i < 51; i++)\n \tfreq[i][0] = i;\n // count the frequency of the first k numbers\n for (int i = 0; i < k; i++)\n \tfreq[nums[i]][1]++;\n res[0] = sum(freq, x);\n // sliding window\n for (int i = 1, j = k; j < n; i++, j++) {\n \tfreq[nums[i - 1]][1]--;\n \tfreq[nums[j]][1]++;\n \tres[i] = sum(freq, x);\n }\n return res;\n }\n int sum(int[][] freq, int x) {\n \tArrays.sort(freq, (a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]);\n \tint sum = 0;\n \tfor (int i = 0; i < x; i++)\n \t\tsum += freq[i][0] * freq[i][1];\n Arrays.sort(freq, (a, b) -> a[0] - b[0]);\n \treturn sum;\n }\n}\n```
2
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
100% Beat Java Simple Solution
100-beat-java-simple-solution-by-shree_g-7ug9
Complexity\n- Time complexity:O(n(i+k)sorting*x)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n Add your space complexity here, e.g. O(n)
Shree_Govind_Jee
NORMAL
2024-10-13T04:03:44.718496+00:00
2024-10-13T04:03:44.718532+00:00
1,326
false
# Complexity\n- Time complexity:$$O(n*(i+k)*sorting*x)$$\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 Pair{\n int first;\n int second;\n \n public Pair(int first, int second){\n this.first = first;\n this.second = second;\n }\n}\n\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n \n int[] ans = new int[n-k+1];\n for(int i=0; i<n-k+1; i++){\n Map<Integer, Integer> map = new HashMap<>();\n for(int j=i; j<i+k; j++){\n map.put(nums[j], map.getOrDefault(nums[j], 0)+1);\n }\n \n List<Pair> list = new ArrayList<>();\n for(int key:map.keySet()){\n list.add(new Pair(map.get(key), key));\n }\n Collections.sort(list, (Pair a, Pair b)->{\n if(a.first==b.first){\n return b.second-a.second;\n }\n return b.first-a.first;\n });\n \n int sum = 0;\n int uniq = 0;\n for(Pair l:list){\n if(uniq >= x){\n break;\n }\n \n sum += l.first*l.second;\n uniq++;\n }\n ans[i]=sum;\n }\n return ans;\n }\n}\n```
2
0
['Array', 'Hash Table', 'Math', 'Sorting', 'Hash Function', 'Java']
1
find-x-sum-of-all-k-long-subarrays-i
Solution using dictionary and sorting
solution-using-dictionary-and-sorting-by-m265
Code
M-VIMAL
NORMAL
2025-03-12T04:28:50.284523+00:00
2025-03-12T04:28:50.284523+00:00
128
false
# Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: ans = [] left = 0 for i in range(len(nums)+1): dic = {} if(i>=k): sub = nums[left:i] valcount = 0 single = 0 sol = [] singlelements = [] for j in sub: dic[j] = dic.get(j,0)+1 for val,count in dic.items(): if(count >=x ): valcount+=1 sol.append((val*count,count)) if(count<x): single+=1 singlelements.append((val*count,count)) sol.sort(reverse = True,key = lambda x:(x[1],x[0])) singlelements.sort(reverse = True , key = lambda x:(x[1],x[0])) diff = x - len(singlelements) if(len(sol)>=x): ans.append(sum(tup[0] for tup in sol[:x])) elif(len(sol) < x and len(singlelements) >= diff): ans.append(sum(tupp[0] for tupp in sol[:x])+ sum(tuple[0] for tuple in singlelements[:x-len(sol)])) else: ans.append(sum(sub)) left+=1 return ans ```
1
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Javascript
javascript-by-davidchills-zrw4
Code
davidchills
NORMAL
2025-02-14T19:26:51.613078+00:00
2025-02-14T19:26:51.613078+00:00
48
false
# Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @param {number} x * @return {number[]} */ var findXSum = function(nums, k, x) { const result = []; for (let i = 0; i <= nums.length - k; i++) { const subarray = nums.slice(i, i + k); const freqMap = new Map(); // Count occurrences for (const num of subarray) { freqMap.set(num, (freqMap.get(num) || 0) + 1); } // Convert map to array and sort by frequency and value const sorted = Array.from(freqMap.entries()).sort((a, b) => { if (b[1] === a[1]) return b[0] - a[0]; // Sort by value if frequency is equal return b[1] - a[1]; // Sort by frequency }); // Take top x most frequent elements const topX = sorted.slice(0, x); // Calculate sum const sum = topX.reduce((acc, [num, freq]) => acc + num * freq, 0); result.push(sum); } return result; }; ```
1
0
['JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
PHP
php-by-davidchills-ymjx
Code
davidchills
NORMAL
2025-02-14T19:21:01.447875+00:00
2025-02-14T19:21:01.447875+00:00
8
false
# Code ```php [] class Solution { /** * @param Integer[] $nums * @param Integer $k * @param Integer $x * @return Integer[] */ function findXSum($nums, $k, $x) { $n = count($nums); $answer = []; // Process each subarray of length k for ($i = 0; $i <= $n - $k; $i++) { $sub = array_slice($nums, $i, $k); // Count occurrences $counts = array_count_values($sub); // Sort by frequency descending, then by value descending uksort($counts, function($a, $b) use ($counts) { if ($counts[$a] == $counts[$b]) { return $b - $a; // Higher value first if frequency is the same } return $counts[$b] - $counts[$a]; // Higher frequency first }); // Take the top x frequencies $sum = 0; $count = 0; foreach ($counts as $num => $freq) { $sum += $num * $freq; $count++; if ($count == $x) break; } $answer[] = $sum; } return $answer; } } ```
1
0
['PHP']
0
find-x-sum-of-all-k-long-subarrays-i
AAAAAAAAAAAAAAAAAA
aaaaaaaaaaaaaaaaaa-by-danisdeveloper-zzts
Code
DanisDeveloper
NORMAL
2025-01-07T22:04:54.883405+00:00
2025-01-07T22:04:54.883405+00:00
48
false
# Code ```kotlin [] class Solution { fun findXSum(nums: IntArray, k: Int, x: Int): IntArray { val n = nums.size val result = IntArray(n - k + 1) { 0 } for (i in 0..n - k) { val map = HashMap<Int, Int>() nums.drop(i).take(k).forEach { map[it] = map.getOrDefault(it, 0) + 1 } result[i] = map .toList() .sortedWith(compareBy({ it.second }, { it.first })) .takeLast(x) .sumOf { it.second * it.first } } return result } } ```
1
0
['Kotlin']
0
find-x-sum-of-all-k-long-subarrays-i
Find X-Sum of All K-Long Subarrays I | Sliding Window + Mapping + No Sorting | Detailed Explanation
find-x-sum-of-all-k-long-subarrays-i-sli-ctpn
Approach Map the frequency of each elements. If it has duplicate, get the maximum frequency. Get the highest index with frequency if not. Add the product of (fr
SRNM21
NORMAL
2024-12-26T17:54:25.059189+00:00
2024-12-27T17:23:26.223190+00:00
289
false
# Approach 1. Map the frequency of each elements. 2. If it has duplicate, get the maximum frequency. Get the highest index with frequency if not. 3. Add the product of (frequency * index + 1) to the answers array. # Complexity - Time complexity (***99.08%***): $$O(Nβˆ—K)$$ - Space complexity (***90.79%***): $$O(1)$$ # Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] freqMap = new int[50]; int[] ans = new int[n - k + 1]; int tempMax = 0; int max = 0; boolean dup = false; for (int i = 0; i < n - k + 1; i++) { freqMap = new int[50]; // Frequency Map max = 0; // Map each frequency of elements and store the maximum element for (int j = i; j < i + k; j++) { freqMap[nums[j] - 1]++; if (nums[j] > max) max = nums[j]; } // Loop 'x' times for (int z = x; z > 0; z--) { tempMax = max - 1; dup = false; // Check for duplicates (Greater than 1 frequency) for (int f : freqMap) { if (f > 1) { dup = true; break; } } // Iterate through frequency map starting from the end for easier access to highest indeces for (int j = freqMap.length - 1; j >= 0; j--) { if (freqMap[j] == 0) continue; // Skip all 0 frequency if (dup) { // If flagged duplicate, get the highest frequency index if (freqMap[j] > freqMap[tempMax]) tempMax = j; } else { // If not flagged duplicate, get the highest index with frequency tempMax = j; break; } } // Add the total to the answers array // (element * index + 1) ans[i] += (freqMap[tempMax] * (tempMax + 1)); freqMap[tempMax] = 0; // Remove used frequency } } return ans; } } ``` ![upvote.jpg](https://assets.leetcode.com/users/images/36182cee-a274-468a-b01e-e73ac3476123_1735235719.0732708.jpeg)
1
0
['Array', 'Hash Table', 'Sliding Window', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
C++ transform_reduce
c-transform_reduce-by-michelusa-4wig
Calculate frequency, sort then apply transform/reduce\n\n# Code\ncpp []\nclass Solution {\n\npublic:\n vector<int> findXSum(const vector<int>& nums, const in
michelusa
NORMAL
2024-11-29T13:22:56.048096+00:00
2024-11-29T13:22:56.048137+00:00
37
false
Calculate frequency, sort then apply transform/reduce\n\n# Code\n```cpp []\nclass Solution {\n\npublic:\n vector<int> findXSum(const vector<int>& nums, const int k, const int x) {\n std::vector<int> res;\n for (int i = 0; i < nums.size() - k + 1; ++i) {\n\n unordered_map<int, int> freq;\n for (int j = i; j != i + k && j < nums.size(); ++j) {\n freq[nums[j]]++;\n }\n\n std::vector<std::pair<int, int>> pick;\n for (const auto [k, v] : freq) {\n pick.push_back({v, k});\n }\n std::sort(rbegin(pick), rend(pick));\n const int size = std::min(x, (int)pick.size());\n const int sum = std::transform_reduce(\n begin(pick), begin(pick) + size, 0, std::plus<>(),\n [](const auto item) { return item.first * item.second; });\n\n res.push_back(sum);\n }\n\n return res;\n }\n};\n```
1
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
C++
c-by-tinachien-2pf5
\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int>rets;\n for(int i = 0; i + k <= nums.size();
TinaChien
NORMAL
2024-10-21T15:15:07.303389+00:00
2024-10-21T15:15:07.303427+00:00
54
false
```\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int>rets;\n for(int i = 0; i + k <= nums.size(); i++)\n rets.push_back( helper(nums, k, x, i) );\n return rets;\n }\n int helper(vector<int>& nums, int k, int x, int idx){\n unordered_map<int, int>Map;\n priority_queue<pair<int, int>>pq;\n for(int i = 0; i < k; i++){\n Map[nums[idx + i]]++;\n }\n for(auto [key, count] : Map){\n pq.push({count, key});\n }\n int ret = 0;\n int items = 0;\n while(items < x && !pq.empty()){\n ret += pq.top().second * pq.top().first;\n pq.pop();\n items++;\n }\n return ret;\n }\n};\n```
1
0
[]
0
find-x-sum-of-all-k-long-subarrays-i
Intuitive Hash Map
intuitive-hash-map-by-brandoncossin-pfzr
Approach\nBrute Force Method\nCapture each number in a hash map (defaultdict)\nSort the hashmap by occurances, or the higher value and cap it with the limit\nTh
brandoncossin
NORMAL
2024-10-14T01:04:40.797515+00:00
2024-10-14T01:04:40.797535+00:00
43
false
# Approach\nBrute Force Method\nCapture each number in a hash map (defaultdict)\nSort the hashmap by occurances, or the higher value and cap it with the limit\nThen do the map and push to a new array\n# Complexity\n- Time complexity: O(N\u2217K\u2217Log(K))\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n ansArray=[]\n for i in range(len(nums)-k+1):\n ans = defaultdict(int)\n newNum=0\n for j in range(i, i+k):\n ans[nums[j]]+=1\n ansList = sorted(ans.items(), key=lambda x:(x[1], x[0]), reverse=True)[:x]\n for i in ansList:\n newNum+=i[0]*i[1]\n ansArray.append(newNum)\n return ansArray\n```
1
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
BEST PYTHON SOLUTION WITH 84MS OF RUNTIME !
best-python-solution-with-84ms-of-runtim-6uls
\n# Code\npython3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n from collections import Counter\n i
rishabnotfound
NORMAL
2024-10-13T10:44:12.454612+00:00
2024-10-13T10:44:12.454647+00:00
430
false
\n# Code\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n from collections import Counter\n import heapq\n \n def x_sum(subarray):\n freq = Counter(subarray)\n # Get the top x most frequent elements\n most_common = heapq.nlargest(x, freq.items(), key=lambda item: (item[1], item[0]))\n # Sum of the elements, keeping only top x frequent ones\n result = sum(value * count for value, count in most_common)\n return result\n\n result = []\n for i in range(len(nums) - k + 1):\n subarray = nums[i:i + k]\n result.append(x_sum(subarray))\n\n return result\n\n```
1
0
['Python3']
1
find-x-sum-of-all-k-long-subarrays-i
1-line Linq
1-line-linq-by-3s_akb-ncei
\n# Code\ncsharp []\npublic class Solution {\n public int[] FindXSum(int[] nums, int k, int x) {\n return Enumerable.Range(0, nums.Length - k + 1).Sel
3S_AKB
NORMAL
2024-10-13T10:11:44.174034+00:00
2024-10-13T10:11:44.174057+00:00
61
false
\n# Code\n```csharp []\npublic class Solution {\n public int[] FindXSum(int[] nums, int k, int x) {\n return Enumerable.Range(0, nums.Length - k + 1).Select(i => nums.Skip(i).Take(k).GroupBy(v => v).OrderBy(v => -v.Count()).ThenBy(v => -v.Key).Take(x).Sum(v => v.Key * v.Count())).ToArray();\n }\n}\n```
1
0
['C#']
0
find-x-sum-of-all-k-long-subarrays-i
Brute force
brute-force-by-mahesh_pokale99-3yyw
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
Mahesh_pokale99
NORMAL
2024-10-13T09:53:03.909388+00:00
2024-10-14T02:30:51.259219+00:00
48
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 vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int>ans;\n unordered_map<int,int>map;\n int n=0;\n int start=0,end=0;\n while(end<nums.size()){\n map[nums[end]]++;\n n++;\n if(n==k){\n vector<pair<int,int>>temp;\n for(auto ele : map) temp.push_back({ele.first, ele.second});\n for(int i=0; i<temp.size(); i++){\n for(int j=0; j<temp.size()-1-i; j++){\n if(temp[j].second==temp[j+1].second && temp[j].first<temp[j+1].first) swap(temp[j],temp[j+1]);\n else if(temp[j].second<temp[j+1].second) swap(temp[j],temp[j+1]);\n }\n }\n for(auto ele : temp) cout<<ele.first<<" "<<ele.second<<endl;\n int sum=0;\n for(int i=0,j=0; i<temp.size() && j<x; i++,j++){\n sum+=temp[i].first*temp[i].second;\n }\n ans.push_back(sum);\n n--;\n map[nums[start]]--;\n if(map[nums[start]]==0) map.erase(nums[start]);\n start++;\n }\n end++;\n }\n return ans;\n }\n};\n```
1
0
['Ordered Map', 'Sliding Window', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
Easiest Solution beats 100 percent
easiest-solution-beats-100-percent-by-su-v593
Intuition\n Describe your first thoughts on how to solve this problem. \nWe basically create a function to solve the x sum with the given conditions and we use
suhaas001
NORMAL
2024-10-13T09:21:06.467015+00:00
2024-10-13T09:21:06.467039+00:00
173
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe basically create a function to solve the x sum with the given conditions and we use the x sum function for the sub array\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we create a dictionary for the mapping to calculate the frequency and then we take the frequecy and the element as pairs and put in list this inner list is reversed such that the first index will be the frequency and second element will be the term itself. \nNext we sort and reverse. Now we have the final list with x first frequent terms.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*k)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```python []\nclass Solution(object):\n def findXSum(self, nums, k, x):\n """\n :type nums: List[int]\n :type k: int\n :type x: int\n :rtype: List[int]\n """\n \n def x_sum(arr,x):\n if (len(list(set(arr))) < x):\n return arr\n d = {}\n for i in arr:\n d[i] = arr.count(i)\n res = []\n for i in d.keys():\n res.append([d[i],i])\n res.sort()\n res.reverse()\n f_res = []\n for i in range(x):\n for j in range(res[i][0]):\n f_res.append(res[i][1])\n return f_res\n n = len(nums)\n des = []\n for i in range(n-k+1):\n des.append(sum(x_sum(nums[i:i+k],x)))\n return des\n\n \n```
1
0
['Python']
1
find-x-sum-of-all-k-long-subarrays-i
🚨 C++ || Map Sort Calculate || O(n)
c-map-sort-calculate-on-by-t86-lgzu
Intuition\n- Index value to count\n- Reverse index count to value\n- Calculate top\n\nCode\nc++\nvector<int> findXSum(vector<int>& nums, int k, int upto) {\n
t86
NORMAL
2024-10-13T09:11:08.920028+00:00
2024-10-16T03:47:51.333031+00:00
73
false
**Intuition**\n- Index value to count\n- Reverse index count to value\n- Calculate top\n\n**Code**\n```c++\nvector<int> findXSum(vector<int>& nums, int k, int upto) {\n int n = nums.size();\n vector<int> res; k--;\n \n map<int, int> track;\n auto get_sum = [&]() {\n vector<pair<int, int>> r;\n for (auto [x, count]: track) r.emplace_back(count, x);\n sort(r.begin(), r.end(), greater<pair<int, int>>());\n \n int sum = 0;\n for (auto j = 0; j < min( (int) r.size(), upto); j++) \n sum += r[j].first * r[j].second;\n return sum;\n };\n \n for (auto i = 0; i < n; i++) {\n track[nums[i]]++;\n if (i >= k) \n res.push_back(get_sum()),\n track[nums[i - k]]--;\n }\n return res;\n}\n```\n\n**Complexity**\n`Time`: O(nlogn)\n`Space`: O(n)\n\n**For more solutions and concepts, check out this \uD83D\uDCD6 [BLOG](https://github.com/MuhtasimTanmoy/notebook) and \uD83C\uDFC6 [GITHUB REPOSITORY](https://github.com/MuhtasimTanmoy/playground) with over 2000+ solutions.**
1
0
[]
1
find-x-sum-of-all-k-long-subarrays-i
Beats 100%
beats-100-by-aniket_raut-2nql
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem asks to calculate the "x-sum" of each k-length subarray. The x-sum is deriv
Aniket_Raut
NORMAL
2024-10-13T07:25:54.771686+00:00
2024-10-13T07:25:54.771719+00:00
136
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks to calculate the "x-sum" of each k-length subarray. The x-sum is derived by keeping the most frequent elements, considering the higher value in case of ties.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through each subarray of length k.\n2. For each subarray:\n- Count the frequency of each element.\n- Use a max heap (priority queue) to keep the top x most frequent elements.\n- Calculate the sum of those elements.\n3. Store the x-sum result for each subarray in the final output array.\n# Complexity\n- Time complexity:\n- O(n * k * log k) due to subarray creation and heap operations.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(k) for the frequency map and heap.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n int[] result = new int[n - k + 1];\n\n for (int i = 0; i <= n - k; i++) {\n int[] subarray = Arrays.copyOfRange(nums, i, i + k);\n result[i] = calculateXSum(subarray, x);\n }\n\n return result;\n }\n\n private int calculateXSum(int[] subarray, int x) {\n Map<Integer, Integer> frequencyMap = new HashMap<>();\n for (int num : subarray) {\n frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);\n }\n\n PriorityQueue<int[]> maxHeap = new PriorityQueue<>(\n (a, b) -> a[1] != b[1] ? b[1] - a[1] : b[0] - a[0]\n );\n\n for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {\n maxHeap.offer(new int[] {entry.getKey(), entry.getValue()});\n }\n\n int sum = 0;\n for (int i = 0; i < x && !maxHeap.isEmpty(); i++) {\n int[] top = maxHeap.poll();\n sum += top[0] * top[1];\n }\n return sum;\n }\n}\n```
1
0
['Array', 'Hash Table', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
πŸ’‘βœ…πŸ”₯ Sliding window with map + detailed explanation
sliding-window-with-map-detailed-explana-cn8h
Intuition\nThis task takes some time to interpret the requirements but basically it\'s easy.\n\n# Approach\n- Consider subarrays with sliding window within i..(
jekatigr
NORMAL
2024-10-13T04:29:02.485775+00:00
2024-10-13T04:29:02.485798+00:00
97
false
# Intuition\nThis task takes some time to interpret the requirements but basically it\'s easy.\n\n# Approach\n- Consider subarrays with sliding window within $$i..(i+k-1)$$ indexes\n- For each subarray:\n - calculate numbers occurance\n - sort by occurance, then by number value\n - make product-sum within top `x` occurances\n\n# Complexity\n- Time complexity:\n$$O(n * k)$$ for sliding window\n$$O(n * logn)$$ for sorting occurances\n$$O(n * x)$$ for summarizing the result\n\nOverall: $$O(n * (k + logn + x))$$\n\n\n- Space complexity:\n$$O(n)$$ for occurances\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findXSum = function(nums, k, x) {\n const ans = [];\n\n for (let i = 0; i < nums.length - k + 1; i++) {\n const map = {};\n\n // counting occurances\n for (let j = i; j <= i + k - 1 && j < nums.length; j++) {\n if (!map[nums[j]]) {\n map[nums[j]] = 0;\n }\n\n map[nums[j]] += 1;\n }\n\n // sort\n const entries = Object.entries(map);\n\n entries.sort((e1,e2) => {\n if (e2[1] !== e1[1]) {\n return e2[1] - e1[1];\n }\n\n return e2[0] - e1[0];\n });\n\n // calculating top x sum\n let sum = 0;\n\n for (let p = 0; p < x && p < entries.length; p++) {\n sum += +entries[p][0] * +entries[p][1];\n }\n\n ans.push(sum);\n }\n\n return ans;\n};\n```
1
0
['Array', 'Hash Table', 'Sliding Window', 'Sorting', 'JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
brute force
brute-force-by-_dharamvir-5fhk
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
_dharamvir__
NORMAL
2024-10-13T04:07:44.311730+00:00
2024-10-13T04:21:31.419093+00:00
433
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\nint solve(map<int,int>&mp,int x){\n vector<pair<int,int>>ans; //freq ,element storing \n for(auto &i:mp){\n ans.push_back({i.second,i.first}); \n }\n\n int res=0;\n auto cmp=[](auto a,auto b){\n if(a.first==b.first)return a.second>b.second;\n return a.first>b.first; \n };\n sort(ans.begin(),ans.end(),cmp);//costum sort\n \n for(int i=0;i<ans.size();i++){\n \n res+=(ans[i].first)*ans[i].second;\n x-=1;//decrease x every times\n if(x==0)break;\n }\n return res;\n}\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n int n=nums.size();\n\n vector<int>ans(n-k+1);\n for(int i=0;i<n-k+1;i++){\n map<int,int>mp;\n //calculating freq\n for(int j=i;j<k+i;j++){ \n mp[nums[j]]++;\n } \n int f=solve(mp,x);\n ans[i]=f;\n }\n return ans;\n }\n};\n```
1
0
['Hash Table', 'Ordered Map', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
Easy to understand C++ Solution
easy-to-understand-c-solution-by-rajvir_-deyw
Complexity\n- Time complexity: O(n*x(log m))\n\n- Space complexity: O(m)\n\n# Code\ncpp []\nclass Solution {\nprivate:\n int f(int x, unordered_map<int,int>
rajvir_singh
NORMAL
2024-10-13T04:06:47.317011+00:00
2024-10-13T04:08:11.655114+00:00
427
false
# Complexity\n- Time complexity: O(n*x(log m))\n\n- Space complexity: O(m)\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n int f(int x, unordered_map<int,int> &mp){\n priority_queue<pair<int,int>> pq;\n for(auto &it: mp) pq.push({it.second, it.first});\n int ans = 0;\n while(!pq.empty() && x != 0){\n int val = pq.top().second;\n int freq = pq.top().first;\n pq.pop();\n ans += (val*freq);\n x--;\n }\n return ans;\n }\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int> ans;\n int n = nums.size();\n unordered_map<int,int> mp;\n for(int i = 0; i < k; i++){\n mp[nums[i]]++;\n }\n ans.push_back(f(x, mp));\n for(int i = k; i < n; i++){\n mp[nums[i-k]]--;\n if(mp[nums[i-k]] == 0) mp.erase(nums[i-k]);\n mp[nums[i]]++;\n ans.push_back(f(x, mp));\n }\n return ans;\n }\n};\n```
1
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
Java Map & Priority Queue Solution
java-map-priority-queue-solution-by-solv-0ksv
\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int[] result = new int[nums.length - k + 1];\n for (int i = 0; i < num
solved
NORMAL
2024-10-13T04:01:05.322687+00:00
2024-10-13T04:01:05.322717+00:00
317
false
```\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int[] result = new int[nums.length - k + 1];\n for (int i = 0; i < nums.length - k + 1; i++) {\n result[i] = getSum(nums, i, i + k - 1, x);\n }\n return result;\n }\n public int getSum(int[] nums, int start, int end, int x) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i = start; i <= end; i++) {\n map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);\n }\n PriorityQueue<Pair<Integer, Integer>> priorityQueue = new PriorityQueue<Pair<Integer, Integer>>((a, b) -> {\n if (a.getValue() == b.getValue()) {\n return -Integer.compare(a.getKey(), b.getKey());\n }\n return -Integer.compare(a.getValue(), b.getValue());\n });\n for (Map.Entry<Integer, Integer> entry : map.entrySet()) {\n priorityQueue.offer(new Pair(entry.getKey(), entry.getValue()));\n }\n int sum = 0;\n while (x > 0 && !priorityQueue.isEmpty()) {\n Pair<Integer, Integer> pair = priorityQueue.poll();\n sum = sum + pair.getKey() * pair.getValue();\n x--;\n }\n return sum;\n }\n}\n```
1
0
['Heap (Priority Queue)', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
Java Easy Solution Explained
java-easy-solution-explained-by-tbekpro-pw78
Code
tbekpro
NORMAL
2025-04-09T00:47:23.947413+00:00
2025-04-09T00:47:23.947413+00:00
2
false
# Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int[] result = new int[nums.length - k + 1]; for (int i = 0; i < result.length; i++) { result[i] = findSum(nums, i, i + k, x); } return result; } private int findSum(int[] nums, int i, int j, int x) { Map<Integer, Integer> map = new HashMap<>(); for (int k = i; k < j; k++) { map.put(nums[k], map.getOrDefault(nums[k], 0) + 1); } PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> a.freq == b.freq ? a.val - b.val : a.freq - b.freq); for (int key : map.keySet()) { pq.offer(new Pair(key, map.get(key))); if (pq.size() > x) pq.poll(); } int sum = 0; while (pq.size() > 0) { Pair p = pq.poll(); sum += p.freq * p.val; } return sum; } class Pair { int val, freq; public Pair(int v, int f) { val = v; freq = f; } } } ``` ``` Java-explained [] class Solution { public int[] findXSum(int[] nums, int k, int x) { // Initialize the result array with size n - k + 1 int[] result = new int[nums.length - k + 1]; // Iterate over each sliding window of size k for (int i = 0; i < result.length; i++) { // Compute x-sum for the subarray nums[i..i+k-1] result[i] = findSum(nums, i, i + k, x); } return result; } private int findSum(int[] nums, int i, int j, int x) { // Create a map to count the frequency of elements in the subarray Map<Integer, Integer> map = new HashMap<>(); for (int k = i; k < j; k++) { map.put(nums[k], map.getOrDefault(nums[k], 0) + 1); } // Use a min-heap (priority queue) to keep track of top x most frequent elements // If frequencies are equal, the element with the smaller value has lower priority PriorityQueue<Pair> pq = new PriorityQueue<>( (a, b) -> a.freq == b.freq ? a.val - b.val : a.freq - b.freq ); // Iterate through the frequency map for (int key : map.keySet()) { pq.offer(new Pair(key, map.get(key))); // Push each element and its frequency // Keep only top x frequent elements in the heap if (pq.size() > x) pq.poll(); // Remove the least frequent (or smaller valued if tie) } // Sum up the total frequency-weighted values from the top x elements int sum = 0; while (!pq.isEmpty()) { Pair p = pq.poll(); sum += p.freq * p.val; // Multiply value by frequency } return sum; } // Helper class to store element value and its frequency class Pair { int val, freq; public Pair(int v, int f) { val = v; freq = f; } } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
dict, sliding window
dict-sliding-window-by-victor-smk-g9u1
null
Victor-SMK
NORMAL
2025-04-03T19:49:50.876514+00:00
2025-04-03T19:49:50.876514+00:00
11
false
```swift [] class Solution { func findXSum(_ nums: [Int], _ k: Int, _ x: Int) -> [Int] { var ans = [Int]() var dict = [Int: Int]() for i in 0..<nums.count { dict[nums[i], default: 0] += 1 if i < k - 1 { continue } let arr = dict.sorted{ $0.value > $1.value || $0.value == $1.value && $0.key > $1.key} var temp = 0 for j in 0..<min(x, arr.count) { temp += arr[j].key * arr[j].value } ans.append(temp) dict[nums[i - (k - 1)], default: 0] -= 1 } return ans } } ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Python', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Java&JS&TS Solution (JW)
javajsts-solution-jw-by-specter01wj-fksf
IntuitionApproachComplexity Time complexity: Space complexity: Code
specter01wj
NORMAL
2025-04-02T06:50:54.000853+00:00
2025-04-02T06:50:54.000853+00:00
6
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 [] public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] result = new int[n - k + 1]; Map<Integer, Integer> freq = new HashMap<>(); for (int i = 0; i < k; i++) { freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1); } result[0] = computeXSum(freq, x); for (int i = k; i < n; i++) { // remove leftmost int left = nums[i - k]; freq.put(left, freq.get(left) - 1); if (freq.get(left) == 0) freq.remove(left); // add new right int right = nums[i]; freq.put(right, freq.getOrDefault(right, 0) + 1); result[i - k + 1] = computeXSum(freq, x); } return result; } private int computeXSum(Map<Integer, Integer> freq, int x) { List<int[]> freqList = new ArrayList<>(); for (Map.Entry<Integer, Integer> entry : freq.entrySet()) { freqList.add(new int[]{entry.getKey(), entry.getValue()}); } // Sort by frequency DESC, then value DESC freqList.sort((a, b) -> { if (a[1] != b[1]) return Integer.compare(b[1], a[1]); return Integer.compare(b[0], a[0]); }); Set<Integer> topX = new HashSet<>(); for (int i = 0; i < Math.min(x, freqList.size()); i++) { topX.add(freqList.get(i)[0]); } // Sum up only top x frequent values int sum = 0; for (Map.Entry<Integer, Integer> entry : freq.entrySet()) { if (topX.contains(entry.getKey())) { sum += entry.getKey() * entry.getValue(); } } return sum; } ``` ```javascript [] var findXSum = function(nums, k, x) { const n = nums.length; const result = []; const freq = new Map(); // Initialize frequency map with first k elements for (let i = 0; i < k; i++) { freq.set(nums[i], (freq.get(nums[i]) || 0) + 1); } result.push(computeXSum(freq, x)); for (let i = k; i < n; i++) { // Remove element going out of the window const out = nums[i - k]; freq.set(out, freq.get(out) - 1); if (freq.get(out) === 0) { freq.delete(out); } // Add element coming into the window const inVal = nums[i]; freq.set(inVal, (freq.get(inVal) || 0) + 1); result.push(computeXSum(freq, x)); } return result; }; function computeXSum(freqMap, x) { const freqList = []; // Convert freqMap to list of [value, count] for (let [val, count] of freqMap.entries()) { freqList.push([val, count]); } // Sort by frequency DESC, then value DESC freqList.sort((a, b) => { if (b[1] !== a[1]) return b[1] - a[1]; return b[0] - a[0]; }); // Select top x values const topX = new Set(); for (let i = 0; i < Math.min(x, freqList.length); i++) { topX.add(freqList[i][0]); } // Sum up values from top x let sum = 0; for (let [val, count] of freqMap.entries()) { if (topX.has(val)) { sum += val * count; } } return sum; } ``` ```typescript [] function findXSum(nums: number[], k: number, x: number): number[] { const n = nums.length; const result: number[] = []; const freq: Map<number, number> = new Map(); // Initialize frequency map with first k elements for (let i = 0; i < k; i++) { freq.set(nums[i], (freq.get(nums[i]) || 0) + 1); } result.push(computeXSum(freq, x)); // Slide the window for (let i = k; i < n; i++) { const outVal = nums[i - k]; const outCount = freq.get(outVal)! - 1; if (outCount === 0) { freq.delete(outVal); } else { freq.set(outVal, outCount); } const inVal = nums[i]; freq.set(inVal, (freq.get(inVal) || 0) + 1); result.push(computeXSum(freq, x)); } return result; }; function computeXSum(freqMap: Map<number, number>, x: number): number { const freqList: [number, number][] = []; // Convert map to list of [value, frequency] for (const [val, count] of freqMap.entries()) { freqList.push([val, count]); } // Sort by frequency descending, then value descending freqList.sort((a, b) => { if (b[1] !== a[1]) return b[1] - a[1]; return b[0] - a[0]; }); // Pick top x values const topX = new Set<number>(); for (let i = 0; i < Math.min(x, freqList.length); i++) { topX.add(freqList[i][0]); } // Compute sum of top x frequent values let sum = 0; for (const [val, count] of freqMap.entries()) { if (topX.has(val)) { sum += val * count; } } return sum; } ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Java', 'TypeScript', 'JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
easy
easy-by-omarismail55-t7fl
IntuitionApproachComplexity Time complexity: Space complexity: Code
OMarIsmail55
NORMAL
2025-03-23T19:00:52.638070+00:00
2025-03-23T19:00:52.638070+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)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @param {number} x * @return {number[]} */ var findXSum = function (nums, k, x) { let answer = []; let newMap = new Map() for (let num = 0; num <= nums.length - k; num++) { let window = nums.slice(num, num + k); for (let i = 0; i < window.length; i++) { if (newMap.has(window[i])) { newMap.set(window[i], newMap.get(window[i]) + 1); } else { newMap.set(window[i], 1); } } let sortedMap = [...newMap].sort((a, b) => { if (b[1] == a[1]) return b[0] - a[0] return b[1] - a[1]; }); let sum = 0; for (let i = 0; i < Math.min(x, sortedMap.length); i++) { sum += sortedMap[i][0] * sortedMap[i][1]; } answer.push(sum); newMap.clear() } return answer; }; ```
0
0
['JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
A noob approach
a-noob-approach-by-satyajeetpp-b8xc
Intuitionused pen and paper to solve this and took one dayApproachone step at a time , and I got to know I need to learn dict,lambda againComplexity Time compl
satyajeetpp
NORMAL
2025-03-21T12:04:43.772788+00:00
2025-03-21T12:04:43.772788+00:00
5
false
# Intuition used pen and paper to solve this and took one day # Approach one step at a time , and I got to know I need to learn dict,lambda again # Complexity - Time complexity: I don't know. - Space complexity: I don't know. # Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: listmain=[] for i in range(len(nums)-k+1): listnums=[] for j in range(i,i+k): listnums.append(nums[j]) listmain.append(listnums) mainans=[] for k in listmain: minidict={} for j in k: minidict[j] = k.count(j) mainans.append(minidict) newmain = [] for r in mainans: newmain.append(dict(sorted(r.items(),key = lambda item: (item[1], item[0]),reverse=True))) itslast=[] for t in newmain: newt=list(t.items()) minilastans=[] for z in newt[:x] : minilastans.append(z[0]*z[1]) itslast.append(sum(minilastans[:x])) return itslast ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
A noob approach
a-noob-approach-by-satyajeetpp-gkm1
Intuitionused pen and paper to solve this and took one dayApproachone step at a time , and I got to know I need to learn dict,lambda againComplexity Time compl
satyajeetpp
NORMAL
2025-03-21T12:04:39.202385+00:00
2025-03-21T12:04:39.202385+00:00
4
false
# Intuition used pen and paper to solve this and took one day # Approach one step at a time , and I got to know I need to learn dict,lambda again # Complexity - Time complexity: I don't know. - Space complexity: I don't know. # Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: listmain=[] for i in range(len(nums)-k+1): listnums=[] for j in range(i,i+k): listnums.append(nums[j]) listmain.append(listnums) mainans=[] for k in listmain: minidict={} for j in k: minidict[j] = k.count(j) mainans.append(minidict) newmain = [] for r in mainans: newmain.append(dict(sorted(r.items(),key = lambda item: (item[1], item[0]),reverse=True))) itslast=[] for t in newmain: newt=list(t.items()) minilastans=[] for z in newt[:x] : minilastans.append(z[0]*z[1]) itslast.append(sum(minilastans[:x])) return itslast ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding Window || Java
sliding-window-java-by-arvindadari722-kw7j
IntuitionApproachComplexity Time complexity: Space complexity: Code
arvindadari722
NORMAL
2025-03-20T08:10:47.122284+00:00
2025-03-20T08:10:47.122284+00:00
9
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 int[] findXSum(int[] nums, int k, int x) { List<Integer> list = new ArrayList<>(); List<Integer> temp = new ArrayList<>(); int start = 0; for (int end = 0; end < nums.length; end++) { temp.add(nums[end]); Map<Integer, Integer> map = new HashMap<>(); if (end - start == k - 1) { for (Integer z : temp) { map.put(z, map.getOrDefault(z, 0) + 1); } Map<Integer, Integer> sortedMap = map.entrySet().stream() .sorted(Map.Entry.<Integer, Integer>comparingByValue(Comparator.reverseOrder()) .thenComparing(Map.Entry.comparingByKey(Comparator.reverseOrder()))) .collect(Collectors.toMap(Map.Entry::getKey, // Key Map.Entry::getValue, // Value (e1, e2) -> e1, // Merge function (if necessary) LinkedHashMap::new)); int y = 1; int sum = 0; breakHere: for(Map.Entry<Integer, Integer> entry: sortedMap.entrySet()) { sum += entry.getKey() * entry.getValue(); if(y == x) { list.add(sum); break breakHere; } if(x > map.size() & y == map.size()) { list.add(sum); break breakHere; } y++; } temp.remove(0); start++; map = new HashMap<>(); } } return list.stream().mapToInt(a-> (int)a).toArray(); } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
βœ…πŸ’―πŸ”₯Simple CodeπŸ“ŒπŸš€| πŸŽ“πŸ§ Beginner friendlyπŸ”₯| | using dictionary and sliding window|| sorting
simple-code-beginner-friendly-using-dict-wqa5
IntuitionThe function computes a sliding window sum of the most frequent x elements for each window of size k.Approach1.Initialize a result list res of size len
kotla_jithendra
NORMAL
2025-03-19T04:34:13.949985+00:00
2025-03-19T04:37:18.165348+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The function computes a sliding window sum of the most frequent x elements for each window of size k. # Approach <!-- Describe your approach to solving the problem. --> 1.Initialize a result list res of size len(nums) - k + 1. 2.Iterate over each valid starting index j of a k-sized subarray. 3.Create a frequency dictionary d for the subarray. 4.Sort the dictionary by frequency (descending), then by value (descending). 5.Pick the top x elements and compute their total contribution. 6.Store the computed sum in res[j]. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Time Complexity Building the frequency dictionary (O(k)) Sorting the dictionary (O(k log k)) Extracting the top x elements (O(x)) Summation (O(x)) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n) # Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: res=[0]*(len(nums)-k+1) for j in range(len(nums)-k+1): sub=nums[j:j+k] re=0 d={} for i in sub: if i in d: d[i]+=1 else: d[i]=1 sorted_items = sorted(d.items(), key=lambda item: (-item[1], -item[0])) top_x_elements = {sorted_items[l][0] for l in range(min(x, len(sorted_items)))} for l in top_x_elements: re+=(l*d[l]) res[j]=re return res ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Beginner-friendly solution
beginner-friendly-solution-by-sarichi-cj8l
IntuitionApproachComplexity Time complexity: Space complexity: Code
sarichi
NORMAL
2025-03-16T16:18:28.436067+00:00
2025-03-16T16:18:28.436067+00:00
11
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 ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: def top_x_frequent(nums, x): freq_map = Counter(nums) top_x = sorted(freq_map.items(), key=lambda x: (x[1], x[0]), reverse=True)[:x] result = [key * freq for key, freq in top_x] return result ans = [] for i in range(len(nums)-k+1): val = nums[i:i+k] ans.append(sum(top_x_frequent(val, x))) return ans ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Fixed length sliding window, frequency counter and max heap Python solution. Beats 89%
fixed-length-sliding-window-frequency-co-tk7k
IntuitionUpdate frequency counter to reflect current window as you slide through the listApproachImplement x_sum method to take a freq_counter and current windo
user3552d
NORMAL
2025-03-16T14:33:43.929425+00:00
2025-03-16T14:33:43.929425+00:00
38
false
# Intuition Update frequency counter to reflect current window as you slide through the list # Approach Implement `x_sum` method to take a freq_counter and current window. Use max heap to get top x values. Put tuple of (frequency, value) in the max heap. There is no max heap in python so we use min heap with the values negated. # Complexity - Time complexity: O(n*k) where n is length of nums and k is the max number of keys that will ever be in the frequency counter or the heap - Space complexity: O(k) for the counter and the heap # Code ```python3 [] from collections import Counter from heapq import heapify, heappush, heappop class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: def x_sum(counter, arr): heap = [] for k, v in counter.items(): heappush(heap, (-v, -k)) if len(heap)<x: return sum(arr) s = 0 for i in range(x): k, v = heappop(heap) s+= -k * -v return s l = 0 r = k n = len(nums) res = [] counter = Counter(nums[l: r]) res.append(x_sum(counter, nums[l:r])) l+=1 while r < n: counter[nums[l-1]] -=1 counter[nums[r]] +=1 res.append(x_sum(counter, nums[l: r+1])) l+=1 r+=1 return res ```
0
0
['Python3']
1
find-x-sum-of-all-k-long-subarrays-i
find x sum of all k long subarrays I
find-x-sum-of-all-k-long-subarrays-i-by-trmtz
Code
AnushaYelleti
NORMAL
2025-03-12T14:17:30.213012+00:00
2025-03-12T14:17:30.213012+00:00
5
false
# Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: n=len(nums) def xsum(l,x): freq={} for i in l: if i not in freq: freq[i]=1 else: freq[i]+=1 sor=sorted(freq.items(),key= lambda item:(item[1],item[0]),reverse=True) return sum([item[0]*item[1] for item in sor[:x]]) ans=[] for i in range(n-k+1): l=xsum(nums[i:i+k],x) ans.append(l) return ans ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding window, Map, with explanation
sliding-window-map-with-explanation-by-r-ymzc
IntuitionThe task requires us to calculate the sum of the x most frequent elements in each sliding window of size k from an array of numbers. To do this efficie
rikkaaar
NORMAL
2025-03-11T11:55:22.581870+00:00
2025-03-11T11:55:22.581870+00:00
8
false
## Intuition The task requires us to calculate the sum of the `x` most frequent elements in each sliding window of size `k` from an array of numbers. To do this efficiently, we need to maintain a frequency map of the elements in the current window and calculate the sum of the `x` most frequent elements as the window slides over the array. ### First Thoughts: 1. A **sliding window** approach makes sense because the problem asks us to calculate the result for each subarray of length `k`. 2. We can keep track of the frequency of elements in the window using a **frequency map** (`Map` in JavaScript). 3. After updating the map with the new element that enters the window and removing the element that leaves, we need to sort the map by frequency and sum the `x` most frequent elements. ## Approach ### Steps: 1. **Initialize the frequency map**: - We begin by filling the map with the frequencies of the first `k-1` elements (not including the last element for now to adjust the window in the following steps). 2. **Sliding window mechanism**: - For each window (from index `L` to `R`), we include the element at `R` in the frequency map. - Then, sort the frequency map in descending order first by frequency, and second by the value of the element itself (for ties). - Select the top `x` most frequent elements from the sorted list and calculate their sum, which will be the result for the current window. - Move the window by removing the element at index `L` from the frequency map and incrementing both `L` and `R`. 3. **Return the results**: - For each window, we store the calculated sum of the top `x` frequent elements in an array and return this array after processing all windows. # Complexity - **Time Complexity**: For each window, the frequency map is sorted. If there are `m` unique elements in the window (at most `k`), the sorting cost is `O(m log m)`. In the worst-case scenario, this yields an overall complexity of: $$O((n - k + 1) \times k \log k) \approx O(n \times k \log k)$$ - **Space Complexity**: The space is primarily used by the frequency map, which stores at most `k` unique elements. Thus, the space complexity is: $$O(k)$$ # Code ```typescript [] function findXSum(nums: number[], k: number, x: number): number[] { let answer = [] let freqMap = new Map<number, number>() // Add frequencies of the first k - 1 elements. // Since 1 <= x <= k <= nums.length, no need to check boundaries. // Do not include last index to make the adjustment in FOR loop down below for (let i = 0; i < k - 1; i++) { freqMap.set(nums[i], (freqMap.get(nums[i]) || 0) + 1); } for (let L = 0, R = L + k - 1; R < nums.length; L++, R++) { const LNum = nums[L] const RNum = nums[R] // Increase frequency of the new element at index R. freqMap.set(RNum, (freqMap.get(RNum) || 0) + 1); // Sort the frequency map entries by frequency (descending) and by number (descending) in case of ties. Return (slice) x elements const mostXElements = Array.from(freqMap).toSorted(([keyA, valueA], [keyB, valueB]) => { if (valueA !== valueB) { return valueB - valueA; } return keyB - keyA; }).slice(0, x) // Calculate the sum of the top x elements. const mostXElementsSum = mostXElements.reduce((acc, curr) => { return acc + curr[0] * curr[1] }, 0) answer.push(mostXElementsSum) // Decrease frequency of the element at index L. // If the resulting frequency is 0, delete it from map to reduce complexity when sorting freqMap.set(LNum, freqMap.get(LNum) - 1); if (freqMap.get(LNum) == 0) freqMap.delete(LNum); } return answer }; ```
0
0
['Hash Table', 'Sliding Window', 'TypeScript']
0
find-x-sum-of-all-k-long-subarrays-i
The most beautiful and easy to understand solution to the most difficult "easy" problem.
the-most-beautiful-and-easy-to-understan-ljmx
ApproachAt first, we initialize an array answer of length n - k + 1 to store the x-sums of each subarray. Then while iterating through each subarray we define t
Khamdam
NORMAL
2025-03-10T07:30:40.879662+00:00
2025-03-10T07:30:40.879662+00:00
21
false
# Approach At first, we initialize an array answer of length n - k + 1 to store the x-sums of each subarray. Then while iterating through each subarray we define three variables: - sum - for calculating the sum of elements, - set - for tracking distinct elements - freqMap - for tracking frequencies. During each iteration of the array using a sliding window of size k, for each window, we calculate: - the sum of elements, - the frequency for each element in the subarray by updating the freqMap, - the unique elements by adding them into the set. **If there are fewer than x distinct elements, we simply sum all elements of the subarray and store it in answer[i].** **If there are x or more distinct elements, we use the priority queue to sort the elements by frequency and value.** **We poll the top x elements and compute their contribution to the x-sum, and store the result in answer[i].** After processing all subarrays, we return the answer array containing the x-sums for all the subarrays of length k. # Complexity - Time complexity: O(n * k log k). - Space complexity: O(n + k) # Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] answer = new int[n - k + 1]; for (int i = 0; i < answer.length; i++) { int sum = 0; Set<Integer> set = new HashSet<>(); Map<Integer, Integer> freqMap = new HashMap<>(); for (int j = i; j < i + k; j++) { sum += nums[j]; set.add(nums[j]); freqMap.put(nums[j], freqMap.getOrDefault(nums[j], 0) + 1); } if (set.size() < x) { answer[i] = sum; } else { PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((a, b) -> { if (freqMap.get(a) == freqMap.get(b)) { return b - a; } return freqMap.get(b) - freqMap.get(a); }); for (int element : set) { priorityQueue.offer(element); } int topCount = x; while (topCount > 0) { int topElement = priorityQueue.poll(); answer[i] += topElement * freqMap.get(topElement); topCount--; } } } return answer; } } ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
python code
python-code-by-vishalyadav28-mcjd
Complexity Time complexity: O(nβ‹…klogk) Space complexity: O(n+k) Code
vishalyadav28
NORMAL
2025-03-10T06:45:36.396436+00:00
2025-03-10T06:45:36.396436+00:00
8
false
# Complexity - Time complexity: $$O(nβ‹…klogk)$$ - Space complexity: $$O(n+k)$$ # Code ```python3 [] from collections import Counter class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: result = [] for i in range(0,len(nums)-k+1): subarray = nums[i:i+k] fre = Counter(subarray) sort_fre = sorted(fre.keys(), key=lambda num:(-fre[num],-num)) filter_num = [] for j in sort_fre[:x]: filter_num.extend([j]*fre[j]) result.append(sum(filter_num)) return result ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
simple python solution, create hashmap first -> sort hashmap by key desc -> get value from max key
simple-python-solution-create-hashmap-fi-smle
IntuitionApproachComplexity Time complexity: Space complexity: Code
leeyeehao
NORMAL
2025-03-10T03:39:52.096490+00:00
2025-03-10T03:39:52.096490+00:00
8
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 ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: n = len(nums) ans=[] for i in range(n-k+1): t = nums[i:i+k] hashmap = {} for j in t: if j not in hashmap: hashmap[j] = 1 else: hashmap[j] += 1 hashmap = dict(sorted(hashmap.items(),reverse=True)) cnt=0 for j in range(x): try: v = max(hashmap, key=hashmap.get) cnt+=(v*hashmap[v]) hashmap.pop(v) except ValueError: pass ans.append(cnt) return ans ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Find X-Sum of All K-Long Subarrays I
find-x-sum-of-all-k-long-subarrays-i-by-5ktqq
Code
srinivas_lingampelli
NORMAL
2025-03-09T17:01:10.030678+00:00
2025-03-09T17:01:10.030678+00:00
18
false
# Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int ans[]=new int[nums.length-k+1]; int left=0; int right=k-1; int []freq=new int[51]; for(int i=0;i<=right;i++) freq[nums[i]]++; ans[0]=find(freq,x); int ind=1; while(right<nums.length) { right++; if(right==nums.length) break; freq[nums[right]]++; freq[nums[left]]--; left++; ans[ind++]=find(freq,x); } return ans; } public static int find(int f[],int x) { int freq[]=new int[51]; for(int i=0;i<51;i++) { freq[i]=f[i]; } int nums[]=new int[51]; for(int i=0;i<51;i++) { nums[i]=i; } for(int i=1;i<51;i++) { int key=freq[i]; int numKey=nums[i]; int j=i-1; while(j>=0 && freq[j]<=key) { freq[j+1]=freq[j]; nums[j+1]=nums[j]; j--; } freq[j+1]=key; nums[j+1]=numKey; } int sum=0; for(int i=0;i<x;i++) { sum+=(nums[i]*freq[i]); } return sum; } } ```
0
0
['Sliding Window', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
Heap + Sliding Window
heap-sliding-window-by-littlefish20-xaby
IntuitionApproachComplexity Time complexity: Space complexity: Code
littleFish20
NORMAL
2025-03-07T02:18:25.919152+00:00
2025-03-07T02:18:25.919152+00:00
9
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 ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: size, dd, result, left = len(nums), defaultdict(int), [], 0 def calculate_nlargest(n, d): heap = [] result = 0 for k, v in d.items(): heappush(heap, (v, k)) if len(heap) > n: heappop(heap) while heap: x, y = heappop(heap) result += x * y return result for right in range(size): dd[nums[right]] += 1 if right == k - 1: result.append(calculate_nlargest(x, dd)) elif right >= k: dd[nums[left]] -= 1 left += 1 result.append(calculate_nlargest(x, dd)) return result ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
JAVA | Sliding Windows for large N
java-sliding-windows-for-large-n-by-user-ycjx
IntuitionApproachComplexity Time complexity: Space complexity: Code
ankit9999
NORMAL
2025-03-02T04:04:54.069159+00:00
2025-03-02T04:04:54.069159+00:00
10
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 { // record won't help as we need to incr/decr freq class Pair { int num; int freq; public Pair(int num, int freq) { this.num = num; this.freq = freq; } } public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] res = new int[n - k + 1]; // Map to quickly access the Pair for a given number. Map<Integer, Pair> numToPairMap = new HashMap<>(); // TreeSet to maintain ordering of pairs. // Sorted by frequency descending, then by number descending. TreeSet<Pair> tree = new TreeSet<>((a, b) -> { if (a.freq!=b.freq) return b.freq - a.freq; // higher frequency first if (a.num!=b.num) return b.num-a.num; // higher number first when frequencies tie return 0; }); int i=0,j=0; while(j<n){ Pair inPair = numToPairMap.get(nums[j]); if(inPair == null){ inPair = new Pair(nums[j],1); tree.add(inPair); numToPairMap.put(nums[j], inPair); }else{ tree.remove(inPair); inPair.freq++; tree.add(inPair); } if(j-i+1 == k){ res[i] = computeXSum(tree, x); // remove ith num Pair outPair = numToPairMap.get(nums[i]); tree.remove(outPair); outPair.freq--; if(outPair.freq > 0 ) { tree.add(outPair);} i++; j++; }else{ j++; } } return res; } // Helper method to compute the x-sum for the current window based on the TreeSet. private int computeXSum(TreeSet<Pair> tree, int x) { int sum = 0, count = 0; // Since our TreeSet is sorted by frequency (then value) in descending order, // iterating over it will give the highest frequency numbers first. for (Pair p : tree) { if (count < x) { sum += p.num * p.freq; count++; } else { break; } } return sum; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
oneliner: return sum for nlagrest Counter items lambda enumerate range len
oneliner-return-sum-for-nlagrest-counter-bd9n
null
qulinxao
NORMAL
2025-02-20T08:10:09.274998+00:00
2025-02-20T08:10:09.274998+00:00
7
false
```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: return [ sum(b*a for a,b in nlargest(x, Counter(nums[l:r]).items(), key=lambda z:(z[1],z[0])) ) for r,l in enumerate( range(len(nums)-k+1), k) ] ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
I am happy that i did it alone
i-am-happy-that-i-did-it-alone-by-koushi-8pcr
IntuitionApproachComplexity Time complexity: Space complexity: Code
Koushik_Dutta
NORMAL
2025-02-19T10:32:25.280477+00:00
2025-02-19T10:32:25.280477+00:00
21
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 ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: i=0 ans=[] while i+k<=len(nums): count = Counter(nums[i:i+k]) hps = [] for k1,v in count.items(): heapq.heappush(hps,(-v,-k1)) res = 0 for j in range(x): if hps: v,k1 = heapq.heappop(hps) res += k1*v ans.append(res) i+=1 return ans ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
eaasy
eaasy-by-irfan_khanbhao-bp0r
Intuitionusing priority_queue and unordered_mapApproachfirst i push arr not all arr like sliding arr length push push in map and i find all frequenc
irfan_khanbhao
NORMAL
2025-02-17T09:50:27.270955+00:00
2025-02-17T09:50:27.270955+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> using priority_queue and unordered_map # Approach <!-- Describe your approach to solving the problem. --> first i push arr not all arr like sliding arr length push push in map and i find all frequency and make a priority_queue push in queue this queueu top is maximum number ic start a loop if count<x then and !queue empty stop and return sum # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * k log k) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(K) # Code ```cpp [] class Solution { public: int solve(vector<int>& arr, int x) { unordered_map<int, int> freq; for (auto it : arr) { freq[it]++; } priority_queue<pair<int, int>> maxHeap; for (auto it : freq) { maxHeap.push({it.second, it.first}); } int sum = 0; int count = 0; while (!maxHeap.empty() && count < x) { auto top = maxHeap.top(); maxHeap.pop(); sum += top.second * top.first; count++; } return sum; } vector<int> findXSum(vector<int>& arr, int k, int x) { vector<int> result; vector<int> add; for (int i = 0; i < arr.size(); i++) { add.push_back(arr[i]); if (add.size() == k) { result.push_back(solve(add, x)); add.erase(add.begin()); } } return result; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
C++ Frankenstein solution with map and max-heap
c-frankenstein-solution-with-map-and-max-tn3d
IntuitionApproachComplexity Time complexity: Space complexity: Code
user2505C
NORMAL
2025-02-16T22:17:34.258824+00:00
2025-02-16T22:17:34.258824+00:00
7
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 [] #include <queue> #include <utility> #include <functional> #include <unordered_map> class Solution { typedef int VAL; typedef int FRQ; typedef std::pair<VAL,FRQ> PAIR; public: vector<int> findXSum(vector<int>& nums, int k, int x) { // Conditions if (nums.empty() || k > nums.size()) return {}; // Initialisation std::vector<int> result; std::size_t size = nums.size(); std::unordered_map<VAL,FRQ> umap; std::function<bool(const PAIR&, const PAIR&)> MaxHeap = [] (const PAIR &a, const PAIR &b) noexcept(true) -> bool { if (a.second == b.second) return a.first < b.first; return a.second < b.second; }; std::priority_queue<PAIR, std::vector<PAIR>, decltype(MaxHeap)> pq(MaxHeap); // Implementation int start = 0; while (k <= size){ // Calculate frequency using a map if (umap.empty()){ for (unsigned int i(start); i < k; ++i){ umap[nums[i]]++; } } else { umap[nums[start - 1]]--; umap[nums[k - 1]]++; } //push map data into a max-heap // clear first while (!pq.empty()) pq.pop(); for (const auto & pair : umap){ pq.push(pair); } int sum = 0; for (unsigned int i(0); i < x && !pq.empty(); ++i){ auto [val, frq] = pq.top(); sum += (val*frq); pq.pop(); } result.emplace_back(sum); ++start; ++k; } // Return result return result; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
Kotlin Sugar Style + Decomposition
kotlin-sugar-style-decomposition-by-dani-ss80
How it work: Create Res Array Iterate over array For each index calculate x - sum Create map and iterate and calculate count of occurances Create Pq and fill It
Danil_M
NORMAL
2025-02-16T09:10:14.517694+00:00
2025-02-16T09:10:14.517694+00:00
12
false
**How it work:** 1. Create Res Array 2. Iterate over array 3. For each index calculate x - sum 4. Create map and iterate and calculate count of occurances 5. Create Pq and fill 6. Iterate take x and calc sum # Complexity - Time complexity:O(n * k * log(k)) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n * k) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```kotlin [] class Solution { fun findXSum(nums: IntArray, k: Int, x: Int): IntArray { if (nums.hasSingle()) return intArrayOf(nums[0]) val n = nums.size val res = IntArray(n - k + 1) for (i in 0 until res.size) { res[i] = nums.calculateXSum(i, k + i - 1, k, x) } return res } private fun IntArray.hasSingle(): Boolean = when { this.size == 1 -> true else -> false } private fun IntArray.calculateXSum(startIndex: Int, endIndex: Int, k: Int, x: Int): Int { when { startIndex > endIndex -> throw IndexOutOfBoundsException("$startIndex") endIndex > this.size -> throw IndexOutOfBoundsException("$endIndex") } val counts = mutableMapOf<Int, Int>() for (i in startIndex..endIndex) counts[this[i]] = counts.getOrDefault(this[i], 0) + 1 val pq = PriorityQueue<Pair<Int, Int>> {a: Pair<Int, Int>, b: Pair<Int, Int> -> if (a.second != b.second) b.second - a.second else b.first - a.first } for ((num, count) in counts) pq.offer(Pair(num, count)) var x = x var sum = 0 while (pq.isNotEmpty() && x != 0) { val (num, count) = pq.poll() sum += (num * count) x-- } return sum } } ```
0
0
['Hash Table', 'Heap (Priority Queue)', 'Kotlin']
0
find-x-sum-of-all-k-long-subarrays-i
Beats 90% - Most easy way on INTERNET to understand (C#)
beats-90-most-easy-way-on-internet-to-un-9wur
IntuitionApproachComplexity Time complexity: Space complexity: Code
robinparth
NORMAL
2025-02-13T19:48:26.246163+00:00
2025-02-13T19:48:26.246163+00:00
23
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 ```csharp [] public class Solution { public int[] FindXSum(int[] nums, int k, int x) { List<int> ls = new List<int>(); Dictionary<int,int> dic = new Dictionary<int,int>(); for(int i = 0, j=0; j<nums.Length ; j++) { if(dic.ContainsKey(nums[j])) { dic[nums[j]]++; } else { dic.Add(nums[j],1); } //calculate window if(((j+1)-i)==k) { ls.Add(Calculate(dic, x)); //First element removal if(dic[nums[i]] > 1) { dic[nums[i]]--; } else { dic.Remove(nums[i]); } //shift window ahead from left i++; } } return ls.ToArray(); } public int Calculate(Dictionary<int,int> dic, int x) { int result = 0; if(dic.Count<x) { foreach(var d in dic ) { result = result + (d.Key * d.Value); } return result; } PriorityQueue<int,(int,int)> queue = new PriorityQueue<int,(int,int)>( Comparer<(int, int)>.Create((a, b) => { // Higher occurrence first if (a.Item1 != b.Item1) return b.Item1.CompareTo(a.Item1); // Higher value in case of tie return b.Item2.CompareTo(a.Item2); }) ); foreach(var d in dic ) { queue.Enqueue(d.Key,(d.Value,d.Key)); } for(int i = 0; i < x; i++) { int xx = queue.Dequeue(); result = result + (dic[xx] * xx); } return result; } } ```
0
0
['C#']
0
find-x-sum-of-all-k-long-subarrays-i
Python No Built in functions - SORT + Windows slide
python-no-built-in-functions-sort-window-uzbh
IntuitionApproachi like catsComplexity Time complexity: Space complexity: Code
Tolga-dev
NORMAL
2025-02-09T12:19:48.134411+00:00
2025-02-09T12:19:48.134411+00:00
17
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach i like cats # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: def find_sum(a, x): freq = {} for num in a: freq[num] = freq.get(num, 0) + 1 top_elements = sorted(freq.items(), key=lambda item: (-item[1], -item[0]))[:x] return sum(item[0] * item[1] for item in top_elements) n = len(nums) res = [] for i in range(n - k + 1): subarray = nums[i:i + k] res.append(find_sum(subarray, x)) return res ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
C++ | Easy approach | Intuitive
c-easy-approach-intuitive-by-gitanjli_52-spho
Complexity Time complexity: O(nlogn) Space complexity: O(n) Code
gitanjli_525
NORMAL
2025-02-08T09:53:55.537637+00:00
2025-02-08T09:53:55.537637+00:00
11
false
# Complexity - Time complexity: O(nlogn) - Space complexity: O(n) # Code ```cpp [] class Solution { public: int calculateXSum(vector<int>& nums, int x){ unordered_map<int,int> frequencyCount; priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> minHeap; int sum=0; for(int i=0;i<nums.size();i++){ frequencyCount[nums[i]]++; } for(auto i: frequencyCount){ minHeap.push({i.second, i.first}); if(minHeap.size() > x) { minHeap.pop(); } } while(!minHeap.empty()){ pair<int,int> item = minHeap.top(); sum = (item.first*item.second) + sum; minHeap.pop(); } return sum; } vector<int> findXSum(vector<int>& nums, int k, int x) { vector<int> result; int s = nums.size(); for(int i=0;i+k-1<s;i++){ vector<int> subArray; for(int j=i;j<i+k;j++){ subArray.push_back(nums[j]); } result.push_back(calculateXSum(subArray,x)); } return result; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
C++ solution
c-solution-by-lathcsmath-0ahx
IntuitionApproachComplexity Time complexity: O(N) Space complexity: O(N) Code
lathcsmath
NORMAL
2025-02-07T18:42:31.187741+00:00
2025-02-07T18:42:31.187741+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # 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 { public: vector<int> findXSum(vector<int>& nums, int k, int x) { int n = nums.size() - k + 1; vector<int> answer (n); for(int i = 0; i < n; i++) { vector<int> sub_nums = {nums.begin() + i,nums.begin() + i + k}; answer[i] = x_sum(sub_nums,x); } return answer; } private: int x_sum(vector<int>& nums, int x) { map<int,int> freq; for(int num: nums) { freq[num]++; } vector<pair<int,int>> freq_vec (freq.size()); int i = 0; for(auto pair: freq) { freq_vec[i].first = pair.first; freq_vec[i].second = pair.second; i++; } sort(freq_vec.begin(),freq_vec.end(),cmp); int sum = 0; vector<pair<int,int>>::iterator it = freq_vec.begin(); while(x > 0 && it != freq_vec.end()) { sum += it->first * it->second; x--; it++; } return sum; } bool static cmp(const pair<int,int>& a, const pair<int,int>& b) { return ((a.second == b.second)? a.first > b.first : a.second > b.second); } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
C++ / Java / Python3 solution (Sliding Window, Hash Table, Priority Queue)
c-java-python3-solution-sliding-window-h-gvuy
IntuitionKeep hash table as sliding window to calculate frequencies. Use priority queue to get top x elements.Complexity Time complexity: O(nΓ—kΓ—log(k)) Space
RuslanVdovychenko
NORMAL
2025-02-05T16:13:00.887819+00:00
2025-02-05T16:13:00.887819+00:00
68
false
# Intuition Keep hash table as sliding window to calculate frequencies. Use priority queue to get top $x$ elements. # Complexity - Time complexity: $$O(n \times k \times \log(k))$$ - Space complexity: $$O(k)$$ # Code ```cpp [] #include <functional> typedef pair<int, int> int_pair; class Solution { public: vector<int> findXSum(vector<int>& nums, int k, int x) { int n = nums.size(); vector<int> answer(n - k + 1, 0); unordered_map<int, int> counter; for (int i = 0; i < k; i++) { int num = nums[i]; if (counter.find(num) == counter.end()) { counter[num] = 1; } else { counter[num] += 1; } } answer[0] = get_sum(counter, x); for (int i = 1; i < n - k + 1; i++) { int tail_idx = i - 1; int tail = nums[tail_idx]; int head_idx = k + tail_idx; int head = nums[head_idx]; if (head == tail) { answer[i] = answer[i - 1]; continue; } int count = counter[tail]; if (count == 1) { counter.erase(tail); } else { counter[tail] = count - 1; } if (counter.find(head) == counter.end()) { counter[head] = 1; } else { counter[head] = counter[head] + 1; } answer[i] = get_sum(counter, x); } return answer; } private: function<bool(const int_pair&, const int_pair&)> comparator = [](const int_pair& a, const int_pair& b) { int diff = a.second - b.second; if (diff != 0) { return diff > 0; } return b.first < a.first; }; int get_sum(unordered_map<int, int>& counter, int x) { priority_queue<int_pair, vector<int_pair>, decltype(comparator)> pq(comparator); int sum = 0; for (auto& kv: counter) { pq.push(kv); sum += kv.first*kv.second; if (pq.size() > x) { int_pair top = pq.top(); pq.pop(); sum -= top.first*top.second; } } return sum; } }; ``` ``` java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] answer = new int[n - k + 1]; Map<Integer, Integer> counter = new HashMap<>(); for (int i = 0; i < k; i++) { int num = nums[i]; counter.put(num, counter.getOrDefault(num, 0) + 1); } answer[0] = getSum(counter, x); for (int i = 1; i < n - k + 1; i++) { int tailIdx = i - 1; int tail = nums[tailIdx]; int headIdx = k + tailIdx; int head = nums[headIdx]; if (tail == head) { answer[i] = answer[i - 1]; continue; } if (counter.get(tail) == 1) { counter.remove(tail); } else { counter.put(tail, counter.get(tail) - 1); } counter.put(head, counter.getOrDefault(head, 0) + 1); answer[i] = getSum(counter, x); } return answer; } private int getSum(Map<Integer, Integer> counter, int x) { PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>( new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) { if (a.getValue() != b.getValue()) { return a.getValue() - b.getValue(); } return a.getKey() - b.getKey(); } }); int sum = 0; for (Map.Entry<Integer, Integer> entry: counter.entrySet()) { queue.offer(entry); sum += entry.getKey()*entry.getValue(); if (queue.size() > x) { Map.Entry<Integer, Integer> polled = queue.poll(); sum -= polled.getKey()*polled.getValue(); } } return sum; } } ``` ``` python [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: n = len(nums) answer = [0] * (n - k + 1) counter = Counter(nums[:k]) answer[0] = self.get_sum(counter, x) for i in range(1, n - k + 1): tail_idx = i - 1 tail = nums[tail_idx] head_idx = k + tail_idx head = nums[head_idx] if head == tail: answer[i] = answer[i - 1] continue if counter[tail] == 1: del counter[tail] else: counter[tail] -= 1 counter[head] += 1 answer[i] = self.get_sum(counter, x) return answer def get_sum(self, counter: Counter, x: int) -> int: pq = [(count, num) for num, count in counter.items()] heapq.heapify(pq) sum_value = sum(num * count for num, count in counter.items()) while len(pq) > x: count, num = heapq.heappop(pq) sum_value -= num * count return sum_value ```
0
0
['Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Python', 'C++', 'Java', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding window
sliding-window-by-wondertx-l3l6
IntuitionApproachComplexity Time complexity: Space complexity: Code
wondertx
NORMAL
2025-01-31T06:30:17.419910+00:00
2025-01-31T06:30:17.419910+00:00
9
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: std::vector<int> findXSum(const std::vector<int>& nums, int k, int x) const { std::vector<int> result; size_t left = 0; size_t right = k; std::unordered_map<int, int> num2freq; std::map<int, std::set<int, std::greater<int>>, std::greater<>> freq2num; for (size_t i = left; i < right; ++i) { int freq = num2freq[nums[i]]++; if (freq > 0) { freq2num[freq].erase(nums[i]); if (freq2num[freq].empty()) { freq2num.erase(freq); } } freq2num[freq + 1].insert(nums[i]); } int cnt = 0; int sum = 0; // X-sum for (auto it = freq2num.begin(); it != freq2num.end() && cnt < x; ++it) { for (auto it_inner = it->second.begin(); it_inner != it->second.end() && cnt < x; ++it_inner) { sum += *it_inner * num2freq[*it_inner]; ++cnt; } } result.push_back(sum); sum = 0; cnt = 0; while (right < nums.size()) { // Delete nums[left], update the freq2num and num2freq for nums[left] int freq = num2freq[nums[left]]--; freq2num[freq].erase(nums[left]); if (freq2num.empty()) { freq2num.erase(freq); } if (freq > 1) { freq2num[freq - 1].insert(nums[left]); } // Insert nums[right], update the freq2num and num2freq for nums[right] freq = num2freq[nums[right]]++; if (freq > 0) { freq2num[freq].erase(nums[right]); if (freq2num[freq].empty()) { freq2num.erase(freq); } } freq2num[freq + 1].insert(nums[right]); for (auto it = freq2num.begin(); it != freq2num.end() && cnt < x; ++it) { for (auto it_inner = it->second.begin(); it_inner != it->second.end() && cnt < x; ++it_inner) { sum += *it_inner * num2freq[*it_inner]; ++cnt; } } result.push_back(sum); sum = 0; cnt = 0; ++left; ++right; } return result; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
easy solution
easy-solution-by-owenwu4-2jic
Intuitionlots of requirements for this oneApproachComplexity Time complexity: Space complexity: Code
owenwu4
NORMAL
2025-01-29T15:40:48.374584+00:00
2025-01-29T15:40:48.374584+00:00
18
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> lots of requirements for this one # 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 ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: res = [] windowlen = k for i in range(len(nums) - windowlen + 1): subarr = nums[i: i + windowlen] print(subarr) d = defaultdict(int) for s in subarr: d[s] += 1 d = sorted(d.items(), key=lambda x: (x[1], x[0]), reverse=True) print(d) now = 0 cur = d[:x] for c in cur: now += (c[0] * c[1]) res.append(now) return res ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Two Java Solutions with PriorityQueue and TreeSet
two-java-solutions-with-priorityqueue-an-z2bk
IntuitionApproachComplexity Time complexity: Space complexity: Code
hchen229
NORMAL
2025-01-27T06:17:31.314813+00:00
2025-01-27T06:17:31.314813+00:00
15
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 int[] findXSum1(int[] nums, int k, int x) { int len = nums.length - k + 1; if (len < 1) { len = 1; } int[] result = new int[len]; HashMap<Integer, Integer> map = new HashMap<>(); // init map for ( int i = 0; i < k && i< nums.length; i++) { if (map.containsKey(nums[i])) { map.put(nums[i], map.get(nums[i]) + 1); } else { map.put(nums[i], 1); } } for (int i = 0; i < len; i++) { // count result[i] result[i] = sum1(map, x); //remove nums[i] map.put(nums[i], map.get(nums[i]) - 1); if ((i + k) < nums.length) { if (map.containsKey(nums[i + k])) { map.put(nums[i + k], map.get(nums[i + k]) + 1); } else { map.put(nums[i + k], 1); } } } return result; } int sum1(HashMap<Integer, Integer> map, int x) { PriorityQueue<Element> queue = new PriorityQueue<>(new MyComparator()); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { queue.add(new Element(entry.getValue(), entry.getKey())); } int sum = 0; for (int i = 0; i < x && !queue.isEmpty(); i++) { sum += queue.poll().sum(); } return sum; } public int[] findXSum(int[] nums, int k, int x) { int len = nums.length - k + 1; if (len < 1) { len = 1; } int[] result = new int[len]; HashMap<Integer, Element> map = new HashMap<>(); TreeSet<Element> treeSet = new TreeSet<>(new MyComparator()); // init map for ( int i = 0; i < k && i< nums.length; i++) { addOrIncreaseElement(treeSet, map, nums[i]); } for (int j = 0; j < len; j++) { // count result[j] result[j] = sum2(treeSet, x); // sliding window // remove first decreaseCount(treeSet, map.get(nums[j])); // add new if ((j + k) < nums.length) { addOrIncreaseElement(treeSet, map, nums[j + k]); } } return result; } private void addOrIncreaseElement(TreeSet<Element> treeSet, HashMap<Integer, Element> map, int num) { Element e = map.get(num); if (e != null) { increaseCount(treeSet, e); } else { e = new Element(1, num); map.put(num, e); treeSet.add(e); } } int sum2(TreeSet<Element> treeSet, int x) { Iterator<Element> it = treeSet.iterator(); int sum = 0; for (int i = 0; it.hasNext() && i < x; i++) { sum += it.next().sum(); } return sum; } private void increaseCount(TreeSet<Element> treeSet, Element element) { treeSet.remove(element); // must remove first, otherwise treeset cannot locate the element element.count++; treeSet.add(element); } private void decreaseCount(TreeSet<Element> treeSet, Element element) { treeSet.remove(element); element.count--; if (element.count > 0) { treeSet.add(element); } } class Element { int count; int val; Element(int count, int val) { this.count = count; this.val = val; } int sum() { return count * val; } } // descending class MyComparator implements Comparator<Element> { @Override public int compare(Element o1, Element o2) { if (o1.count != o2.count) { return o2.count - o1.count; } else { return o2.val - o1.val; } } } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
Simple 2 Approach Hash Table & Sliding Window
simple-hash-table-by-eskandar1-gihc
Complexity Time complexity: O(n*k) Space complexity: O(n)CodeComplexity Time complexity: O(n) Space complexity: O(n)Code
Eskandar1
NORMAL
2025-01-24T16:28:38.593954+00:00
2025-01-24T17:19:26.980349+00:00
28
false
# Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n*k) ---- - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n) ---- # Code ```cpp [] class Solution { public: vector<int> findXSum(vector<int>& nums, int k, int x) { vector<int>ans; for(int l=0; l+k<=nums.size(); l++){ vector<int>frq(51); vector<int>frqOfFrq(51); for(int r=l; r<l+k; r++){ frq[nums[r]]++; frqOfFrq[frq[nums[r]]]++; } int tmp=0, cnt=x; for(int i=50; cnt>0 && i>=0; i--){ if(!frqOfFrq[i]) continue; for(int j=50; cnt>0 && j>=0; j--){ if(frq[j]==i){ tmp +=(j*frq[j]); cnt--; } } } ans.push_back(tmp); } return ans; } }; ``` ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int[]ans = new int [nums.length-k+1]; int idx=0; for(int l=0; l+k<=nums.length; l++){ int[]frq = new int [51]; int[]frqOfFrq = new int [51]; for(int r=l; r<l+k; r++){ frq[nums[r]]++; frqOfFrq[frq[nums[r]]]++; } int tmp=0, cnt=x; for(int i=50; cnt>0 && i>=0; i--){ if(frqOfFrq[i]==0) continue; for(int j=50; cnt>0 && j>=0; j--){ if(frq[j]==i){ tmp +=(j*frq[j]); cnt--; } } } ans[idx++] = tmp; } return ans; } } ``` --------- -- Optimization sliding Window -- # 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(n) ---- # Code ```cpp [] class Solution { public: vector<int> findXSum(vector<int>& nums, int k, int x) { vector<int>ans; int l=0, r=0; vector<int>frq(51), frqOfFrq(51); while(l<=nums.size()-k){ while(r<l+k){ frq[nums[r]]++; frqOfFrq[frq[nums[r]]]++; r++; } int tmp=0, cnt=x; for(int i=50; cnt>0 && i>=0; i--){ if(!frqOfFrq[i]) continue; for(int j=50; cnt>0 && j>=0; j--){ if(frq[j]==i){ tmp +=(j*frq[j]); cnt--; } } } ans.push_back(tmp); frqOfFrq[frq[nums[l]]]--; frq[nums[l]]--; l++; } return ans; } }; ``` ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { int[]ans = new int [nums.length-k+1]; int[]frq = new int [51]; int[]frqOfFrq = new int [51]; int l=0, r=0, idx=0; while(l<=nums.length-k){ while(r<l+k){ frq[nums[r]]++; frqOfFrq[frq[nums[r]]]++; r++; } int tmp=0, cnt=x; for(int i=50; cnt>0 && i>=0; i--){ if(frqOfFrq[i]==0) continue; for(int j=50; cnt>0 && j>=0; j--){ if(frq[j]==i){ tmp +=(j*frq[j]); cnt--; } } } ans[idx++] = tmp; frqOfFrq[frq[nums[l]]]--; frq[nums[l]]--; l++; } return ans; } } ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'C++', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
Shortest & Easiest Brute - Force Approach with Detailed Explanation πŸ’‘ βœ…
shortest-easiest-brute-force-approach-wi-bmvq
Problem Recap πŸ“We have an array nums of integers, and we need to find the "x-sum" for each subarray of length k. The "x-sum" is calculated by keeping the occurr
Nitansh_Koshta
NORMAL
2025-01-22T13:25:24.577549+00:00
2025-01-22T13:25:24.577549+00:00
4
false
# Problem Recap πŸ“ *We have an array nums of integers, and we need to find the "x-sum" for each subarray of length k. The "x-sum" is calculated by keeping the occurrences of the x most frequent elements in the subarray. If two elements have the same frequency, the larger element is considered more frequent.* # Solution Explanation πŸš€ 1. Prepare the result array: We need to store the results for each subarray of length k, so we initialize an empty vector ans. This will hold the x-sum for each sliding window. 🏁 **vector<int> ans;** 2. Loop through the array with a sliding window: We will process each subarray of size k and compute the "x-sum" for it. We move this window from the start of the array to the end. 🏞️ The sliding window will slide one position at a time, so we loop through the array from index 0 to nums.size() - k. So, for each starting index i: **for (int i = 0; i <= nums.size() - k; i++) {** 3. Count element frequencies: For each subarray nums[i..i + k - 1], we need to count how often each number appears. We use an unordered_map (a hash map) to store the frequency of each element in the current window. πŸ”’ **unordered_map<int, int> freq; for (int j = i; j < i + k; j++) freq[nums[j]]++;** 4. Sort the elements by frequency and value: Now that we have the frequency of each element in the current window, we need to sort them by two criteria: * First by frequency (higher frequency comes first) πŸ† * If two elements have the same frequency, we sort by the value of the element (larger value comes first) 🎩 This is done by converting the unordered_map to a vector of pairs, and sorting them with a custom comparison function. πŸ§‘β€πŸ’» **vector<pair<int, int>> freqVec(freq.begin(), freq.end()); sort(freqVec.begin(), freqVec.end(), [](const pair<int, int>& a, const pair<int, int>& b) { if (a.second == b.second) return a.first > b.first; // Larger value comes first if frequencies are equal return a.second > b.second; // Higher frequency comes first });** 5. Calculate the x-sum for the current window: Now we need to calculate the "x-sum" by adding up the elements' values, but only for the top x most frequent elements. If there are fewer than x distinct elements, we sum them all up. We track how many elements we've added using the count variable. πŸ… **int sum = 0; int count = 0; for (auto p : freqVec) { if (count < x) { sum += p.first * p.second; // Add element * its frequency to the sum count++; } else break; // Stop once we’ve added `x` elements }** 6. Store the result for this subarray: After calculating the x-sum for the current window, we store it in the result vector ans. πŸ“₯ **ans.push_back(sum);** 7. Return the result: After we've processed all subarrays, we return the final result array ans. This contains the x-sum for each sliding window of size k. πŸŽ‰ **return ans;** # Visual Example Let's consider a simple example where nums = [1, 2, 2, 3, 4], k = 3, and x = 2. We will go through the sliding windows: 1. First window (nums[0..2] = [1, 2, 2]): * Frequencies: 1:1, 2:2 * Sorted: 2:2, 1:1 * x-sum: 2 * 2 + 1 * 1 = 5 2. Second window (nums[1..3] = [2, 2, 3]): * Frequencies: 2:2, 3:1 * Sorted: 2:2, 3:1 * x-sum: 2 * 2 + 3 * 1 = 7 3. Third window (nums[2..4] = [2, 3, 4]): * Frequencies: 2:1, 3:1, 4:1 * Sorted: 4:1, 3:1, 2:1 (Sorted by value because all have same frequency) * x-sum: 4 * 1 + 3 * 1 = 7 Final result: [5, 7, 7] 🎯 # Conclusion 🌟 ***In summary, the algorithm uses a sliding window to process each subarray of size k, counts the frequencies of elements, sorts them by frequency and value, and then calculates the x-sum based on the top x most frequent elements. The result is stored and returned as an array of x-sums for each subarray!*** # Code ```cpp [] class Solution { public: vector<int> findXSum(vector<int>& nums, int k, int x) { vector<int> ans; for (int i = 0; i <= nums.size() - k; i++) { unordered_map<int, int> freq; for (int j = i; j < i + k; j++) freq[nums[j]]++; vector<pair<int, int>> freqVec(freq.begin(), freq.end()); sort(freqVec.begin(), freqVec.end(), [](const pair<int, int>& a, const pair<int, int>& b) { if (a.second == b.second) return a.first > b.first; return a.second > b.second; }); int sum = 0; int count = 0; for (auto p : freqVec) { if (count < x) { sum += p.first * p.second; count++; } else break; } ans.push_back(sum); } return ans; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
C# | Dictionary | LINQ ORDERBY
c-dictionary-linq-orderby-by-codeme0720-8zp3
Code
codeme0720
NORMAL
2025-01-20T10:24:17.962452+00:00
2025-01-20T10:24:17.962452+00:00
22
false
# Code ```csharp [] public class CustomComparer : IComparer<KeyValuePair<int,int>> { public int Compare(KeyValuePair<int,int> x, KeyValuePair<int,int> y) { if(y.Value.CompareTo(x.Value)==1) return 1; if(y.Value.CompareTo(x.Value) == 0) return y.Key.CompareTo(x.Key); return -1; } } public class Solution { public int GetXSum(List<int> arr, int x) { Dictionary<int,int> dict = new Dictionary<int,int>(); foreach(var v in arr) { if(dict.ContainsKey(v)) dict[v]++; else dict[v] = 1; } var sDict = dict.OrderBy(item => item, new CustomComparer()); int tans = 0; int count = 0; foreach(var kvp in sDict) { tans += (kvp.Key*kvp.Value); count++; if(count == x) break; } return tans; } public int[] FindXSum(int[] nums, int k, int x) { List<int> ans = new List<int>(); List<int> lNums = new List<int>(nums); for(int i=0;i<nums.Length-k+1;i++) { var subArray = lNums.GetRange(i,k); int xSum = GetXSum(subArray,x); ans.Add(xSum); } return ans.ToArray(); } } ```
0
0
['C#']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding window for dictionary, 97% speed
sliding-window-for-dictionary-97-speed-b-y1v6
Code
evgenysh
NORMAL
2025-01-18T23:06:35.849978+00:00
2025-01-18T23:06:35.849978+00:00
28
false
# Code ```python3 [] class Solution: def sum_x(self, window: dict, freq: int) -> int: lst = [(window[key], key) for key in window] lst.sort(reverse=True) # Adjust the frequency to the minimum of the length of lst and freq freq = min(freq, len(lst)) return sum(lst[i][0] * lst[i][1] for i in range(freq)) def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: window_dict = dict() # Initialize the sliding window dictionary with the first 'k' elements for i in range(k): if nums[i] in window_dict: window_dict[nums[i]] += 1 else: window_dict[nums[i]] = 1 # Initialize the answer list with zeroes and set the first value ans = [0] * (len(nums) - k + 1) ans[0] = self.sum_x(window_dict, x) # Slide the window across the array for i in range(len(ans) - 1): # Decrement the frequency of the outgoing element window_dict[nums[i]] -= 1 if window_dict[nums[i]] == 0: window_dict.pop(nums[i]) # Increment the frequency of the incoming element right = i + k if nums[right] in window_dict: window_dict[nums[right]] += 1 else: window_dict[nums[right]] = 1 # Compute the sum for the current window and update the answer list ans[i + 1] = self.sum_x(window_dict, x) return ans ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Elixir - uses :gb_sets
elixir-uses-gb_sets-by-lykos_unleashed-8zmk
Complexity Time complexity: O(n * x log k) Space complexity: O(k) Code
Lykos_unleashed
NORMAL
2025-01-18T08:09:25.252640+00:00
2025-01-18T08:09:25.252640+00:00
2
false
# Complexity - Time complexity: O(n * x log k) - Space complexity: O(k) # Code ```elixir [] defmodule Solution do @spec find_x_sum(nums :: [integer], k :: integer, x :: integer) :: [integer] def find_x_sum(nums, k, x) do freq = Enum.take(nums, k) |> Enum.frequencies() count_gb_set = freq |> Enum.map(fn {num, count} -> {count, num} end) |> :gb_sets.from_list() first_res_val = find_most_freq_x_nums_sum(count_gb_set, x, 0) tuple = List.to_tuple(nums) length = tuple_size(tuple) if length <= k do [first_res_val] else for i <- k..(length - 1), reduce: {freq, count_gb_set, [first_res_val]} do {freq, count_gb_set, res} -> {freq, count_gb_set} = update_window(freq, count_gb_set, elem(tuple, i), elem(tuple, i - k)) {freq, count_gb_set, [find_most_freq_x_nums_sum(count_gb_set, x, 0) | res]} end |> elem(2) |> Enum.reverse() end end defp update_window(freq, count_gb_set, el_to_add, el_to_remove) do {freq, count_gb_set} = case Map.get(freq, el_to_add) do nil -> {Map.put(freq, el_to_add, 1), :gb_sets.add({1, el_to_add}, count_gb_set)} count -> count_gb_set = :gb_sets.delete({count, el_to_add}, count_gb_set) {Map.put(freq, el_to_add, count + 1), :gb_sets.add({count + 1, el_to_add}, count_gb_set)} end case Map.get(freq, el_to_remove) do 1 -> {Map.delete(freq, el_to_remove), :gb_sets.delete({1, el_to_remove}, count_gb_set)} count -> count_gb_set = :gb_sets.delete({count, el_to_remove}, count_gb_set) {Map.put(freq, el_to_remove, count - 1), :gb_sets.add({count - 1, el_to_remove}, count_gb_set)} end end defp find_most_freq_x_nums_sum(count_gb_set, x, res) do cond do :gb_sets.is_empty(count_gb_set) || x == 0 -> res true -> {{count, num}, count_gb_set} = :gb_sets.take_largest(count_gb_set) find_most_freq_x_nums_sum(count_gb_set, x - 1, res + (count * num)) end end end ```
0
0
['Elixir']
0
find-x-sum-of-all-k-long-subarrays-i
JavaScript + TypeScript Solution
javascript-typescript-solution-by-snake-dsoie
null
snake-eater
NORMAL
2025-01-16T22:05:17.111434+00:00
2025-01-16T22:05:17.111434+00:00
21
false
```typescript [] function findXSum(nums: number[], k: number, x: number): number[] { let res: number[] = [] let seen: Map<number, number> = new Map<number, number>() for(let i: number = 0; i < k; i++){ seen.set(nums[i], (seen.has(nums[i]) ? seen.get(nums[i]) : 0) + 1); } for(let i: number = 0; i < nums.length-k+1; i++){ const sortedHash = [...seen].sort((a, b) => (b[1] == a[1]) ? (b[0] - a[0]) : (b[1] - a[1])); let total: number = 0; for(let j: number = 0; j < Math.min(x, seen.size); j++){ total += sortedHash[j][0] * sortedHash[j][1] } seen.set(nums[i], seen.get(nums[i])-1); if(seen.get(nums[i]) == 0) seen.delete(nums[i]) seen.set(nums[i+k], (seen.has(nums[i+k]) ? seen.get(nums[i+k]) : 0) + 1); res.push(total) } return res; }; ```
0
0
['Hash Table', 'Sliding Window', 'Sorting', 'TypeScript', 'JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
N*x*LogK solution , Sliding Window + TreeSet solution
nxlogk-solution-sliding-window-treeset-s-u7dy
IntuitionFrom the description of the problem we can understand we need to have on demand sorting as at each instant and at each window we will want to have the
are_you_in_illusion
NORMAL
2025-01-13T08:25:58.273623+00:00
2025-01-13T08:25:58.273623+00:00
5
false
# Intuition From the description of the problem we can understand we need to have on demand sorting as at each instant and at each window we will want to have the elements sorted based on their occurrences .Hence for each subarray we treat it as a window and at each window the TreeSet maintains the sort order by their frequencies and we can just interate the top x elements # Approach For the window 0 to k -1 , use the hashMap to make the element -> frequencyMap Then for the rest of the subarrays from window start = i end = i + k - 1 remove the identity ( element and its old frequency ) of nums[start] and then add the identity (element + its new frequency ) Similarly do the same for the nums[end] P.S wondering if their is a way , we can have ondemand ans[i] update from ans[i - 1] . Because at max frequency of two elements are changing . # Complexity - Time complexity: O(N*LogK) N = Size Of the Array K = Size of the Subarray - Space complexity: K = TreeSet Size at any instance N- k + 1 = Answer Array Overall Size = N + 1 # Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { class Pair{ int first; int second; public Pair(int first , int second ) { this.first = first; this.second = second; } } HashMap<Integer , Integer > freq = new HashMap<>(); TreeSet<Pair> treeSet = new TreeSet<>( (a , b ) -> { if(b.second == a.second ) { return b.first - a.first; } return b.second - a.second; }); int n = nums.length; int[] ans = new int[n - k + 1 ]; for(int i = 0 ; i < n - k + 1 ; i ++ ) { ans[i] = 0; } for(int i = 0 ; i < k ; i ++ ) { freq.put(nums[i] , freq.getOrDefault(nums[i] , 0) + 1); } for(Map.Entry<Integer, Integer> entry : freq.entrySet()) { treeSet.add(new Pair(entry.getKey() , entry.getValue())); } Iterator<Pair> iterator = treeSet.iterator(); int cnt = 0 ; while(cnt < x && iterator.hasNext()) { Pair p = iterator.next(); ans[0] += p.first * p.second; //System.out.println(p.first + "," + p.second); cnt++; } for(int i = 1 ; i < n ; i ++ ) { int start = i ; int end = i + k - 1 ; if(end >= n ) { break; } // removing the start - 1 th element from the window int oldFreq = freq.getOrDefault(nums[start - 1] , 0); Pair p = new Pair(nums[i - 1] , oldFreq); // already existing node to be removed treeSet.remove(p); // removing it freq.put(nums[i - 1] , oldFreq - 1); // subtracting 1 freq as it is removed from the node treeSet.add(new Pair(nums[i - 1] , oldFreq - 1)); // adding a new node to the tree // add the new element , that is the end element to the window int newFreq = freq.getOrDefault(nums[end] , 0); // getting the existing freq from the node treeSet.remove(new Pair(nums[end] , newFreq )); // removing it from the TreeSet freq.put(nums[end] , newFreq + 1); // adding freq to the hashmap treeSet.add(new Pair(nums[end] , newFreq + 1 )); // adding new node to the TreeSet //System.out.println("\n"); cnt = 0 ; iterator = treeSet.iterator(); while(cnt < x && iterator.hasNext()) { p = iterator.next(); ans[i] += p.first * p.second; //System.out.println(p.first + "," + p.second); cnt++; } } return ans; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
N*x*LogK solution , Sliding Window + TreeSet solution
nxlogk-solution-sliding-window-treeset-s-g2x8
IntuitionApproachComplexity Time complexity: Space complexity: Code
are_you_in_illusion
NORMAL
2025-01-13T08:24:31.395844+00:00
2025-01-13T08:24:31.395844+00:00
5
false
# Intuition <!-- From the description of the problem we can understand we need to have on demand sorting as at each instant and at each window we will want to have the elements sorted based on their occurrences .Hence for each subarray we treat it as a window and at each window the TreeSet maintains the sort order by their frequencies and we can just interate the top x elements --> # Approach <!-- For the window 0 to k -1 , use the hashMap to make the element -> frequencyMap Then for the rest of the subarrays from window start = i end = i + k - 1 remove the identity ( element and its old frequency ) of nums[start] and then add the identity (element + its new frequency ) Similarly do the same for the nums[end] P.S wondering if their is a way , we can have ondemand ans[i] update from ans[i - 1] . Because at max frequency of two elements are changing . . --> # Complexity - Time complexity: <!-- O(N*LogK) N = Size Of the Array K = Size of the Subarray --> - Space complexity: <!-- K = TreeSet Size at any instance N- k + 1 = Answer Array Overall Size = N + 1 --> # Code ```java [] class Solution { public int[] findXSum(int[] nums, int k, int x) { class Pair{ int first; int second; public Pair(int first , int second ) { this.first = first; this.second = second; } } HashMap<Integer , Integer > freq = new HashMap<>(); TreeSet<Pair> treeSet = new TreeSet<>( (a , b ) -> { if(b.second == a.second ) { return b.first - a.first; } return b.second - a.second; }); int n = nums.length; int[] ans = new int[n - k + 1 ]; for(int i = 0 ; i < n - k + 1 ; i ++ ) { ans[i] = 0; } for(int i = 0 ; i < k ; i ++ ) { freq.put(nums[i] , freq.getOrDefault(nums[i] , 0) + 1); } for(Map.Entry<Integer, Integer> entry : freq.entrySet()) { treeSet.add(new Pair(entry.getKey() , entry.getValue())); } Iterator<Pair> iterator = treeSet.iterator(); int cnt = 0 ; while(cnt < x && iterator.hasNext()) { Pair p = iterator.next(); ans[0] += p.first * p.second; //System.out.println(p.first + "," + p.second); cnt++; } for(int i = 1 ; i < n ; i ++ ) { int start = i ; int end = i + k - 1 ; if(end >= n ) { break; } // removing the start - 1 th element from the window int oldFreq = freq.getOrDefault(nums[start - 1] , 0); Pair p = new Pair(nums[i - 1] , oldFreq); // already existing node to be removed treeSet.remove(p); // removing it freq.put(nums[i - 1] , oldFreq - 1); // subtracting 1 freq as it is removed from the node treeSet.add(new Pair(nums[i - 1] , oldFreq - 1)); // adding a new node to the tree // add the new element , that is the end element to the window int newFreq = freq.getOrDefault(nums[end] , 0); // getting the existing freq from the node treeSet.remove(new Pair(nums[end] , newFreq )); // removing it from the TreeSet freq.put(nums[end] , newFreq + 1); // adding freq to the hashmap treeSet.add(new Pair(nums[end] , newFreq + 1 )); // adding new node to the TreeSet //System.out.println("\n"); cnt = 0 ; iterator = treeSet.iterator(); while(cnt < x && iterator.hasNext()) { p = iterator.next(); ans[i] += p.first * p.second; //System.out.println(p.first + "," + p.second); cnt++; } } return ans; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding Window + Map Heap (Priority Queue)
sliding-window-map-heap-priority-queue-b-tmq3
ApproachStep-by-Step Explanation: Understanding the Input: You have an array nums that contains integers. For example, nums = [1, 1, 2, 2, 3, 4]. You also have
hokteyash
NORMAL
2025-01-08T18:54:03.818257+00:00
2025-01-08T18:54:03.818257+00:00
15
false
# Approach Step-by-Step Explanation: 1) Understanding the Input: You have an array nums that contains integers. For example, nums = [1, 1, 2, 2, 3, 4]. You also have two integers: k, which specifies the length of the subarrays you want to consider (e.g., k = 3), and x, which specifies how many of the most frequent elements you want to include in your sum (e.g., x = 2). 2) Setting Up the Result Array: You need to create an array res to store the x-sum for each subarray of length k. The size of this array will be n - k + 1, where n is the length of nums. This is because there are n - k + 1 possible starting points for subarrays of length k. For example, if n = 6 and k = 3, then res will have a size of 6 - 3 + 1 = 4. 3) Iterating Through the Array: You will use a loop to go through the array nums. The loop will run from 0 to n - k, which allows you to extract each subarray of length k. For each position i, you extract the subarray starting at index i and ending at index i + k - 1. This can be done using Arrays.copyOfRange(nums, i, i + k). For example, if i = 0, the subarray is [1, 1, 2]. If i = 1, the subarray is [1, 2, 2], and so on. 4) Counting Frequencies: For each subarray, you need to count how many times each number appears. This is done using a HashMap, where the key is the number and the value is its count. For example, for the subarray [1, 1, 2], the counts would be {1: 2, 2: 1} because 1 appears twice and 2 appears once. 5) Finding the Top x Frequent Elements: To find the top x most frequent elements, you can use a priority queue (or a max-heap). This data structure allows you to efficiently retrieve the elements with the highest frequency. You add all the entries from the frequency map to the priority queue. The priority queue is set up to sort first by frequency (in descending order) and then by value (also in descending order) if frequencies are the same. For example, if you have counts {1: 2, 2: 1}, the priority queue will prioritize 1 (because it has the highest frequency) over 2. 6) Calculating the x-sum: Initialize a variable sum to zero. This will hold the x-sum for the current subarray. Poll (remove) the top x elements from the priority queue. For each of these elements, calculate the contribution to the sum by multiplying the number by its frequency. For example, if the top two elements are 1 (2 times) and 2 (1 time), the x-sum would be calculated as 1 * 2 + 2 * 1 = 4. 7) Storing the Result: After calculating the x-sum for the current subarray, store this value in the res array at the index corresponding to the starting position of the subarray. For example, if you calculated the x-sum for the subarray starting at index 0, you would store it in res[0]. 8) Returning the Result: After processing all possible subarrays, return the res array, which now contains the x-sums for each subarray of length k. For example, if you processed all subarrays and calculated their x-sums, the final result might look like res = [4, 5, 7, 6] # Complexity - Time complexity: O(Nβˆ—Kβˆ—Log(K)) - Space complexity: O(N) # Code ```java [] class Solution { public int calSum(int []arr,int x){ Map<Integer, Integer> map = new HashMap<>(); for (int num : arr) { map.put(num, map.getOrDefault(num, 0) + 1); } // Create a priority queue to sort by frequency and then by value PriorityQueue<Map.Entry<Integer, Integer>>pq = new PriorityQueue<>((a,b) -> { if(a.getValue() == b.getValue()) return b.getKey()-a.getKey(); // Higher Value First return b.getValue()-a.getValue(); // Higher Frequency First }); pq.addAll(map.entrySet()); int cnt = 1, sum = 0; // Get the top x elements while (!pq.isEmpty() && cnt<=x) { Map.Entry<Integer, Integer> entry = pq.poll(); // Add the occurrences of the element to the sum sum+= entry.getKey()*entry.getValue(); cnt++; } return sum; } public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] res = new int[n - k + 1]; for (int i = 0; i <= n - k; i++) { // Get the current subarray of length k int[] temp = Arrays.copyOfRange(nums, i, i + k); // Calculate the x-sum for the current subarray res[i] = calSum(temp, x); } return res; } } ```
0
0
['Array', 'Sliding Window', 'Heap (Priority Queue)', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
Create NodeFreq class(contain compare)
create-nodefreq-classcontain-compare-by-del8b
IntuitionNot sure why search tuple item in sortedset doesn't work properly. Create a new class and keep updating is an acceptable way.ApproachComplexity Time co
linda2024
NORMAL
2025-01-08T18:50:22.083090+00:00
2025-01-08T18:50:22.083090+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Not sure why search tuple item in sortedset doesn't work properly. Create a new class and keep updating is an acceptable way. # 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 ```csharp [] public class Solution { public class NodeFreq { public int Val; public int Freq; public NodeFreq(int val, int freq) { Val = val; Freq = freq; } } public class NodeFSort : IComparer<NodeFreq> { public int Compare(NodeFreq a, NodeFreq b) { if (a.Freq != b.Freq) return b.Freq > a.Freq ? 1 : -1; return b.Val > a.Val ? 1 : -1; } } private int SumX(List<NodeFreq> sSet, int x) { int sum = 0; foreach (var cur in sSet) { sum += cur.Val * cur.Freq; if (--x == 0) break; } return sum; } private int FindIdx(List<NodeFreq> l, int val) { for (int i = 0; i < l.Count; i++) { if (l[i].Val == val) return i; } return -1; } public int[] FindXSum(int[] nums, int k, int x) { int len = nums.Length; List<NodeFreq> sortedSet = new List<NodeFreq>(); int firstPart = Math.Min(k, len); Dictionary<int, int> dict = new(); for (int i = 0; i < firstPart; i++) { if (!dict.ContainsKey(nums[i])) dict.Add(nums[i], 1); else dict[nums[i]]++; } foreach (var kvp in dict) { sortedSet.Add(new NodeFreq(kvp.Key, kvp.Value)); } int[] res = new int[len - k + 1]; for (int i = 0; i < res.Length; i++) { sortedSet.Sort(new NodeFSort()); res[i] = SumX(sortedSet, x); if (i == res.Length - 1) break; int next = nums[i + k]; if (dict.ContainsKey(next)) { int idx = FindIdx(sortedSet, next); sortedSet.RemoveAt(idx); dict[next]++; } else { dict.Add(next, 1); } sortedSet.Add((new NodeFreq(next, dict[next]))); var remIdx = FindIdx(sortedSet, nums[i]); sortedSet.RemoveAt(remIdx); if (--dict[nums[i]] == 0) { dict.Remove(nums[i]); } else { sortedSet.Add(new NodeFreq(nums[i], dict[nums[i]])); } } return res; } } ```
0
0
['C#']
0
find-x-sum-of-all-k-long-subarrays-i
3318. Find X-Sum of All K-Long Subarrays I
3318-find-x-sum-of-all-k-long-subarrays-uw7i3
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-08T08:17:13.035744+00:00
2025-01-08T08:17:13.035744+00:00
19
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 ```python3 [] from collections import Counter class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: result = [] for i in range(len(nums) - k + 1): # Get the current subarray nums[i:i+k] subarray = nums[i:i + k] # Count frequencies of elements in the subarray freq = Counter(subarray) # Sort elements by frequency, and by value in case of tie sorted_freq = sorted(freq.items(), key=lambda item: (-item[1], -item[0])) # Get the sum of the top `x` frequent elements x_sum = 0 for j in range(min(x, len(sorted_freq))): x_sum += sorted_freq[j][0] * sorted_freq[j][1] result.append(x_sum) return result ```
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Java | Efficient Solution | Easy to understand
java-efficient-solution-easy-to-understa-xyf3
IntuitionApproachComplexity Time complexity: Space complexity: Code
Mahammad_Khairuddin
NORMAL
2025-01-07T18:13:57.988524+00:00
2025-01-07T18:13:57.988524+00:00
10
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 int[] findXSum(int[] nums, int k, int x) { int [] resultArr = new int[nums.length-k+1]; for(int i =0; i<resultArr.length;i++){ Map<Integer,Integer> map = new HashMap<>(); int left = i; while(left<k+i){ map.put(nums[left],map.getOrDefault(nums[left++],0)+1); } PriorityQueue<Map.Entry<Integer,Integer>> pq = new PriorityQueue<>( (a,b)->{ if(a.getValue()==b.getValue()){ return b.getKey()-a.getKey(); } return b.getValue()-a.getValue(); } ); for(Map.Entry<Integer,Integer> entry : map.entrySet()){ pq.add(entry); } int currSum=0; for(int j=0; j<x; j++){ Map.Entry<Integer,Integer> num = pq.poll(); if(num != null){ currSum += num.getValue()*num.getKey(); } } resultArr[i] = currSum; } return resultArr; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
Java | Easy and simple solution to understand
java-easy-and-simple-solution-to-underst-4cbk
IntuitionApproachComplexity Time complexity: Space complexity: Code
Mahammad_Khairuddin
NORMAL
2025-01-07T17:47:23.023359+00:00
2025-01-07T17:47:23.023359+00:00
11
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 int[] findXSum(int[] nums, int k, int x) { int [] resultArr = new int[nums.length-k+1]; for(int i =0; i<resultArr.length;i++){ Map<Integer,Integer> map = new HashMap<>(); int currSum=0; int left = i; while(left<k+i){ currSum += nums[left]; map.put(nums[left],map.getOrDefault(nums[left++],0)+1); } if(k==x) resultArr[i] = currSum; else{ PriorityQueue<Integer> pq = new PriorityQueue<>( (a,b)->{ if(map.get(a)==map.get(b)){ return b-a; } return map.get(b)-map.get(a); } ); for(Integer key : map.keySet()){ pq.add(key); } currSum=0; for(int j=0; j<x; j++){ Integer num = pq.poll(); if(num != null){ currSum += num*map.get(num); } } resultArr[i] = currSum; } } return resultArr; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
PriorityQueue solution using TreeMap.
priorityqueue-solution-using-treemap-by-u82tm
IntuitionUse a Map and MaxHeap to allow retrieval of most frequent elements from the given array, and compute sum from the array[i...i+k-1]ApproachFor each iter
utk1801
NORMAL
2025-01-07T03:12:53.378692+00:00
2025-01-07T03:12:53.378692+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Use a Map and MaxHeap to allow retrieval of most frequent elements from the given array, and compute sum from the array[i...i+k-1] # Approach <!-- Describe your approach to solving the problem. --> For each iteration create a map of current set of elements, store the map entry in PriorityQueue and compute sum. Logic for compute Sum: compute sum of elements in the pq, multiplying each element with the frequency of the element in the map. # 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 { PriorityQueue<Map.Entry<Integer,Integer>> pq; Map<Integer,Integer> map; public int[] findXSum(int[] nums, int k, int x) { map = new TreeMap<>(); int n=nums.length; pq=new PriorityQueue<>((a,b)->(a.getValue()==b.getValue()?b.getKey()-a.getKey():b.getValue()-a.getValue())); int[] res=new int[n-k+1]; for(int i=0;i<n-k+1;i++){ res[i]=xSum(nums,i,k,x); } return res; } int xSum(int[] nums, int i, int k, int x){ // if (map.size() < x) return cdf(nums); map.clear(); pq.clear(); for(int loop=i;loop<i+k;loop++){ map.put(nums[loop],map.getOrDefault(nums[loop],0)+1); } // System.out.println(map); for(Map.Entry<Integer,Integer> entry:map.entrySet()) pq.add(entry); // System.out.println("priority q: " + pq); int[] arr=new int[x]; int a=0,sum=0; if(pq.size()<x) return cdf(pq); while(a<x){ int topElement = pq.poll().getKey(); sum+=topElement * map.get(topElement); a++; } return sum; } int cdf(PriorityQueue<Map.Entry<Integer,Integer>> pq){ int sum=0; for(Map.Entry<Integer,Integer> e:pq){ sum+=e.getKey()*e.getValue(); } return sum; } } ```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
sliding window with sort map
sliding-window-with-sort-map-by-zeroqs-whqt
Code
zeroqs
NORMAL
2025-01-05T12:36:14.205704+00:00
2025-01-05T12:36:14.205704+00:00
21
false
# Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @param {number} x * @return {number[]} */ var findXSum = function (nums, k, x) { let begin = 0 let windowState = new Map() let result = [] for (let end = 0; end < nums.length; end++) { windowState.set(nums[end], (windowState.get(nums[end]) || 0) + 1) if (end - begin + 1 === k) { result.push(xSum(windowState, x)) windowState.set(nums[begin], windowState.get(nums[begin]) - 1) if (windowState.get(nums[begin]) === 0) windowState.delete(nums[begin]) begin++ } } return result }; function xSum(map, x) { let entries = Array.from(map.entries()); entries.sort((a, b) => { if (b[1] === a[1]) return b[0] - a[0]; return b[1] - a[1]; }); let sum = 0; for (let i = 0; i < Math.min(x, entries.length); i++) { sum += entries[i][0] * entries[i][1]; } return sum; } ```
0
0
['Hash Table', 'Sliding Window', 'JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
Simple solution using counter and heap
simple-solution-using-counter-and-heap-b-efly
Code
tripti15
NORMAL
2025-01-03T07:28:09.553686+00:00
2025-01-03T07:28:09.553686+00:00
24
false
# Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: from collections import Counter import heapq i=0 ans=[] n=len(nums)-k+1 while n: c=Counter(nums[i:i+k]) hps=[] for key, v in c.items(): heapq.heappush(hps,(-v,-key)) s=0 for j in range(x): if hps: v,key=heapq.heappop(hps) s+=(v*key) ans.append(s) i+=1 n-=1 return ans ```
0
0
['Heap (Priority Queue)', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Simple Approach
simple-approach-by-kajal_2-8w5n
IntuitionApproachComplexity Time complexity: O(nβ‹…klogk) Space complexity: O(n) Code
Kajal_2
NORMAL
2025-01-03T06:56:13.463067+00:00
2025-01-03T06:56:13.463067+00:00
11
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(nβ‹…klogk) <!-- 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 { public: vector<int> findXSum(vector<int>& nums, int k, int x) { int n = nums.size(); vector<int> answer; unordered_map<int, int> freq; priority_queue<pair<int, int>> pq; // max-heap to track frequencies // Initialize frequency map and max-heap for the first window for (int j = 0; j < k; j++) { freq[nums[j]]++; } // Fill the priority queue with the first k elements (without re-building in each window) for (auto& entry : freq) { pq.push({entry.second, entry.first}); } // Calculate the x-sum for the first window answer.push_back(calculateXSum(pq, x)); // Sliding window to process remaining elements for (int i = 1; i <= n - k; i++) { // Remove the element going out of the window freq[nums[i - 1]]--; if (freq[nums[i - 1]] == 0) { freq.erase(nums[i - 1]); } // Add the new element coming into the window freq[nums[i + k - 1]]++; // Rebuild the priority queue from the frequency map (to handle element removal) pq = priority_queue<pair<int, int>>(); // clear the priority queue for (auto& entry : freq) { pq.push({entry.second, entry.first}); } // Calculate the x-sum for the current window answer.push_back(calculateXSum(pq, x)); } return answer; } private: int calculateXSum(priority_queue<pair<int, int>>& pq, int x) { int sum = 0; int count = 0; // Sum the top x elements from the priority queue while (!pq.empty() && count < x) { auto top = pq.top(); pq.pop(); sum += top.second * top.first; // value * frequency count++; } return sum; } }; ```
0
0
['C++']
0
find-x-sum-of-all-k-long-subarrays-i
Hashmap || Max-Heap || Priority Queue || Sliding Window-I
hashmap-max-heap-priority-queue-sliding-97gu5
IntuitionApproachComplexity Time complexity: Space complexity: Code
devansh_dubey
NORMAL
2024-12-31T10:13:39.983214+00:00
2024-12-31T10:13:39.983214+00:00
12
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 { int xsum(vector<int>& nums,unordered_map<int,int>& store, int k, int x,int index){ priority_queue<pair<int,int>> pq; int ans = 0; for(auto it = store.begin();it!=store.end();it++){ pq.push({it->second,it->first}); } while(x-- && !pq.empty()){ ans += pq.top().first * pq.top().second; pq.pop(); } return ans; } public: vector<int> findXSum(vector<int>& nums, int k, int x) { unordered_map<int,int> store; for(int i = 0;i<nums.size() && i<k;i++){ if(!store[nums[i]]){ store[nums[i]] = 1; } else{ store[nums[i]]++; } } vector<int> answer(nums.size()-k+1,0); for(int i = 0;i<nums.size()-k+1;i++){ answer[i] = xsum(nums,store,k,x,i); store[nums[i]]--; if(i+k<nums.size()){ if(!store[nums[i+k]]){ store[nums[i+k]] = 1; } else{ store[nums[i+k]]++; } } } return answer; } }; ```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
🦍 Dumb python3 solution by Ape 🦍
dumb-python3-solution-by-ape-by-jithu743-qfvb
Intuition🦍 Ape recomputes the counter for each iteration instead of sliding a window 🦍🦍 Ape no slide cos not enough bananas 🍌 1 <= n == nums.length <= 50Code🦍 A
jithu7432
NORMAL
2024-12-23T18:41:39.932460+00:00
2024-12-23T18:41:39.932460+00:00
23
false
# Intuition 🦍 Ape recomputes the counter for each iteration instead of sliding a window 🦍 🦍 Ape no slide cos not enough bananas 🍌 `1 <= n == nums.length <= 50` # Code ```python3 [] class Solution: def findXSum(self, nums: List[int], k: int, x: int) -> List[int]: def get_max(arr): cc = [(-c, -e) for e,c in Counter(arr).items()] heapify(cc) s = 0 for _ in range(x): if cc: c, e = heappop(cc) s += e*c return s val = [] for i in range(0, len(nums)-k+1): arr = nums[i:i+k] val.append(get_max(arr)) return val ``` 🦍 Ape together stronk 🦍
0
0
['Python3']
0
find-x-sum-of-all-k-long-subarrays-i
3318. Find X-Sum of All K-Long Subarrays I
3318-find-x-sum-of-all-k-long-subarrays-gcy4i
IntuitionWhen approaching this problem, I was reminded of the sliding window technique commonly used to solve the maximum sum of a subarray problem. In this con
SangharshVMore
NORMAL
2024-12-23T14:05:28.155695+00:00
2024-12-23T14:05:28.155695+00:00
14
false
# Intuition When approaching this problem, I was reminded of the sliding window technique commonly used to solve the maximum sum of a subarray problem. In this context, we need to keep track of the frequency of elements within each sliding window and prioritize them to find the top x most frequent elements. To achieve this, I used a custom comparator to handle the frequency and value of elements. By employing a priority queue, I was able to efficiently manage the elements based on their frequencies and compute the x-sum for each window. # Approach 1.Custom Comparator Class: Define a class Freq that implements Comparable<Freq> to store the value and frequency of each element. Implement the compareTo method to sort the elements based on their frequency. If frequencies are equal, sort them by their value in reverse order. 2.Sliding Window Technique: Initialize a frequency array to keep track of the count of each element within the current window. Use a priority queue to manage and retrieve the elements with the highest frequencies in each window. # Complexity - Time complexity: O(nlogk) - Space complexity: O(n+k). <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public class Freq implements Comparable<Freq> { int val; int freq; public Freq(int val, int freq) { this.val = val; this.freq = freq; } @Override public int compareTo(Freq v2) { if (this.freq == v2.freq) { // If frequencies are the same, return the comparison of values in reverse order return Integer.compare(v2.val, this.val); } else { // Compare frequencies normally (higher frequency comes first) return Integer.compare(v2.freq, this.freq); } } } public int[] findXSum(int[] nums, int k, int x) { int n = nums.length; int[] freq = new int[51]; // Frequency array (1 <= nums[i] <= 50) int[] result = new int[n - k + 1]; // Result array PriorityQueue<Freq> pq = new PriorityQueue<>(); // Initializing the first window for (int i = 0; i < k; i++) { freq[nums[i]]++; } // Sliding window processing for (int i = 0; i <= n - k; i++) { if (i > 0) { // Update frequency for sliding window freq[nums[i - 1]]--; // Element leaving the window freq[nums[i + k - 1]]++; // Element entering the window } // Rebuild the priority queue based on current frequencies pq.clear(); for (int j = 1; j <= 50; j++) { if (freq[j] > 0) { pq.add(new Freq(j, freq[j])); } } // Compute x-sum int sum = 0, count = 0; while (!pq.isEmpty() && count < x) { Freq top = pq.poll(); sum += top.val * top.freq; count++; } result[i] = sum; } return result; } } ```
0
0
['Heap (Priority Queue)', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
PriorityQueue (Min heap) + Sliding Window Solution in Java
priorityqueue-min-heap-sliding-window-so-kzf6
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
soham15
NORMAL
2024-12-03T23:06:54.740238+00:00
2024-12-03T23:06:54.740259+00:00
56
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n * log(x))\n\n- Space complexity:\nO(k)\n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n Map<Integer, Integer> count = new HashMap<>();\n PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b) -> {\n if (count.get(a) == count.get(b)) {\n return a - b;\n } else {\n return count.get(a) - count.get(b);\n }\n });\n int n = nums.length;\n int[] ans = new int[n - k + 1];\n for (int i = 0; i < k; i++) {\n count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);\n }\n for (int key : count.keySet()) {\n minHeap.offer(key);\n if (minHeap.size() > x) {\n minHeap.poll();\n }\n }\n ans[0] = calculateXSum(count, minHeap);\n for (int i = k; i < n; i++) {\n count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);\n int outgoing = nums[i - k];\n count.put(outgoing, count.get(outgoing) - 1);\n if (count.get(outgoing) == 0) {\n count.remove(outgoing);\n }\n minHeap.clear();\n for (int key : count.keySet()) {\n minHeap.offer(key);\n if (minHeap.size() > x) {\n minHeap.poll();\n }\n }\n ans[i - k + 1] = calculateXSum(count, minHeap);\n }\n\n return ans;\n }\n\n public int calculateXSum(Map<Integer, Integer> count, PriorityQueue<Integer> minHeap) {\n int sum = 0;\n for (int num : minHeap) {\n sum += num * count.get(num);\n }\n return sum;\n }\n}\n```
0
0
['Sliding Window', 'Heap (Priority Queue)', 'Java']
1
find-x-sum-of-all-k-long-subarrays-i
Easiest Solution in Java
easiest-solution-in-java-by-mayankbisht8-k0km
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
MayankBisht8630
NORMAL
2024-12-01T14:51:46.043656+00:00
2024-12-01T14:51:46.043683+00:00
17
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 Pair{\n int first;\n int second;\n \n public Pair(int first, int second){\n this.first = first;\n this.second = second;\n }\n}\n\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n \n int[] ans = new int[n-k+1];\n for(int i=0; i<n-k+1; i++){\n Map<Integer, Integer> map = new HashMap<>();\n for(int j=i; j<i+k; j++){\n map.put(nums[j], map.getOrDefault(nums[j], 0)+1);\n }\n \n List<Pair> list = new ArrayList<>();\n for(int key:map.keySet()){\n list.add(new Pair(map.get(key), key));\n }\n Collections.sort(list, (Pair a, Pair b)->{\n if(a.first==b.first){\n return b.second-a.second;\n }\n return b.first-a.first;\n });\n \n int sum = 0;\n int uniq = 0;\n for(Pair l:list){\n if(uniq >= x){\n break;\n }\n \n sum += l.first*l.second;\n uniq++;\n }\n ans[i]=sum;\n }\n return ans;\n }\n}\n```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
Easy solution brute force
easy-solution-brute-force-by-_jyoti_geek-o4ef
Code\njava []\nclass Solution {\n class Pair{\n int val;\n int count;\n\n Pair(int a, int b){\n val = a;\n count =
_jyoti_geek
NORMAL
2024-11-28T17:00:14.620214+00:00
2024-11-28T17:00:14.620249+00:00
17
false
# Code\n```java []\nclass Solution {\n class Pair{\n int val;\n int count;\n\n Pair(int a, int b){\n val = a;\n count = b;\n }\n }\n\n public int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n\n int j = 0;\n int[] ans = new int[n-k+1];\n for(int i=k-1;i<n;i++){\n ans[j] = helper(nums, j, i, x);\n j++;\n }\n return ans;\n }\n\n public int helper(int[] arr, int low, int high, int x){\n PriorityQueue<Pair> pq = new PriorityQueue<>((a,b)->(b.count==a.count?b.val-a.val:b.count-a.count));\n HashMap<Integer, Integer> map = new HashMap<>();\n int sum = 0;\n for(int i=low;i<=high;i++){\n sum += arr[i];\n map.put(arr[i], map.getOrDefault(arr[i], 0)+1);\n }\n if(map.size()<x){\n return sum;\n }\n sum = 0;\n\n for(Map.Entry<Integer,Integer> it : map.entrySet()){\n pq.add(new Pair(it.getKey(), it.getValue()));\n }\n\n int ct = 0;\n while(ct!=x && pq.size()!=0){\n Pair p = pq.poll();\n sum += p.val*p.count;\n ct++;\n }\n return sum;\n }\n}\n```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'Java']
0
find-x-sum-of-all-k-long-subarrays-i
Simple Scala with custom Ordering and Sliding Window
simple-scala-with-custom-ordering-and-sl-ftmn
Code\nscala []\nobject Solution {\n def countOccurrences(a: Array[Int]) : Map[Int, Int] = a.groupMapReduce[Int, Int](identity)(_ => 1)(_ + _)\n def sortOc
sblackmon
NORMAL
2024-11-24T16:28:03.869852+00:00
2024-11-24T16:28:03.869876+00:00
1
false
# Code\n```scala []\nobject Solution {\n def countOccurrences(a: Array[Int]) : Map[Int, Int] = a.groupMapReduce[Int, Int](identity)(_ => 1)(_ + _)\n def sortOccurrenceCountPairs(m: Map[Int, Int]): Seq[(Int, Int)] = m.view.toSeq.sortWith(\n (_, _) match {\n case (e1, e2) if e1._2 > e2._2 => true\n case (e1, e2) if e1._2 < e2._2 => false\n case (e1, e2) if e1._1 > e2._1 => true\n case _ => false\n }\n )\n def computeXSum(a: Array[Int], x: Int) : Int = {\n // Count the occurrences of all elements in the array.\n val occurrenceCounts: Map[Int, Int] = countOccurrences(a)\n // Keep only the occurrences of the top x most frequent elements.\n // If two elements have the same number of occurrences, the element with the bigger value is considered more frequent.\n val sortedOccurrenceCountPairs: Seq[(Int, Int)] = sortOccurrenceCountPairs(occurrenceCounts)\n // Calculate the sum of the resulting array.\n val answer : Int = sortedOccurrenceCountPairs.take(x).map[Int]((k,v) => k * v).sum\n answer\n }\n def findXSum(nums: Array[Int], k: Int, x: Int): Array[Int] = {\n val windows: Iterator[Array[Int]] = nums.sliding(k)\n val answers : Array[Int] = windows.map(computeXSum(_, x)).toArray\n answers\n }\n}\n```
0
0
['Scala']
0
find-x-sum-of-all-k-long-subarrays-i
Find X-Sum
find-x-sum-by-shamshaddav12-ya8x
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
shamshaddav12
NORMAL
2024-11-24T15:35:25.745995+00:00
2024-11-24T15:35:25.746030+00:00
7
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 int[] findXSum(int[] nums, int k, int x) {\n int n = nums.length;\n int[] res = new int[n - k + 1];\n int[][] freq = new int[51][2];\n // store the number in 2D array\n for (int i = 0; i < 51; i++)\n \tfreq[i][0] = i;\n // count the frequency of the first k numbers\n for (int i = 0; i < k; i++)\n \tfreq[nums[i]][1]++;\n res[0] = sum(freq, x);\n // sliding window\n for (int i = 1, j = k; j < n; i++, j++) {\n \tfreq[nums[i - 1]][1]--;\n \tfreq[nums[j]][1]++;\n \tres[i] = sum(freq, x);\n }\n return res;\n }\n int sum(int[][] freq, int x) {\n \tArrays.sort(freq, (a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]);\n \tint sum = 0;\n \tfor (int i = 0; i < x; i++)\n \t\tsum += freq[i][0] * freq[i][1];\n Arrays.sort(freq, (a, b) -> a[0] - b[0]);\n \treturn sum;\n }\n}\n```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
sliding window, hash and sort on js and ts.
sliding-window-hash-and-sort-on-js-and-t-v33p
Code\njavascript []\nfunction findXSum(nums, k, x) {\n let l = 0\n const res = []\n const freq = {}\n for (let r = 0; r < nums.length; r++) {\n
anuchataowkaen
NORMAL
2024-11-18T18:20:06.916840+00:00
2024-11-18T18:20:06.916868+00:00
27
false
# Code\n```javascript []\nfunction findXSum(nums, k, x) {\n let l = 0\n const res = []\n const freq = {}\n for (let r = 0; r < nums.length; r++) {\n // if out of window update left and freq\n if (r - l + 1 > k) {\n freq[nums[l]]--\n l++\n }\n\n // update right and freq\n freq[nums[r]] = (freq[nums[r]] || 0) + 1\n\n // if stay at window\n if (r - l + 1 === k) {\n // convert freq to arr\n const arr = []\n for (const key in freq) arr.push([key, freq[key]])\n\n // then sort if same value use element compare else use value\n // [element, frequency]\n arr.sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1])\n\n // final sum by x\n let sum = 0\n for (let i = 0; i < x; i++) {\n if (arr[i]) sum += (arr[i][0] * arr[i][1])\n }\n \n // push result\n res.push(sum)\n }\n }\n return res\n};\n```\n```typescript []\nfunction findXSum(nums: number[], k: number, x: number): number[] {\n let l = 0\n const res = []\n const freq = {}\n for (let r = 0; r < nums.length; r++) {\n // if out of window update left and freq\n if (r - l + 1 > k) {\n freq[nums[l]]--\n l++\n }\n\n // update right and freq\n freq[nums[r]] = (freq[nums[r]] || 0) + 1\n\n // if stay at window\n if (r - l + 1 === k) {\n // convert freq to arr\n const arr = []\n for (const key in freq) arr.push([key, freq[key]])\n\n // then sort if same value use element compare else use value\n // [element, frequency]\n arr.sort((a, b) => a[1] === b[1] ? b[0] - a[0] : b[1] - a[1])\n\n // final sum by x\n let sum = 0\n for (let i = 0; i < x; i++) {\n if (arr[i]) sum += (arr[i][0] * arr[i][1])\n }\n \n // push result\n res.push(sum)\n }\n }\n return res\n};\n```
0
0
['Array', 'Hash Table', 'Sliding Window', 'TypeScript', 'JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
Beats 80% of C++ Users || Solution using Simple Hash Table
beats-80-of-c-users-solution-using-simpl-3akb
Intuition\nMin Heap, Sorting, Hash Table\n\n# Approach\nFirst count the frequency of each element till \'k\' and then perform operation as say in question\n\n#
dk8818604
NORMAL
2024-11-15T17:20:29.596831+00:00
2024-11-15T17:20:29.596882+00:00
17
false
# Intuition\nMin Heap, Sorting, Hash Table\n\n# Approach\nFirst count the frequency of each element till \'k\' and then perform operation as say in question\n\n# Complexity\n- Time complexity:\nO(n*logn)\n\n- Space complexity:\nO(n)\n![Screenshot 2024-11-15 224739.png](https://assets.leetcode.com/users/images/dc46fa6e-ef10-4b80-971b-58fe681e2290_1731691224.776664.png)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n int n=nums.size();\n unordered_map<int,int> mp;\n for(int i=0; i<k; i++){\n mp[nums[i]]++;\n }\n vector<int> ans;\n int u=0;\n while(k<=n){\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;\n for(auto k : mp){\n pq.push({k.second,k.first});\n if(pq.size()>x) pq.pop();\n }\n int sum=0;\n while(pq.size()>0){\n int frq=pq.top().first;\n int num=pq.top().second;\n pq.pop();\n sum+=num*frq;\n }\n ans.push_back(sum);\n k++;\n if(k>n) break;\n mp[nums[u]]--;\n if(mp[nums[u]]==0) mp.erase(nums[u]);\n mp[nums[k-1]]++;\n u++;\n }\n return ans;\n }\n};\n```
0
0
['Array', 'Hash Table', 'Sliding Window', 'Heap (Priority Queue)', 'C++']
0
find-x-sum-of-all-k-long-subarrays-i
Sliding Window and Hash Table
sliding-window-and-hash-table-by-raghavi-tri7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSliding Window and Hash_table\n\n# Complexity\n- Time complexity:\n Add y
raghavi
NORMAL
2024-11-13T21:27:16.312308+00:00
2024-11-13T21:27:16.312334+00:00
43
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSliding Window and Hash_table\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNot the Best OK Solution - O(N\u2217K\u2217Log(K)+N\u2217K)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n \n result = []\n\n for i in range(len(nums)-k+1):\n\n curr_elem = nums[i:i+k]\n sorted_dict = sorted(Counter(curr_elem).items(),key=lambda x:(-x[1],-x[0]))[:x]\n result.append(sum([v[0]*v[1] for v in sorted_dict]))\n \n return result\n\n\n\n```
0
0
['Sliding Window', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
O(n*k) in Rust but still beats 100%
onk-in-rust-but-still-beats-100-by-maksi-px6u
Intuition\n Describe your first thoughts on how to solve this problem. \nYou can save k iterations for every n element by implementing a sliding windows approac
maksimov
NORMAL
2024-11-12T20:48:21.623468+00:00
2024-11-12T20:48:21.623493+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can save k iterations for every n element by implementing a sliding windows approach for calculating freq of element in the subarray.\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$$O(n*k)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```rust []\nuse std::collections::HashMap;\nuse std::collections::BinaryHeap;\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn find_x_sum(nums: Vec<i32>, k: i32, x: i32) -> Vec<i32> {\n let n = nums.len() as i32;\n let mut freq = HashMap::new();\n let mut ans = vec![];\n\n nums[..k as usize].iter().for_each(|&n| *freq.entry(n).or_insert(0) += 1);\n\n for start in 1..n-k+2 {\n let mut sum = 0;\n\n let mut popular = BinaryHeap::new();\n for (v, f) in freq.iter() {\n popular.push((*f,*v));\n }\n //let mut popular: BinaryHeap<(i32, i32)> = freq.iter().map(|(&v, &f)| (f, v)).collect(); \n\n for i in 0..x {\n if let Some((f, v)) = popular.pop() {\n sum += f*v;\n } \n }\n ans.push(sum);\n\n if start + k < n+1 {\n let prev = nums[(start-1) as usize];\n let new = nums[(start + k-1) as usize];\n\n if let Some(f) = freq.get_mut(&prev) { \n *f -= 1;\n if (*f == 0) {\n freq.remove(&prev);\n }\n }\n\n *freq.entry(new).or_insert(0) += 1;\n } \n\n }\n \n ans\n }\n}\n```
0
0
['Rust']
0
find-x-sum-of-all-k-long-subarrays-i
Java - Heap - beats 96.27%
java-heap-beats-9627-by-mangdelamang-0b6m
Intuition\nThere\'s really no intuition here because this is a medium problem disguised as an easy and ya\'ll are ridiculous, honestly. \n\n# Approach\n1 - you
mangdelamang
NORMAL
2024-11-12T19:25:18.130889+00:00
2024-11-12T19:25:18.130917+00:00
9
false
# Intuition\nThere\'s really no intuition here because this is a medium problem disguised as an easy and ya\'ll are ridiculous, honestly. \n\n# Approach\n1 - you need a nested for loop to iterate through the the sub arrays. The bounds are just a little tricky, but they\'re below. \n2 - you create a heap (priority queue) that sorts by two criteria: the number of occurrences, and then the actual number itself. The comparator below does that for you. \n3 - process the answer. \n\n# Complexity\n- Time complexity:\nI\'m not sure... looks like O(n * log(n)) for the heap processing\n\n- Space complexity:\nO(n) since there\'s a heap allocated that is, at maximum, the size of nums. It gets reclaimed continually. \n\n# Code\n```java []\nclass Solution {\n public int[] findXSum(int[] nums, int k, int x) {\n\n // k is the length of the answer... \n int[] ans = new int[nums.length - k + 1];\n for(int i = 0; i <= nums.length - k; i++) { // offset\n int[] count = new int[51]; \n // process:\n for(int j = i; j < k+i; j++) {\n count[nums[j]]++; \n }\n int sum = xSum(count, x); \n ans[i] = sum; \n }\n return ans;\n }\n\n public int xSum(int[] count, int x) {\n PriorityQueue<int[]> heap = new PriorityQueue<>(new Comparator<int[]>() {\n @Override public int compare(int[] a, int[] b) {\n if(a[1] != b[1]) {\n return b[1] - a[1];\n }\n else {\n return b[0] - a[0];\n }\n }\n }); \n for(int i = 0; i < count.length; i++) {\n if(count[i] > 0) {\n heap.offer(new int[]{i, count[i]});\n }\n }\n\n int sum = 0;\n for(int i = 0; i < x && ! heap.isEmpty(); i++) {\n int[] num = heap.poll(); \n sum += num[0] * num[1];\n }\n return sum; \n }\n}\n```
0
0
['Java']
0
find-x-sum-of-all-k-long-subarrays-i
pure C
pure-c-by-ekko3add-9vbg
Approach\n1. Sliding window\n- Use two pointer, left and right to mark the boundaries of the sliding window.\n- Move right to right until its size reaches k\n-
ekko3add
NORMAL
2024-11-09T15:13:51.722571+00:00
2024-11-09T15:13:51.722604+00:00
10
false
# Approach\n1. Sliding window\n- Use two pointer, left and right to mark the boundaries of the sliding window.\n- Move right to right until its size reaches ```k```\n- Once the size reaches, calculate the sum of elements in the window and then move left.\n2. Calculate the sum of top ```x``` elements.\n- Traverse all elements in the window and use ```nodeEntry``` structure to store the count of each number.\n- Use ```qsort()``` which sort by their frequency in descending order first, and sort by the value.\n- Finally, calculate the sum of the ```x```\n\n# Complexity\n- Time complexity: \n$$O((n - k + 1) * (k + k log k))$$ \n= $$O(n * klog k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```c []\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\n\n#define MAX_LEN 50\n\ntypedef struct {\n int val;\n int count;\n} nodeEntry;\n\nint cmp(const void *a, const void *b) {\n nodeEntry *node1 = (nodeEntry*)a;\n nodeEntry *node2 = (nodeEntry*)b;\n\n if (node1->count != node2->count) {\n return node2->count - node1->count;\n }\n\n return node2->val - node1->val;\n}\n\nint calcXSum(int *nums, int left, int right, int x) {\n int size = right - left + 1;\n int nodeCount = 0, sum = 0;\n nodeEntry nodes[size];\n\n if (size <= x) {\n for (int i = left; i <= right; ++i) {\n sum += nums[i];\n }\n\n return sum;\n }\n\n for (int i = left; i <= right; ++i) {\n bool found = false;\n for (int j = 0; j < nodeCount; ++j) {\n if (nodes[j].val == nums[i]) {\n nodes[j].count +=1;\n found = true;\n break;\n }\n }\n\n if (!found) {\n nodes[nodeCount].val = nums[i];\n nodes[nodeCount].count = 1;\n ++nodeCount;\n }\n }\n\n qsort(nodes, nodeCount, sizeof(nodeEntry), cmp);\n for (int i = 0; i < x && i < nodeCount; ++i) {\n sum += (nodes[i].val * nodes[i].count);\n }\n\n return sum;\n}\n\nint* findXSum(int* nums, int numsSize, int k, int x, int* returnSize) {\n *returnSize = numsSize - k + 1;\n int *ans = calloc(*returnSize, sizeof(int));\n int idx = 0;\n\n int left = 0, right = 0, sum = 0;\n while (right < numsSize) {\n if (right - left + 1 == k) {\n sum = calcXSum(nums, left, right, x);\n \n ans[idx++] = sum;\n sum = 0;\n\n if (idx == *returnSize) break;\n ++left;\n }\n\n ++right;\n }\n\n return ans;\n}\n\n```
0
0
['Array', 'Hash Table', 'C', 'Sliding Window', 'Sorting']
0
find-x-sum-of-all-k-long-subarrays-i
Easy to understand, window + heap || 12 ms 98%
easy-to-understand-window-heap-12-ms-98-w966j
\nres = []\nw = defaultdict(int)\nfor i in nums[:k]: # filling dictionary\n\tw[i] += 1\n\n# 1st w count\nh = [(-frq, -num) for num, frq in w.items()]\nheapq.he
kale111
NORMAL
2024-11-08T23:39:59.994338+00:00
2024-11-08T23:43:28.538901+00:00
58
false
```\nres = []\nw = defaultdict(int)\nfor i in nums[:k]: # filling dictionary\n\tw[i] += 1\n\n# 1st w count\nh = [(-frq, -num) for num, frq in w.items()]\nheapq.heapify(h)\ncnt = x\nsumm = 0\nwhile h and cnt > 0:\n\tfrq, ele = heapq.heappop(h)\n\tsumm += ele * frq\n\tcnt -= 1\nres.append(summ)\n\n# main count & iteration \nfor i in range(k, len(nums)):\n\tnew = nums[i]\n\tif new not in w:\n\t\tw[new] = 1\n\telse:\n\t\tw[new] += 1\n\n\told = nums[i - k]\n\tif w[old] <= 1:\n\t\tdel w[old]\n\telse:\n\t\tw[old] -= 1\n\n\th = [(-frq, -num) for num, frq in w.items()]\n\theapq.heapify(h)\n\tcnt = x\n\tsumm = 0\n\twhile h and cnt > 0:\n\t\tfrq, ele = heapq.heappop(h)\n\t\tsumm += ele * frq\n\t\tcnt -= 1\n\tres.append(summ)\n\nreturn res\n```
0
0
['Sliding Window', 'Python', 'Python3']
0
find-x-sum-of-all-k-long-subarrays-i
Suboptimal solution
suboptimal-solution-by-davidfoss-xbg4
Intuition\n Describe your first thoughts on how to solve this problem. \nWe use the fixed-size sliding window pattern, in addition to using a hash map in order
davidfoss
NORMAL
2024-11-06T01:12:47.940814+00:00
2024-11-06T01:12:47.940852+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use the fixed-size sliding window pattern, in addition to using a hash map in order to keep track of numbers and frequencies. \n\nWe initialize the numbers and frequencies for our first window.\n\nThen we loop for as long as our right pointer is still in our list.\n\nAt each loop, we get our key, value tuples for nums, freqs. We then first sort it by number size, and then by frequency, in decreasing order. We do first by number value, so that in case of draw, we get the largest one. Because next we slice the list at x.\n\nThen we simply iterate through the remaining pairs and sum up the (value*freq)\'s, and append to our sums list.\n\nLastly we update our left and right pointer, remembering to decrease the frequency by one for the number at our left pointer, and adding one to the right pointer.\n\nThen we return our sum.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: Would be O(n), but since we sort, it\'s O(log(n)), but input sizes are at max 50, so thats fine, as 50*log(50) = 85.\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```python []\nclass Solution(object):\n def findXSum(self, nums, k, x):\n """\n :type nums: List[int]\n :type k: int\n :type x: int\n :rtype: List[int]\n """\n lp = 0\n rp = k-1\n freq = {}\n sums = []\n\n for i in range(k):\n if nums[i] in freq:\n freq[nums[i]] += 1\n else:\n freq[nums[i]] = 1\n\n while rp <= len(nums)-1:\n curr_freqs = freq.items()\n curr_freqs.sort(key=lambda x: -x[0])\n curr_freqs.sort(key=lambda x: -x[1])\n curr_freqs = curr_freqs[:x]\n curr_sum = 0\n for num, freq_val in curr_freqs:\n curr_sum += num*freq_val\n sums.append(curr_sum)\n freq[nums[lp]] = max(freq[nums[lp]]-1, 0)\n lp += 1\n rp += 1\n if rp > len(nums)-1:\n return sums\n if nums[rp] in freq:\n freq[nums[rp]] += 1\n else:\n freq[nums[rp]] = 1\n return sums\n```
0
0
['Python']
0
find-x-sum-of-all-k-long-subarrays-i
Simple JavaScript Solution
simple-javascript-solution-by-harsh94664-tgz7
Code\njavascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findXSum = function (nums, k, x
harsh94664
NORMAL
2024-11-04T16:56:59.087946+00:00
2024-11-04T16:56:59.087980+00:00
24
false
# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} x\n * @return {number[]}\n */\nvar findXSum = function (nums, k, x) {\n let result = [];\n\n for (let i = 0; i <= nums.length - k; i++) {\n let temp_arr = [...nums].slice(i, i + k);\n let count = {};\n\n for (let j = 0; j < temp_arr.length; j++) {\n const num = temp_arr[j];\n count[num] = (count[num] || 0) + 1;\n }\n\n console.log(count);\n\n const sum = Object.entries(count)\n .sort((a, b) => {\n if (b[1] !== a[1]) return b[1] - a[1];\n return b[0] - a[0];\n })\n .slice(0, x)\n .reduce((prev, curr) => prev + curr[0] * curr[1], 0);\n\n result.push(sum);\n }\n\n return result;\n};\n```
0
0
['JavaScript']
0
find-x-sum-of-all-k-long-subarrays-i
C++ priority_queue
c-priority_queue-by-kaizhe-qrch
\'\'\'\n\n vector findXSum(vector& nums, int k, int x) {\n vector res;\n int N = nums.size();\n for (int i=0; i<N-k+1; ++i) {\n
kaizhe
NORMAL
2024-11-02T23:07:22.394810+00:00
2024-11-02T23:07:22.394845+00:00
2
false
\'\'\'\n\n vector<int> findXSum(vector<int>& nums, int k, int x) {\n vector<int> res;\n int N = nums.size();\n for (int i=0; i<N-k+1; ++i) {\n // now build the map/pq;\n map<int, int> m;\n priority_queue<pair<int, int>> pq;\n for (int j=i; j<i+k; ++j) {\n m[nums[j]]++;\n }\n for (auto it : m) {\n pq.push({it.second, it.first});\n }\n int sum=0, count=x;\n while (count>0 && !pq.empty()) {\n --count;\n pair<int, int> cur = pq.top();\n pq.pop();\n sum += (cur.first * cur.second);\n }\n res.push_back(sum);\n }\n return res;\n }\n\n\'\'\'
0
0
[]
0
find-x-sum-of-all-k-long-subarrays-i
Python3 O(N ^ 2 log N) Solution with a hash table (97.32% Runtime)
python3-on-2-log-n-solution-with-a-hash-0v9hd
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n\n# Approach\n Describe your approach to solving the problem. \n- Iterate through t
missingdlls
NORMAL
2024-11-02T01:28:39.758559+00:00
2024-11-02T01:28:39.758603+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/412ee493-7609-45f0-81fc-7ba63071b5df_1730510764.429047.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Iterate through the given array with frequency counting via defaultdict.\n- Sort the temporal array from the defaultdict and compute x sum.\n\n# Complexity\n- Time complexity: O(N ^ 2) (n * k * sorting)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) (defaultdict)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\nIf this solution is similar to yours or helpful, upvote me if you don\'t mind\n```python3 []\nclass Solution:\n def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:\n ans=[]\n for i in range(len(nums)-k+1):\n a=0\n d=defaultdict(int)\n for n in nums[i:i+k]:\n d[n]+=1\n\n t=[y for y in d.items()]\n t.sort(key=lambda y: (-y[1],-y[0]))\n\n m=0\n for key,val in t:\n if m==x:\n break\n a+=key*val\n m+=1\n ans.append(a)\n return ans\n```
0
0
['Array', 'Hash Table', 'Sorting', 'Python', 'Python3']
0