🚀 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
Solved LeetCode challenge 3318 using sliding window and HashMap in Java.
More Relevant Posts
-
🚀 Day 87/100 of #100DaysOfCode 💡 Problem: 3321. Find X-Sum of All K-Long Subarrays II (Hard) 🔗 Platform: LeetCode Today’s challenge was all about optimizing sliding window logic with frequency-based ordering! The task — find the “x-sum” of every k-sized subarray, keeping only the top x most frequent elements (and if tied, prefer larger values). 🧠 Key Learnings: How to maintain frequency counts efficiently in a sliding window. Managing top-x elements dynamically using TreeSet and custom comparators. Overcoming TLE issues by switching from naive sorting (O(n*k)) to a balanced TreeSet approach (O(n log n)). ⚙️ Concepts Used: → Sliding Window → Frequency Map (HashMap) → Ordered Sets (TreeSet) → Custom Comparator Logic 🔥 This one really tested both logic & optimization — but once it clicked, it felt amazing! #LeetCode #100DaysOfCode #Java #CodingChallenge #ProblemSolving #DSA #SlidingWindow #Optimization
To view or add a comment, sign in
-
-
💻 Day 34 — LeetCode 912: Sort an Array (Merge Sort Implementation) Today, I learned and implemented Merge Sort, a classic Divide and Conquer algorithm that efficiently sorts arrays with a time complexity of O(n log n). I applied it to LeetCode 912 (Sort an Array) — where the task is to sort an integer array without using built-in sorting methods. This problem helped me understand: How recursion splits the array into halves How merging combines sorted halves Why Merge Sort guarantees stable and consistent performance 🧠 Key takeaway: Merge Sort ensures O(n log n) in all cases (best, average, and worst), making it one of the most reliable sorting algorithms. #LeetCode #Day34 #DSA #SortingAlgorithms #MergeSort #CodingJourney #Java #ProblemSolving
To view or add a comment, sign in
-
-
Day 51 of My DSA Challenge Problem: Count all triplets (i, j, k) in an array such that arr[i] + arr[j] + arr[k] = target Example: Input → arr = [1, 2, 3, 4, 5], target = 9 Output → 2 (Triplets: [1,3,5] and [2,3,4]) My Approach: Instead of using a brute force O(N³) approach, I optimized it using HashMap + Two Loops. Logic Breakdown: Store frequency of all elements (from index 2 onwards) in a HashMap. Fix j, iterate i < j, and calculate target - (arr[i] + arr[j]). If that value exists in the HashMap → it forms valid triplets! After processing each j, reduce the count of future elements to maintain correctness. Time Complexity: O(N²) Space Complexity: O(N) #Day51 #DSAChallenge #HashMap #ProblemSolving #TripletsSum #DSA #CodingChallenge #Java #100DaysOfCode #CodeEveryday #GeeksforGeeks #LeetCode #DataStructures #Algorithms #TwoPointers #DSAwithJava #CodingCommunity #ProgrammingJourney #DeveloperMindset #TechLearning
To view or add a comment, sign in
-
-
Problem: "73. Set Matrix Zeroes" The core of this problem is simple: if a cell is zero, its entire row and column must become zero. But the execution is tricky—you can't modify the matrix while you're still scanning for original zeros! My solution uses a clean, two-pass strategy with auxiliary storage: Pass 1: Use two HashSets to record the indices of rows and columns that contain an initial zero. Pass 2: Iterate again and set any cell to zero if its row or column is present in the HashSets. This approach is highly readable and ensures optimal O(M . N) time complexity. While this solution uses O(M+N) extra space, it's a fantastic baseline. The next step is tackling the O(1) space constraint by cleverly using the matrix's first row and column as the marker sets. That's the real optimization puzzle! #Algorithms #DataStructures #LeetCode #CodingChallenge #Java #SoftwareEngineering #100daysofcode
To view or add a comment, sign in
-
-
🔥 LeetCode Daily Challenge – Day 14 🧩 Problem: 3312. Number of Substrings With One’s Count at Least Square of Zero’s Count 🚀 Approach: Zero-Positions + Prefix Optimization Today’s problem was an interesting blend of math and string analysis. The key insight was recognizing that zero-count grows slowly, and feasible substrings can be efficiently tracked using prefix logic and previous zero positions. ⭐ My approach: Precompute previous zero indices for fast block calculations Track zeros and compute required ones using ones ≥ zeros² Use a mathematical bound (sqrt(n)) to safely prune infeasible ranges Achieved near-linear behavior on large inputs Clean, optimized, and significantly faster than brute force. 💡 This method avoids triple-nested loops and leverages structure in binary strings. 📈 Result: ✔️ Accepted ⚡ Runtime: 115ms (Beats 83.33%) 📦 Memory: 47.07MB (Beats 26.85%) Day 14 streak still going strong! 🔥 #LeetCode #DailyChallenge #Java #DSA #ProblemSolving #DailyCodingChallenge #CodingStreak
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 30 of My #100DaysOfLeetCode Challenge ✅ Problem: Find Target Indices After Sorting Array 🧩 Difficulty: Easy 📂 Category: Array / Counting ⚡ Runtime: 0 ms (Beats 100%) 💾 Memory: 44.54 MB 🔹 Approach: Instead of sorting, I used counting logic to find the number of elements smaller than the target (lessThan) and the count of target elements (count). The resulting indices are then [lessThan, lessThan + 1, ..., lessThan + count - 1]. This avoids unnecessary sorting and keeps the solution O(n). 🧠 Time Complexity: O(n) 💾 Space Complexity: O(1) ✨ Learnings: How counting-based reasoning can replace sorting for index-based problems. Focused on optimization and problem pattern recognition. 📈 Progress: Day 30 ✅ | 70 days remaining 🚀 💭 “Optimization is not about doing more — it’s about doing smarter.” #100DaysOfCode #LeetCode #Java #DSA #ProblemSolving #CodingChallenge #Consistency
To view or add a comment, sign in
-
-
🧠 LeetCode Day 97 — Path Sum (Problem 112) Today’s challenge was about checking whether a binary tree has a root-to-leaf path such that adding up all the values along the path equals a given sum. 🔍 Problem Description: Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that the sum of the node values equals targetSum. Otherwise, return false. 💡 Approach: Traverse the tree recursively. Subtract the current node’s value from targetSum. When a leaf node is reached, check if the remaining sum equals zero. Use Depth First Search (DFS) to explore all paths. 🚀 Key Learnings: Strengthened understanding of recursive tree traversal. Practiced handling base cases in recursion effectively. Improved clarity on root-to-leaf path logic in binary trees. 🌳 #Day97 of #100DaysOfCode Each challenge adds a new layer to my problem-solving skills. Binary tree problems like this sharpen the recursive mindset — thinking from root to leaf and back up! 💪 #LeetCode #CodingChallenge #Java #100DaysOfCode #BinaryTree #ProblemSolving #Recursion
To view or add a comment, sign in
-
-
🌳 Day 60 of 100: Maximum Depth of Binary Tree 🌳 Today’s challenge was LeetCode 104 – Maximum Depth of Binary Tree 🌲 The task? Given the root of a binary tree, find the maximum depth — the number of nodes along the longest path from the root to a leaf node 🍃 💡 Intuition: A binary tree’s depth can be thought of as its “height”. To find it, we just need to know the depth of the left and right subtrees — and the answer is the greater of the two, plus one for the current node. This is a classic example of recursion done right — breaking a big problem into smaller ones that mirror the original. ⏱ Time Complexity: O(n) – visit every node once 🗂 Space Complexity: O(h) – h is the height of the tree (recursion stack) ✨ Key Takeaway: This problem beautifully highlights the power of divide and conquer — by solving smaller subproblems (left and right trees), we can elegantly solve the bigger one. #100DaysOfCode #Day60 #LeetCode #Java #CodingJourney #BinaryTree #Recursion #DataStructures #CodingPractice #ProblemSolving #WomenWhoCode #CodeNewbie #LearnToCode
To view or add a comment, sign in
-
-
📌 Day 15/100 - Majority Element (LeetCode 169) 🔹 Problem: Given an array of integers nums, find the element that appears more than ⌊ n/2 ⌋ times — the majority element. It’s guaranteed that such an element always exists in the array. 🔹 Approach: Implemented the Boyer–Moore Voting Algorithm, a clever and efficient approach: Assume the first element as the candidate. Traverse the array — increment votes if the element matches the candidate, otherwise decrement. If votes reach zero, update the candidate. The last candidate standing is the majority element. 🔹 Time Complexity: O(n) — only one traversal through the array. 🔹 Space Complexity: O(1) — uses constant extra space. 🔹 Key Learnings: Learned how voting logic simplifies counting-heavy problems. Achieved 99.76% faster runtime on LeetCode. Reinforced how simplicity and logic often outperform brute force. 💡 Every dataset has a voice — you just need the right logic to hear it. #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingChallenge #BoyerMooreAlgorithm
To view or add a comment, sign in
-
More from this author
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