🚀 Day 406 of #500DaysOfCode 🎯 Problem: 3318. Find X-Sum of All K-Long Subarrays I 🧩 Difficulty: Easy Today’s challenge focused on computing the X-Sum for every subarray of length k. The X-Sum involves identifying the top X most frequent elements in each subarray — and if frequencies tie, we prioritize larger values. Then, we sum up the occurrences of only those selected elements 💡 💻 Approach: For each subarray of length k, count the frequency of elements. Sort elements by frequency (descending) and value (descending). Pick the top x elements and sum their occurrences in the subarray. Store this result for each subarray. 🧠 Key Concepts Used: Frequency counting using HashMap Custom sorting with comparator logic Sliding subarray analysis 📊 Complexity: O(n × k × log k) 🔍 Topics: Arrays | HashMap | Sorting Every problem solved adds a new pattern to how we think about optimization and logical structuring in code 💪 #Java #LeetCode #ProblemSolving #CodingChallenge #DataStructures #Algorithms #100DaysOfCode #500DaysOfCode
Solved LeetCode 3318: X-Sum of K-Long Subarrays in Java
More Relevant Posts
-
✅Day 46 : Leetcode 69 - Sqrt(x) #60DayOfLeetcodeChallenge 🧩 Problem Statement Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer y should satisfy the condition: y * y <= x < (y + 1) * (y + 1) You must not use any built-in exponent functions such as pow(x, 0.5) or Math.sqrt(x). 💡 My Approach I used a binary search approach to efficiently find the integer square root. The search space is between 1 and x. At each step, I calculate mid and compute val = (long) mid * mid to avoid overflow. If val <= x, I move to the right half (low = mid + 1) and update the answer as mid. If val > x, I move to the left half (high = mid - 1). When the loop ends, ans contains the largest integer whose square is less than or equal to x. ⏱ Time Complexity O(log x) — Binary Search reduces the range by half each time. 💾 Space Complexity O(1) — Constant extra space. #LeetCode69 #BinarySearch #Math #SquareRoot #IntegerSquareRoot #Java #DataStructures #Algorithms #DSA #LeetCodeEasy #ProblemSolving #EfficientCode #OverflowHandling
To view or add a comment, sign in
-
-
🚀 Day 407 of #365DaysOfCode 🎯 Problem: 3321. Find X-Sum of All K-Long Subarrays II 🧩 Difficulty: Hard Today’s challenge took the concept of frequency-based subarray analysis to the next level 🔥 Given an array and two integers k and x, the goal is to compute the X-Sum for every subarray of length k. The X-Sum is calculated by taking the sum of occurrences of the top X most frequent elements in the subarray (with ties broken by larger element value). 💡 Key Idea: Since n can go up to 10⁵, we can’t recompute everything for each subarray. We use a sliding window approach with a HashMap for frequency tracking — efficiently adding and removing elements as the window moves — and compute the X-Sum dynamically. 💻 Approach: 1️⃣ Maintain frequency counts using a HashMap. 2️⃣ Sort by frequency (and value when tied). 3️⃣ Use a sliding window to efficiently update counts instead of recalculating each time. 4️⃣ Compute and store the X-Sum for each window. 📊 Complexity: O(n × log(k)) 🧠 Concepts Used: Sliding Window | HashMap | Greedy Sorting Every hard problem is a reminder that optimization isn’t just about speed — it’s about thinking smart and coding cleaner. 💪 #LeetCode #Java #ProblemSolving #CodingChallenge #Algorithms #DataStructures #100DaysOfCode #365DaysOfCode #SlidingWindow #HashMap
To view or add a comment, sign in
-
-
🚀 Day 145 of #150DaysOfCode on LeetCode 🔹 Problem: 3318. Find X-Sum of All K-Long Subarrays I 🔹 Topic: Sliding Window | HashMap | Sorting Today’s challenge was about computing the X-Sum for every subarray of length k in an array — where the X-Sum is defined as the sum of the top x most frequent elements (considering frequency first and then value). To solve this: I used a sliding window to iterate over all subarrays of size k. For each window, I maintained a frequency map of elements. Then sorted them by frequency (descending) and by value to select the top x contributing elements. Finally, calculated the cumulative X-Sum for each subarray. It was a great exercise in combining maps, sorting logic, and windowing concepts efficiently! 🧩 Key Learnings: How to balance frequency counting with sorting priorities. Importance of optimizing nested loops for small vs. large constraints. Clear understanding of how sorting custom objects impacts runtime. #LeetCode #CodingChallenge #Java #DSA #SlidingWindow #HashMap #ProblemSolving #CodingJourney #100DaysOfCode #WomenInTech #LearnByDoing
To view or add a comment, sign in
-
-
🔥 Day 109 of My DSA Challenge – Intersection of Two Arrays 🔷 Problem : 349. Intersection of Two Arrays 🔷 Goal : Return the unique intersection of two integer arrays. Order doesn’t matter, but duplicates should not appear in the result. 🔷 Key Insight : This is a set / hashmap based lookup problem. We store elements from the first array, then check if elements from the second array exist in it. To ensure uniqueness, we remove the element once counted, so duplicates don't appear. 🔷 Approach : 1️⃣ Add all elements of nums1 to a HashMap 2️⃣ Traverse nums2 3️⃣ If the element exists in the map → add to result & remove from map 4️⃣ Convert list to array and return Time Complexity: O(n + m) Space Complexity: O(n) Sometimes the simplest tools — like HashMaps/Sets — give the cleanest solutions. Learning to choose the right data structure = faster logic + cleaner code 💪 #Day109 #100DaysOfCode #LeetCode #DSA #Java #HashMap #DataStructures #CodingChallenge #Algorithm #ProblemSolving #Programming #SoftwareEngineering #TechJourney #DeveloperJourney #CodeEveryday #LearnDSA #LogicBuilding #GrowthMindset #EngineerMindset
To view or add a comment, sign in
-
👇 📅 Day 80 of #100DaysOfLeetCode Problem: Max Area of Island (LeetCode #695) Approach: Used Depth-First Search (DFS) to explore each connected component (island) in the grid. Iterated through every cell in the grid. When a land cell (1) was found, initiated a DFS to count all connected land cells. Marked visited cells by changing their value (to avoid recounting). Tracked the maximum island area found during the traversal. Returned the largest area after exploring the entire grid. Complexity: ⏱️ Time: O(m × n) — every cell visited once 💾 Space: O(m × n) — recursion stack in the worst case 🔗 Problem Link: https://lnkd.in/dvUNduuZ 🔗 Solution Link: https://lnkd.in/djiVYpfe #LeetCode #100DaysOfCode #DFS #Graph #GridTraversal #MaxAreaOfIsland #FloodFill #CodingChallenge #ProblemSolving #Java #Algorithms #DataStructures #ProgrammingJourney #DailyCoding #BuildInPublic #TechCommunity #CodeEveryday
To view or add a comment, sign in
-
-
#Day_23 💡 Problem Solved: Intersection of Two Arrays Today’s challenge tested my ability to handle array manipulation and two-pointer logic efficiently. 🧩 Problem Overview: Given two integer arrays, the task is to find their intersection — meaning the common elements between both arrays, including duplicates. For example: nums1 = [4,9,5] and nums2 = [9,4,9,8,4] 👉 Output should be [4,9] (since both 4 and 9 appear in both arrays). ⚙️ My Approach: Sorting both arrays: By sorting nums1 and nums2, I was able to efficiently compare elements in a linear scan. Two-pointer technique: I used two indices i and j, starting from 0 in each array. If both elements matched → it’s part of the intersection. If one was smaller → move that pointer ahead to catch up. Storing results dynamically: Added all matching elements into an ArrayList. Finally converted it into an integer array for the result. This approach ensures O(n log n) time complexity due to sorting, but O(n) in space — a solid balance between clarity and performance. 🧠 Key Takeaways: Sorting simplifies complex comparison problems. The two-pointer pattern is extremely useful for dealing with sorted arrays. Always remember: clean logic > brute force. 🔥 Every new problem brings a fresh perspective on optimizing logic and learning better ways to handle data structures. #Java #CodingChallenge #LeetCode #100DaysOfCode #ProblemSolving #DSA #ProgrammingJourney #TechWithMudassir
To view or add a comment, sign in
-
-
💻 Day 62 of #LeetCode100DaysChallenge Solved LeetCode 142: Linked List Cycle II — a problem that deepens understanding of linked list traversal and cycle detection using pointers. 🧩 Problem: Given the head of a linked list, return the node where the cycle begins. If there’s no cycle, return null. A cycle exists if a node can be revisited by continuously following the next pointer. The goal is to identify the exact node where the cycle starts — without modifying the list. 💡 Approach — Floyd’s Cycle Detection (Tortoise and Hare): 1️⃣ Use two pointers — slow and fast. 2️⃣ Move slow by 1 step and fast by 2 steps until they meet (if a cycle exists). 3️⃣ Once they meet, reset one pointer to the head. 4️⃣ Move both one step at a time; the node where they meet again is the start of the cycle. 5️⃣ If no meeting point (i.e., fast or fast.next becomes null), return null. ⚙️ Complexity: Time: O(N) — each pointer traverses the list at most twice. Space: O(1) — no extra memory used. ✨ Key Takeaways: ✅ Strengthened Floyd’s algorithm understanding for detecting and locating cycles. ✅ Learned how mathematical reasoning helps pinpoint the start node of a loop. ✅ Reinforced efficient use of pointer manipulation in linked list problems. #LeetCode #100DaysOfCode #Java #LinkedList #CycleDetection #FloydsAlgorithm #DSA #CodingJourney #WomenInTech #ProblemSolving
To view or add a comment, sign in
-
-
Day 55 of My DSA Challenge Problem: Count the number of triplets in an array that can form a valid triangle. Concept Recap: For any three sides to form a triangle, the sum of any two sides must be greater than the third side. Optimized Approach: Instead of checking every triplet (which takes O(N³)), I sorted the array and used a two-pointer technique to bring it down to O(N²): Sort the array. Fix the largest side (arr[k]) and use two pointers (i, j) to find pairs where arr[i] + arr[j] > arr[k]. If the condition holds, all elements between i and j can form valid triangles. Count and move pointers accordingly. Time Complexity: O(N²) Space Complexity: O(1) Takeaway: Sorting combined with the two-pointer approach often transforms brute-force solutions into elegant and efficient ones. #Day55 #DSAChallenge #TwoPointerTechnique #Sorting #Optimization #Java #ProblemSolving #DataStructures #Algorithms #CodingChallenge #GeeksforGeeks #LeetCode #100DaysOfCode #ProgrammersJourney #TechLearning
To view or add a comment, sign in
-
-
📅 Day 90 of #100DaysOfLeetCode Problem: Smallest String Starting From Leaf (LeetCode #988) Approach: We are given a binary tree where each node stores a value from 0 to 25, representing letters 'a' to 'z'. We must form strings from leaf → root and return the lexicographically smallest one. To solve this: ✅ Use DFS to explore all paths ✅ Convert node values to characters ✅ Build strings from bottom to top ✅ Track the minimum lexicographical string Key Idea: Perform a DFS traversal and store the path characters. Whenever we reach a leaf, reverse the current path (leaf → root order), form a string, and compare it with the current smallest string. Steps: DFS from root to all leaves Maintain list of path characters When at leaf → form & compare the string Return the smallest lexicographical string found Complexity: ⏱️ Time: O(n × h) — exploring all paths & string creation 💾 Space: O(h) — recursion stack & path storage where h = height of tree 🔗 Problem Link: https://lnkd.in/dyuMJ8QK 🔗 Solution Link: https://lnkd.in/d8hgy4N8 #LeetCode #100DaysOfCode #BinaryTree #DFS #TreeTraversal #StringProblems #LexicographicalOrder #DataStructures #Java #Algorithms #ProblemSolving #DailyCoding #CodingChallenge #BuildInPublic #SoftwareEngineering #LearnToCode
To view or add a comment, sign in
-
-
🚀 Day 28 of #100DaysOfCode Today’s challenge was all about understanding frequency patterns in arrays — a simple yet powerful concept in hashing 🔍 LeetCode 1207 – Unique Number of Occurrences 🔢 📌 Problem Summary: Given an integer array, determine whether each value appears a unique number of times. In other words, 👉 No two numbers should share the same frequency. 💡 Example: Input: [1,2,2,1,1,3] Output: true Because frequencies are: 1 → 3 times 2 → 2 times 3 → 1 time All unique ✔️ 🧠 My Approach: I solved it using a combination of HashMap + HashSet: 1️⃣ Count the occurrences of each number using a HashMap. 2️⃣ Insert all frequency values into a HashSet. 3️⃣ If the size of the HashSet equals the size of the map → all frequencies are unique ✔️ 4️⃣ Otherwise → duplicates exist ❌ A clean and efficient hashing technique. ⚙️ Complexity: Time: O(n) ⏱️ Space: O(n) 💾 (storing frequencies) 💡 Key Learning: HashMaps aren’t just for storing counts—they can reveal patterns, validations, and uniqueness constraints when combined with sets. This problem reinforced how frequency-based logic solves many real-world scenarios like: ✔ Detecting duplicates ✔ Comparing patterns ✔ Character/string analysis ✔ Data validation 🔥 Result: Code ran successfully with 0 ms Runtime, accepted on the first attempt! Small challenge, clean logic, satisfying finish 💪 On to the next one! 🚀 #100DaysOfCode #LeetCode #HashTable #Java #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development