How to solve 3318. Find X-Sum of All K-Long Subarrays I

𝐃𝐚𝐲 𝟏𝟏 𝐨𝐟 #50DaysOfDSA Problem: [𝟑𝟑𝟏𝟖. 𝐅𝐢𝐧𝐝 𝐗-𝐒𝐮𝐦 𝐨𝐟 𝐀𝐥𝐥 𝐊-𝐋𝐨𝐧𝐠 𝐒𝐮𝐛𝐚𝐫𝐫𝐚𝐲𝐬 𝐈] 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐋𝐢𝐧𝐤 : https://lnkd.in/gy47HgPN In this problem, we are given an array nums and two integers k and x. We need to find the 𝐗-𝐒𝐮𝐦 for every subarray of length k. How the X-Sum works: 1️⃣ Count how many times each element appears in the subarray. 2️⃣ Keep only the top x most frequent elements if two have the same frequency, the larger element is prioritized. 3️⃣ Sum up all occurrences of those selected elements to get the X-Sum. If the subarray has less than x distinct elements, just take the sum of all its elements. Key learning: This problem beautifully combines HashMap for frequency counting and PriorityQueue (Min Heap) for selecting the top x elements efficiently. It also strengthens understanding of sliding window logic and priority-based data selection in Java. Here’s a quick breakdown from my solution: Used HashMap to store frequency of elements in each subarray Created a custom Pair class and used PriorityQueue to sort by frequency (and element value when frequencies matched) Extracted top x and calculated their contribution to the subarray sum Every day of this challenge helps reinforce logical thinking and pattern recognition — step by step toward stronger DSA foundations! #50DaysOfDSA #LeetCode #Java #ProblemSolving #CodingChallenge #DSA #DataStructures #Algorithms #WomenInTech #KeepLearning #Consistency

  • text

Your daily DSA consistency is truly inspiring keep it up

See more comments

To view or add a comment, sign in

Explore content categories